Oauth2 авторизация
Если нужна "авторизация через {провайдера}" для сайта, можно использовать этот файл. Oauth2 это очень просто, но нудновато... В файле ниже чуть более 100 строк, при этом имеется как всегда, супер отладка скрипта плюс нужные ссылки на статьи и места где можно зарегистрировать приложение в Google и Facebook.
На продакшн DEBUG режим выключен, но авторизацию Oauth не отладить на development инсталляции, поэтому в coresky коде имеется ячейка, которую можно приспосабливать для отладки на production. Включите в админке SKY логирование для идентификатора `oauth`, тогда такие вызовы, как на строке 15 в файле ниже будут логироваться FILO способом (последовательная очередь) в ячейку БД типа `text`. Логирование можно и выключить, если все работает как надо.
На продакшн DEBUG режим выключен, но авторизацию Oauth не отладить на development инсталляции, поэтому в coresky коде имеется ячейка, которую можно приспосабливать для отладки на production. Включите в админке SKY логирование для идентификатора `oauth`, тогда такие вызовы, как на строке 15 в файле ниже будут логироваться FILO способом (последовательная очередь) в ячейку БД типа `text`. Логирование можно и выключить, если все работает как надо.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
class Oauth2
{
private $data = false;
private $tracing = '';
# https://hueniverse.com/oauth-2-0-and-the-road-to-hell-8eec45921529
# https://habr.com/post/150756/
static function run($via) {
global $sky;
$me = new Oauth2($via);
if (is_object($me->data))
$sky->log('oauth', print_r($me->data, 1));
return $me->data;
}
function __construct($via) {
global $sky, $user;
method_exists($this, $provider = "cfg_$via") && !$user->auth or die;
$this->$provider(); # set configuration
$redirect_uri = urlencode("http://coresky.net/auth?via=$via");
# step 0
if (!isset($_GET['code'])) {
$tpl = 'client_id=%s&redirect_uri=%s&state=%s&scope=%s';
$dialog = $this->p0 . sprintf($tpl, $this->app_id, $redirect_uri, $user->v_oauth2 = strand(), $this->scope);
$sky->log('oauth', "\nDIALOG: $dialog\n");
jump($dialog);
}
if (!$user->v_oauth2 || $_GET['state'] != $user->v_oauth2)
return $this->error("$via: CSRF protection |$_GET[state]|, vid=$user->vid", true); # fatal
$user->v_oauth2 = null; # erase, do not required anymore
# step 1
$tpl = 'client_id=%s&redirect_uri=%s&client_secret=%s&code=%s';
$auth = unjson($this->cep($this->p1, sprintf($tpl, $this->app_id, $redirect_uri, $this->secret, $_GET['code'] . $this->fields)));
if (!isset($auth->access_token))
return $this->error("$via: no token");
# step 2
$obj = unjson($this->cep($this->p2 . $auth->access_token)); # GET only
if (!isset($obj->email) || $this->verify && @!$obj->{$this->verify})
return $this->error("$via: email error");
$obj->avatar = $this->$provider($obj);
$this->data = $obj;
}
private function error($desc, $is_fatal = false) {
global $sky;
trace($err = "Oauth2 $desc", true);
$sky->log('oauth', "\n$err\n$this->tracing\n");
if ($is_fatal) # auto-ban may used
throw new Exception($err);
}
# call the end point
private function cep($url, $qs = '') {
if ($post = $this->is_post && $qs) {
$this->tracing .= "\nURL: $url\nPOSTFIELDS:$qs";
} else { # get
$this->tracing .= "\nURL: " . ($url .= $qs); # just append QS
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if ($post) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $qs);
}
$out = curl_exec($curl);
if (curl_errno($curl))
trace(curl_error($curl), true);
curl_close($curl);
$this->tracing .= "\nRESULT: $out";
return $out;
}
# see https://developers.facebook.com/tools/debug/accesstoken
# https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
function cfg_facebook($obj = false) {
if ($obj) # set avatar, no ssl !
return "http://graph.facebook.com/$obj->id/picture";
$this->app_id = '{APP_ID}';
$this->secret = '{APP_SECRET}';
$this->scope = 'email,user_location,user_link,user_hometown,user_gender,user_birthday,user_age_range';
$this->p0 = 'https://www.facebook.com/v3.1/dialog/oauth?';
if (isset($_GET['force']))
$this->p0 .= 'auth_type=rerequest&';
$graph = 'https://graph.facebook.com';
$this->p1 = "$graph/v3.1/oauth/access_token?";
$this->is_post = false;
$this->fields = '';
$this->p2 = "$graph/me?fields=email,name,verified&access_token=";
$this->verify = '';
}
# see https://developers.google.com/accounts/docs/OAuth2WebServer?hl=ru
# register app here: https://code.google.com/apis/console#access
function cfg_google($obj = false) {
if ($obj) # set avatar
return isset($obj->picture) ? $obj->picture : false;
$this->app_id = '{APP_ID}';
$this->secret = '{APP_SECRET}';
$this->scope = 'email%20profile&response_type=code';
$this->p0 = ($google = 'https://accounts.google.com/o/oauth2') . '/auth?';
if (isset($_GET['force']))
$this->p0 .= 'approval_prompt=force&';
$this->p1 = "$google/token";
$this->is_post = true;
$this->fields = "&grant_type=authorization_code";
$this->p2 = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=';
$this->verify = 'verified_email';
}
}
News
7 Jan 2013 GMT Project SKY. started
18 Oct 2018 GMT null-site MVC updated
11 Oct 2018 GMT App MED.CRM.SKY. published.
Articles
SKY. status
Current version: 1.001
Coresky records: 22
Local (DEV) records: 89
Web (all) records: 105
Download: dev.php
Coresky records: 22
Local (DEV) records: 89
Web (all) records: 105
Download: dev.php