Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deploy #6

Merged
merged 7 commits into from
Nov 5, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions application/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,13 @@
* Enable modules. Modules are referenced by a relative or absolute path.
*/
Kohana::modules(array(
// 'auth' => MODPATH.'auth', // Basic authentication
'oauth' => MODPATH.'oauth', // Basic authentication
'cache' => MODPATH.'cache', // Caching with multiple backends
// 'codebench' => MODPATH.'codebench', // Benchmarking tool
'database' => MODPATH.'database', // Database access
'image' => MODPATH.'image', // Image manipulation
'minion' => MODPATH.'minion', // CLI Tasks
// 'orm' => MODPATH.'orm', // Object Relationship Mapping
'minion' => MODPATH.'minion', // CLI Tasks
'orm' => MODPATH.'orm', // Object Relationship Mapping
// 'unittest' => MODPATH.'unittest', // Unit testing
// 'userguide' => MODPATH.'userguide', // User guide and API documentation
// 'email' => MODPATH.'email',
Expand Down
62 changes: 62 additions & 0 deletions application/classes/Controller/Auth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php defined('SYSPATH') OR die('No direct access allowed.');

/**
* Class Controller_Auth
*/
class Controller_Auth extends Controller_Base_preDispatch
{

/**
* Осуществляет авторизацию в ВК. В случае, если пользователь авторизован в первый раз - добавляет новую запись
* в таблицу Users. Модель пользователя помещается в сессию "profile". Далее проиходит редирект на /auth/callback
*/
public function action_vk()
{
$vk = Oauth::instance('vkontakte');
if ($vk->login())
{
$profile = $vk->get_user();
if ($profile)
{
Session::instance()->set('profile', $profile);

$user = DB::select('*')->from('Users')->where('uid', '=', ":uid")->param(":uid", $profile->uid)->execute();
#$user = Model_Users::factory('Users')->where('uid', '=', ":uid")->param(":uid", $profile->uid)->find();
if (!isset($user[0]))
{
DB::insert('Users', array('first_name', 'last_name', 'uid'))->values(array($profile->first_name, $profile->last_name, $profile->uid))->execute();
/*$user = Model_Users::factory('Users');
$user->uid = $profile->uid;
$user->first_name = $profile->first_name;
$user->last_name = $profile->last_name;
$user->save();
*/
}
$this->auth_callback('/');
}
}
else
{
# Add auth error view
$this->auth_callback('/');
}

}

/**
* Деавторизует пользователя путем очищения сессии "profile". Возвращает на главную страницу.
*/
public function action_logout()
{
Session::instance()->delete('profile');
Controller::redirect('/');
}

/**
* Место для пост-авторизации. В конце осуществляет редирект страницу $page.
*/
private function auth_callback($page='/')
{
Controller::redirect($page);
}
}
1 change: 1 addition & 0 deletions application/classes/Controller/Base/preDispatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public function before()

$this->session = Session::instance();

View::set_global('auth', new Dao_Auth());

if ($this->auto_render) {
// Initialize with empty values
Expand Down
25 changes: 25 additions & 0 deletions application/classes/Dao/Auth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php defined('SYSPATH') or die('No direct script access.');

class Dao_Auth extends Dao_Base
{
private $profile;

/**
* Dao_Auth constructor.
*/
public function __construct()
{
$this->profile = Session::instance()->get('profile');
}

public function is_guest()
{
return isset($this->profile);
}

public function get_profile()
{
return $this->profile;
}

}
5 changes: 5 additions & 0 deletions application/classes/Dao/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,9 @@ class Dao_User extends Dao_Base {

protected $table = 'users';

public static function is_guest()
{
return isset(Session::instance()->get('profile'));
}

}
13 changes: 13 additions & 0 deletions application/classes/Model/Users.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php defined('SYSPATH') OR die('No Direct Script Access');

Class Model_Users extends ORM
{
protected $_table_name = 'Users';
protected $_table_columns = array(
'id' => NULL,
'first_name' => NULL,
'last_name' => NULL,
'uid' => NULL
);

}
31 changes: 31 additions & 0 deletions application/config/oauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

defined( 'SYSPATH' ) or die( 'No direct script access.' );

return array(
'vkontakte' => array(
'APP_ID' => '4874439',
'APP_SECRET' => 'w6FvjB8uQDFCNN8n4vCO',
'SETTINGS' => NULL,
'REDIRECT_URI' => 'http://'.Arr::get($_SERVER, 'SERVER_NAME').'/auth/vk',
'GET_CODE_URI' => 'https://oauth.vk.com/authorize/',
'GET_TOKEN_URI' => 'https://oauth.vk.com/access_token'
),
'odnoklassniki' => array(
'APP_ID' => NULL,
'APP_SECRET' => NULL,
'APP_PUBLIC' => NULL,
'SETTINGS' => NULL,
'REDIRECT_URI' => NULL,
'GET_CODE_URI' => NULL,
'GET_TOKEN_URI' => NULL
),
'facebook' => array(
'APP_ID' => NULL,
'APP_SECRET' => NULL,
'SETTINGS' => NULL,
'REDIRECT_URI' => NULL,
'GET_CODE_URI' => NULL,
'GET_TOKEN_URI' => NULL
),
);
4 changes: 2 additions & 2 deletions application/config/social.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
(

'vk' => array(
'VK_APP_ID' => '',
'VK_APP_SECRET' => '',
'VK_APP_ID' => '3642070',
'VK_APP_SECRET' => '6csWQgf0UjhOYKbou16e',
'REDIRECT_URI' => 'http://'.Arr::get($_SERVER, 'SERVER_NAME').'/auth/vk',
'DISPLAY' => 'page', // page OR popup OR touch OR wap
'SCOPE' => array(
Expand Down
13 changes: 5 additions & 8 deletions application/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@
'action' => 'newArticle'
));

#<<<<<<< HEAD


// Scripts for articles

Route::set('ADD_ARTICLE_SCRIPT', 'article/addarticle')->defaults(array(
Expand All @@ -55,9 +52,6 @@
'action' => 'delete'
));




// Scripts for comments

Route::set('ADD_COMMENT_SCRIPT', 'article/addcomment')->defaults(array(
Expand All @@ -69,12 +63,15 @@
'controller' => 'comments',
'action' => 'delete'
));
#=======

Route::set('DESIGN_PREVIEW', 'design/<page>')->defaults(array(
'controller' => 'index',
'action' => 'designPreview'
#>>>>>>> master
));

Route::set('AUTH', 'auth/<action>')->defaults(array(
'controller' => 'auth',
'action' => 'action'
));

// Defaults
Expand Down
13 changes: 13 additions & 0 deletions application/views/templates/index.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
<div class="header_text">
<?php if ($auth->is_guest()): ?>
Добрый день, <?= $auth->get_profile()->first_name; ?>
<?php endif; ?>
</div>

<div class="m_logo_wrap">
<div class="m_logo"></div>
<a href="/article">Статьи</a>
<a href="/join">Подать заявку</a>
<a href="/task">Задания</a>

<?php if (!$auth->is_guest()): ?>
<a href='/auth/vk'>Вход VK</a>
<?php else: ?>
<a href='/auth/logout'>Выход</a>
<?php endif; ?>

</div>
9 changes: 9 additions & 0 deletions migrations/05_11_2015_01_Users_model.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS `Users` (
`id` int(11) NOT NULL,
`first_name` tinytext NOT NULL,
`last_name` tinytext NOT NULL,
`uid` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

ALTER TABLE `Users`
ADD PRIMARY KEY (`id`);
13 changes: 13 additions & 0 deletions modules/oauth/classes/Kohana/Oauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php defined('SYSPATH') or die('No direct script access.');

abstract class Kohana_Oauth {

protected static $instance;

public static function instance($service)
{
$config = Kohana::$config->load('oauth');
$class = 'Oauth_' . ucfirst($service);
return Kohana_Oauth::$instance = new $class($config -> get($service));
}
}
98 changes: 98 additions & 0 deletions modules/oauth/classes/Kohana/Oauth/Vkontakte.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php defined('SYSPATH') or die('No direct script access.');

class Kohana_Oauth_Vkontakte extends Oauth {

protected static $config;

public function __construct($config)
{
//var_dump($config);
//die();
self::$config = $config;
}

public function login_query()
{
$params = array(
'client_id' => self::$config['APP_ID'],
'scope' => self::$config['SETTINGS'],
'redirect_uri' => self::$config['REDIRECT_URI'],
'response_type' => 'code'
);
return self::$config['GET_CODE_URI'].'?'.http_build_query($params);
}

// @param code sended at backref
private function get_access_token()
{
$params = Arr::get($_SERVER, 'QUERY_STRING');

// http://www.php.net/manual/ru/function.parse-str.php
// parse_str($input_string, $output_array)
parse_str($params, $params);

// if we on 1st step -> go to authorization page
if ( empty($params['code']) )
{
Controller::redirect($this->login_query());
}

if (!$params)
{
throw new Kohana_Exception('NO QUERY PARAMS');
}

if (isset($error))
throw new Kohana_Exception('Error: '.$error.' Description: '.$error_description);
$params = array(
'client_id' => self::$config['APP_ID'],
'code' => $params['code'],
'client_secret' => self::$config['APP_SECRET'],
'redirect_uri' => self::$config['REDIRECT_URI']
);
$resp = Request::factory(self::$config['GET_TOKEN_URI'])
->method('GET')
->query($params)
->execute();

$resp = json_decode($resp);
if (empty($resp->access_token))
{
throw new Kohana_Exception('Error: '.$resp->error.' Description: '.$resp->error_description);
}
Session::instance()->set('vk_token', $resp->access_token);
Session::instance()->set('vk_user_id', $resp->user_id);
return true;
}

public function get_user()
{
$vk_token = Session::instance()->get('vk_token');
$vk_user_id = Session::instance()->get('vk_user_id');
if(!$vk_token || !$vk_user_id)
{
throw new Kohana_Exception('Невозможно получить токен и id');
}
$params = array(
'uid' => $vk_user_id,
'access_token' => $vk_token
);
$resp = Request::factory('https://api.vk.com/method/users.get')
->method('GET')
->query($params)
->execute();
$resp = json_decode($resp);
if (isset($resp->error))
{
throw new Kohana_Exception('Error: '.$resp->error.' Description: '.$resp->error_description);
}
$profile = array_shift($resp->response);
return $profile;
}

public function login()
{
return $this->get_access_token();
}

}
3 changes: 3 additions & 0 deletions modules/oauth/classes/Oauth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php defined('SYSPATH') or die('No direct script access.');

abstract class Oauth extends Kohana_Oauth { }
3 changes: 3 additions & 0 deletions modules/oauth/classes/Oauth/Vkontakte.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php defined('SYSPATH') or die('No direct script access.');

class Oauth_Vkontakte extends Kohana_Oauth_Vkontakte { }