RoutesAuthDBI/OAuth.pm untested

filter: Statementstmt 0.0% 0 / 147 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 89 MC/DCmcdc 0.0% 0 / 45 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 339 CC 20 SCAR 37.0
CC
20
Cov
0%
login
72.0
_process_profile_tx
72.0
oauth_profile
12.0
CRAP 40.3
1 package Mojolicious::Plugin::RoutesAuthDBI::OAuth;
2 use Mojo::Base 'Mojolicious::Controller';
3 use Mojolicious::Plugin::RoutesAuthDBI::Util qw(json_enc json_dec);#load_class
4 use Hash::Merge qw( merge );
5 use Digest::MD5 qw(md5_hex);
6  
7 my ($Init);
8 has [qw(app plugin )], undef, weak=>1;
9 has [qw(controller namespace model)]
10  
11 # state here for init and many news
12 #~ has model => sub { shift->_model};
13 #~ sub _model { state $model = load_class('Mojolicious::Plugin::RoutesAuthDBI::Model::OAuth')->new }
14  
15 has _providers => sub {# default
16 {
17 vkontakte => {
18 authorize_url => "https://oauth.vk.com/authorize",
19 authorize_query => {display=>'page', response_type=>'code', v=>'5.52',},#&scope=friends
20 token_url => "https://oauth.vk.com/access_token",
21 profile_url => 'https://api.vk.com/method/users.get',#?user_ids=260362925&v=5.52&access_token=...
22 profile_query => sub {
23 my ($c, $auth, ) = @_;
24 {
25 access_token=>$auth->{access_token},
26 fields=>'photo_100',
27 };
28 },
29 profile_avatar =>'photo_100',
30 },
31 google=>{# обязательно redirect_url
32 scope=>'profile',
33 profile_url=> 'https://www.googleapis.com/oauth2/v1/userinfo',
34 profile_query => sub {
35 my ($c, $auth, ) = @_;
36 {
37 alt => 'json',
38 access_token => $auth->{access_token},
39 };
40 },
41 profile_avatar =>'picture',
42 },
43 yandex=>{# обязательно redirect_url
44 authorize_url=>"https://oauth.yandex.ru/authorize",
45 authorize_query => {force_confirm=>1, response_type=>'code',},# state=>
46 token_url => "https://oauth.yandex.ru/token",
47 profile_url=> "https://login.yandex.ru/info",
48 profile_query => sub {
49 my ($c, $auth, ) = @_;
50 {
51 format => 'json',
52 oauth_token=> $auth->{access_token},
53 };
54 },
55 # "default_avatar_id": "458/1266-1543797358",
56 profile_avatar =>'default_avatar_id',# appRoutes!!
57 },
58 mailru => {
59 authorize_url=>"https://connect.mail.ru/oauth/authorize?response_type=code",
60 token_url => "https://connect.mail.ru/oauth/token",
61 profile_url=> "https://www.appsmail.ru/platform/api",
62 profile_query => sub {
63 my ($c, $auth, ) = @_;
64 my $param = {
65 method=>'users.getInfo',
66 app_id=>$Init->config->{mailru}{key},
67 session_key=>$auth->{access_token},
68 #~ uids=>$auth->{x_mailru_vid},
69 secure=>1,
70 };
71 $param->{sig} = md5_hex map("$_=$param->{$_}", sort keys %$param), $Init->config->{mailru}{secret};
72 $param;
73 },
74 profile_avatar =>'pic_small',
75  
76 }
77 }
78
79 };
80  
81 has config => sub {# только $Init ! имя providers уже занято
82 my $self = shift;
83
84 while (my ($name, $val) = each %{$self->{providers}}) {
85 my $site = $self->model->site( json_enc($val), $name,);
86 @$val{qw(id)} = @$site{qw(id)};
87 $val->{name} = $name;
88 }
89 merge $self->{providers}, $self->_providers;
90 };
91  
92 has curr_profile => sub { shift->${ \$Init->plugin->merge_conf->{auth}{current_user_fn} };};
93  
94 has ua => sub {shift->app->ua->connect_timeout(30);};
95  
96 #~ sub curr_profile { shift->${ \$Init->plugin->merge_conf->{auth}{current_user_fn} };};
97  
98 sub init {# from plugin
99 state $self = shift->SUPER::new(@_);
100
101 die "Plugin OAuth2 already loaded"
102 if $self->app->renderer->helpers->{'oauth2.get_token'};
103
104 #~ $self->app->log->debug($self->app->dumper($self->config));
105 $self->app->plugin("OAuth2::Che" => $self->config);
106
107 $Init = $self;
108 return $self;
109
110 }
111  
112 sub login {
113 my $c = shift;
114
115 my $referrer = $c->req->headers->referrer && Mojo::URL->new($c->req->headers->referrer)->path || 'profile';
116 my $redirect = $c->param('redirect') || $referrer;
117
118 my $site_name = $c->stash('site');
119  
120 my $site = $c->oauth2->providers->{$site_name}
121 or return $c->redirect_to($c->url_for($referrer)->query(error=> "No such oauth provider [$site_name]"));
122 #~ or return $c->render('profile/index', err=>);
123
124 if (my @fatal = grep !defined $site->{$_}, qw(id key secret authorize_url token_url profile_url profile_query)) {
125 #~ die "OAuth provider [$site_name] does not configured: [@fatal] is not defined";
126 return $c->redirect_to($c->url_for($referrer)->query(error=> "OAuth provider [$site_name] does not configured: [@fatal] is not defined"));
127 }
128
129 my $curr_profile = $c->curr_profile;
130
131 my $r; $r = $Init->model->check_profile($curr_profile->{id}, $site->{id})
132 and $c->app->log->warn("Попытка двойной авторизации сайта $site_name", $c->dumper($r), "профиль: ", $c->dumper($curr_profile),)
133 #~ and return $c->redirect_to($c->url_for(${ delete $c->session->{oauth_init} }{redirect})->query(err=> "Уже есть авторизация сайта $site_name"))
134 and return $c->redirect_to($c->url_for($referrer)->query(error=> "Уже есть авторизация сайта $site_name"))
135 if $curr_profile;
136
137 $c->session(oauth_init => {
138 site => $site_name,
139 referrer => $referrer, # failback
140 redirect => $redirect, # success
141 })
142 unless $c->session('oauth_init');
143  
144 $c->delay(
145 sub { # шаг авторизации
146 my $delay = shift;
147 my $args = {
148 redirect_uri => $c->url_for('oauth-login', site=>$site_name)->userinfo(undef)->to_abs,
149 $site->{authorize_query} ? (authorize_query => $site->{authorize_query}) : (),
150 };
151 $c->oauth2->get_token($site_name => $args, $delay->begin);
152 },
153 sub {# ну-ка профиль
154 my ($delay, $err, $auth) = @_;
155 $err .= json_enc($auth->{error})
156 if $auth->{error};
157
158 $c->app->log->error("Автоизация $site_name:", $err, $c->dumper($auth))
159 #~ and return $c->$fail_auth_cb()
160 and return $c->redirect_to($c->url_for(${ delete $c->session->{oauth_init} }{referrer})->query(error=> $err." Нет access_token"))
161 unless $auth->{access_token};
162
163 my $url = Mojo::URL->new($site->{profile_url})->query($c->${ \$site->{profile_query} }($auth));
164
165 $c->ua->get($url, $delay->begin);
166 $delay->pass($auth);
167 },
168 sub {# профиль сайта получен
169 my ($delay, $tx, $auth) = @_;
170
171 my $profile = $c->_process_profile_tx($site, $auth, $tx);
172
173 #~ $c->session(oauth_err => $profile)
174 #~ and
175 my $oauth_init = delete $c->session->{oauth_init};
176 return $c->redirect_to($c->url_for($oauth_init->{referrer})->query(error=> $profile, site=>$oauth_init->{site}))#
177 unless ref $profile;
178  
179 return $c->redirect_to($c->url_for($oauth_init->{redirect}));#
180 #~ $c->redirect_to(${ delete $c->session->{oauth_init} }{redirect});
181 },
182 ); # end delay
183
184 }
185  
186 sub _process_profile_tx {# $auth->{conflict} = 'old' нужен для мобильного приложения в редактировании привязок к сайтам, т.е. не допустить использования внешнего профиля привязанного в другом аккаунте
187 my $c = shift;
188 my ($site, $auth, $tx) = @_;
189 my $curr_profile = $c->curr_profile;
190 if (my $auth_cookie = delete $auth->{auth_cookie}) {
191 $curr_profile ||= $c->access->auth_cookie($c, $auth_cookie);
192 }
193 my ($data, $err) = $c->oauth2->process_tx($tx);
194 $err .= json_enc($data->{error})
195 if ref($data) eq 'HASH' && $data->{error};
196 $c->app->log->error("Ошибка профиля сайта $site->{name}:", $err, $tx->req->url, $c->dumper($tx->res), $c->dumper($data),)
197 and return $err
198 if $err;
199
200 $data = $data->{response}
201 if ref($data) eq 'HASH' && $data->{response};
202 $data = shift @$data
203 if ref $data eq 'ARRAY';
204 @$data{keys %$auth} = values %$auth;
205
206 my @bind = (json_enc($data), $site->{id}, $auth->{uid} || $auth->{user_id} || $data->{uid} || $data->{id} || $data->{user_id});
207
208 my $oau = $Init->model->user(@bind);
209
210 $c->app->log->error("Конфликт использования внешнего профиля, уже привязан в другом профиле")
211 #~ and return "Вход на сайт через [$site->{name}] пользователя #$oau->{user_id} уже используется. Невозможно привязать дважды. Можно <a href='/logout?redirect=@{[$c->url_for('oauth-login', site=>$site->{name})]}' class='relogin'>переключиться</a> на этот вход."
212 and return 'CONFLICT'
213 if $oau->{old} && $curr_profile;
214
215 my $profile =
216
217 $curr_profile
218
219 || $Init->model->profile($oau->{id}) # по внешнему профилю получить наш профиль
220  
221 || $Init->plugin->model('Profiles')->new_profile([$data->{first_name} || $data->{given_name}, $data->{last_name} || $data->{family_name},]);
222
223
224 $c->authenticate(undef, undef, $profile) # session only store
225 unless $curr_profile;
226
227 my $r = $Init->plugin->model('Refs')->refer($profile->{id}, $oau->{id},);
228
229 return $profile;
230
231 }
232  
233  
234 sub oauth_profile {# получить по access_token
235 my $c = shift;
236 my $site_name = $c->stash('site');
237 my $site = $c->oauth2->providers->{$site_name}
238 or return $c->render(json=>{error=>"No such oauth provider [$site_name]"});
239 my $auth = $c->req->json
240 or return $c->render(json=>{error=>"Must send JSON auth data"});
241 return $c->render(json=>{ error=>"JSON data access_token not defined"})
242 unless $auth->{'access_token'};
243
244 $c->delay(
245 sub {# ну-ка профиль
246 my ($delay) = @_;
247
248 my $url = Mojo::URL->new($site->{profile_url})->query($c->${ \$site->{profile_query} }($auth));
249
250 $c->ua->get($url, $delay->begin);
251 #~ $delay->pass($auth);
252 },
253 sub {# профиль сайта получен
254 my ($delay, $tx,) = @_;
255
256 my $profile = $c->_process_profile_tx($site, $auth, $tx);
257
258 return $c->render(json=>{ error=>$profile })
259 unless ref $profile;
260
261 #~ $c->authenticate(undef, undef, $profile) # mobile app
262 #~ unless $c->curr_profile;
263
264 my $ou = $Init->model->oauth_users_by_profile($profile->{id});
265 my $oprofile = json_dec $ou->{$site_name}{profile};
266 delete @$oprofile{qw(user_id access_token expires_in token_type refresh_token id_token)};
267 $c->render(json=>$oprofile);
268 },
269 );
270
271 }
272  
273 sub detach {# отсоединить
274 my $c = shift;
275 my $referrer = $c->req->headers->referrer && Mojo::URL->new($c->req->headers->referrer)->path || 'profile';
276 my $redirect = $c->param('redirect') || $referrer;
277 my $site_name = $c->stash('site');
278
279 my $is_post = uc($c->req->method) eq 'POST';
280  
281 my $site = $c->oauth2->providers->{$site_name}
282 or ($is_post && return $c->render(json=>{error =>"No such oauth provider [$site_name]"}))
283 or return $c->redirect_to($c->url_for($referrer)->query(error => "No such oauth provider [$site_name]"));
284
285 my $curr_profile = $c->curr_profile;
286
287 my $r = $Init->model->detach($site->{id}, $curr_profile->{id},);
288 #~ $c->app->log->debug("Убрал авторизацию сайта [$site_name] профиля [$curr_profile->{id}]", $c->dumper($r));
289
290 $Init->plugin->model('Refs')->del($r->{ref_id}, undef, undef);
291
292 $is_post && return $c->render(json=>{success=>"detach [$site_name]"});
293
294 #~ my $redirect = $c->param('redirect') || ($c->req->headers->referrer && Mojo::URL->new($c->req->headers->referrer)->path) || 'profile';
295 return $c->redirect_to($redirect);
296 }
297  
298 #~ sub out {# выход
299 #~ my $c = shift;
300 #~ $c->logout;
301 #~ $c->redirect_to($c->param('redirect') || '/');
302 #~ }
303  
304 sub _routes {# from plugin!
305 my $self = shift;
306
307 return (
308
309 {request=>'/oauth/login/:site',
310 namespace => $Init->namespace,
311 controller => $Init->controller,
312 action => 'login',
313 name => 'oauth-login',
314 },
315 {request=>'POST /oauth/profile/:site',
316 namespace => $Init->namespace,
317 controller => $Init->controller,
318 action => 'oauth_profile',
319 name => 'oauth profile',
320 },
321 {request=>'/oauth/detach/:site',
322 namespace => $Init->namespace,
323 controller=>$Init->controller,
324 action => 'detach',
325 name => 'oauth-detach',
326 auth=>'only',
327 },
328 {request=>'GET /oauth/data',
329 namespace => $Init->namespace,
330 controller=>$Init->controller,
331 action => 'oauth_data',
332 name => 'oauth data',
333 },
334
335 #~ {request =>'/logout',
336 #~ namespace => $Init->namespace,
337 #~ controller => $Init->controller,
338 #~ action => 'out',
339 #~ name => 'logout',
340 #~ },
341 {request =>'/'.$Init->plugin->admin->trust."/oauth/conf",
342 namespace => $Init->namespace,
343 controller => $Init->controller,
344 action => 'conf',
345 name => 'oauth-conf',
346 }
347
348 );
349
350 }
351  
352 sub conf {
353 my $c = shift;
354 $c->render(format=>'txt', text=>
355 "PROVIDERS\n---\n"
356 . $c->dumper(($c->oauth2->providers))
357 );
358 }
359  
360 sub oauth_data {
361 my $c = shift;
362 my $uid = $c->curr_profile && $c->curr_profile->{id};
363 my $ou = $uid && $Init->model->oauth_users_by_profile($uid);
364
365 my @data = map {
366 my %site = %$_;
367 delete @site{qw(secret profile_query authorize_url token_url profile_url authorize_query scope)};
368 if ($ou) {# already authenticate
369 my $oauth = $ou->{$site{name}} || {};# по имени сайта
370 my $profile = $oauth->{profile};
371
372 $site{profile} = json_dec($profile)
373 #~ and delete(@$oauth{qw(ts profile_ts)})
374 and delete (@{$site{profile}}{qw(user_id access_token id_token expires_in token_type refresh_token)})
375 if $profile;
376 } else {# needs authenticate
377 #~ $site{authenticate}=1;
378 }
379
380 #~ $oauth->{site_name} ||= $_->{name};
381 #~ $oauth; # || {}
382 \%site;
383
384 } grep($_->{id}, values %{$c->oauth2->providers});
385
386 $c->render(json=>\@data);
387 }
388  
389 1;
390  
391 =pod
392  
393 =encoding utf8
394  
395 Доброго всем
396  
397 =head1 Mojolicious::Plugin::RoutesAuthDBI::OAuth
398  
399 ¡ ¡ ¡ ALL GLORY TO GLORIA ! ! !
400  
401 =head1 NAME
402  
403 Mojolicious::Plugin::RoutesAuthDBI::OAuth - is a Mojolicious::Controller for oauth2 logins to project. Its has two route: for login and logout.
404  
405 =head1 DB DESIGN DIAGRAM
406  
407 See L<https://github.com/mche/Mojolicious-Plugin-RoutesAuthDBI/blob/master/Diagram.svg>
408  
409 =head1 SYNOPSIS
410  
411 $app->plugin('RoutesAuthDBI',
412 ...
413 oauth => {< hashref options list below >},
414 ...
415 );
416  
417 =head2 OPTIONS
418  
419 =head3 namespace
420  
421 Namespace (string). Defaults to 'Mojolicious::Plugin::RoutesAuthDBI'.
422  
423 =head3 controller
424  
425 Module controller name. Defaults to 'OAuth'.
426  
427  
428 =head3 providers
429  
430 Hashref for key/value per each need provider. Required.
431  
432 providers => {google=>{key=> ..., secret=>..., }, ...},
433  
434 See L<Mojolicious::Plugin::OAuth2>. But two additional parameters (keys of provider hash) are needs:
435  
436 =head4 profile_url
437  
438 Abs url string to fetch profile info after success oauth.
439  
440 profile_url=> 'https://www.googleapis.com/oauth2/v1/userinfo',
441  
442 =head4 profile_query
443  
444 Coderef which prepare additional query params for C<profile_url>
445  
446 Example for google:
447  
448 profile_query => sub {
449 my ($c, $auth, ) = @_;
450 {
451 alt => 'json',
452 access_token => $auth->{access_token},
453 };
454 },
455  
456 In: $auth hash ref with access_token.
457  
458 Out: hashref C<profile_url> query params.
459  
460 =head3 tables
461  
462 Hashref of any DB tables names. See L<Mojolicious::Plugin::RoutesAuthDBI::Schema#Default-variables-for-SQL-templates>.
463  
464 =head2 Defaults options for oauth:
465  
466 oauth = > {
467 namespace => 'Mojolicious::Plugin::RoutesAuthDBI',
468 module => 'OAuth',
469 },
470  
471 disable oauth module
472
473 oauth => undef,
474
475  
476 =head1 METHODS NEEDS IN PLUGIN
477  
478 =head2 _routes()
479  
480 This oauth controller routes. Return array of hashrefs routes records for apply route on app. Plugin internal use.
481  
482 =head1 ROUTES
483  
484 There are number of app routes on this controller:
485  
486 =head2 /oauth/login/:site
487  
488 Main route of this controller. Stash B<site> is the name of the hash key of the C<providers> config above. Example html link:
489  
490 <a href="<%= $c->url_for('oauth-login', site=> 'google')->query(redirect=>'profile') %>">Login by google</a>
491  
492 This route has builtin name 'oauth-login'. This route accept param 'redirect' and will use for $c->redirect_to after success oauith and also failed oauth clauses with param 'err'.
493  
494 =head2 /oauth/detach/:site
495  
496 Remove attached oauth user to profile. Stash B<site> and param 'redirect' as above. Route has builtin name 'oauth-detach'.
497  
498 =head2 /oauth/data
499  
500 Get remote oauth data site only configured.
501  
502 =head2 POST /oauth/profile/:site
503  
504 Usefull for cordova mobile app oauth connect.
505  
506 IN: json data C<{access_token=>"..."}> that got from oauth B<authorize_url> API request.
507  
508 OUT: stored remote oauth API profile.
509  
510 =head2 <trust admin option>/oauth/conf
511  
512 The L<Mojolicious::Plugin::RoutesAuthDBI::Admin/"trust"> option.
513  
514 Returns text dump current hash of L<Mojolicious::Plugin::OAuth2/"providers">.
515  
516 =head1 SEE ALSO
517  
518 L<Mojolicious::Plugin::RoutesAuthDBI>
519  
520 L<Mojolicious::Plugin::RoutesAuthDBI::Admin>
521  
522 =head1 AUTHOR
523  
524 Михаил Че (Mikhail Che), C<< <mche [on] cpan.org> >>
525  
526 =head1 BUGS / CONTRIBUTING
527  
528 Please report any bugs or feature requests at L<https://github.com/mche/Mojolicious-Plugin-RoutesAuthDBI/issues>. Pull requests also welcome.
529  
530 =head1 COPYRIGHT
531  
532 Copyright 2016 Mikhail Che.
533  
534 This library is free software; you can redistribute it and/or modify
535 it under the same terms as Perl itself.
536  
537 =cut
538