Yancy/Plugin/Auth/OAuth2.pm

filter: Statementstmt 34.1% 27 / 79 Branchbran 0.0% 0 / 14 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 27.7% 5 / 18 Podpod 83.3% 5 / 6 totaltotal 27.0% 37 / 137 CC 15 SCAR 30.2
CC
15
Cov
25%
_handle_auth
56.0
init
30.0
_handle_logout
20.0
CRAP 20.5
« Yancy/Plugin/Auth/Role/RequireUser.pm ↑ Summary Yancy/Plugin/Auth/Github.pm »
1 package Yancy::Plugin::Auth::OAuth2;
2 3 our $VERSION = '1.078';
3 # ABSTRACT: Authenticate using an OAuth2 provider
4  
5 #pod =head1 SYNOPSIS
6 #pod
7 #pod use Mojolicious::Lite;
8 #pod plugin Yancy => {
9 #pod backend => 'sqlite://myapp.db',
10 #pod };
11 #pod app->yancy->plugin( 'Auth::OAuth2' => {
12 #pod client_id => 'CLIENT_ID',
13 #pod client_secret => 'SECRET',
14 #pod authorize_url => 'https://example.com/auth',
15 #pod token_url => 'https://example.com/token',
16 #pod } );
17 #pod
18 #pod =head1 DESCRIPTION
19 #pod
20 #pod This module allows authenticating using a standard OAuth2 provider by
21 #pod implementing L<the OAuth2 specification|https://tools.ietf.org/html/rfc6749>.
22 #pod
23 #pod OAuth2 provides no mechanism for transmitting any information about the
24 #pod user in question, so this auth may require some customization to be
25 #pod useful. Without some kind of information about the user, it is
26 #pod impossible to know if this is a new user or a returning user or to
27 #pod maintain any kind of account information for the user.
28 #pod
29 #pod This module composes the L<Yancy::Auth::Plugin::Role::RequireUser> role
30 #pod to provide the
31 #pod L<require_user|Yancy::Auth::Plugin::Role::RequireUser/require_user>
32 #pod authorization method.
33 #pod
34 #pod =head1 CONFIGURATION
35 #pod
36 #pod This plugin has the following configuration options.
37 #pod
38 #pod =head2 client_id
39 #pod
40 #pod The client ID, provided by the OAuth2 provider.
41 #pod
42 #pod =head2 client_secret
43 #pod
44 #pod The client secret, provided by the OAuth2 provider.
45 #pod
46 #pod =head2 authorize_url
47 #pod
48 #pod The URL to start the OAuth2 authorization process.
49 #pod
50 #pod =head2 token_url
51 #pod
52 #pod The URL to get an access token. The second step of the auth process.
53 #pod
54 #pod =head2 login_label
55 #pod
56 #pod The label for the button to log in using this OAuth2 provider. Defaults
57 #pod to C<Login>.
58 #pod
59 #pod =head2 Sessions
60 #pod
61 #pod This module uses L<Mojolicious
62 #pod sessions|https://mojolicious.org/perldoc/Mojolicious/Controller#session>
63 #pod to store the login information in a secure, signed cookie.
64 #pod
65 #pod To configure the default expiration of a session, use
66 #pod L<Mojolicious::Sessions
67 #pod default_expiration|https://mojolicious.org/perldoc/Mojolicious/Sessions#default_expiration>.
68 #pod
69 #pod use Mojolicious::Lite;
70 #pod # Expire a session after 1 day of inactivity
71 #pod app->sessions->default_expiration( 24 * 60 * 60 );
72 #pod
73 #pod =head1 HELPERS
74 #pod
75 #pod This plugin has the following helpers.
76 #pod
77 #pod =head2 yancy.auth.current_user
78 #pod
79 #pod Get the current user from the session, if any. Returns C<undef> if no
80 #pod user was found in the session.
81 #pod
82 #pod my $user = $c->yancy->auth->current_user
83 #pod || return $c->render( status => 401, text => 'Unauthorized' );
84 #pod
85 #pod =head2 yancy.auth.require_user
86 #pod
87 #pod Validate there is a logged-in user and optionally that the user data has
88 #pod certain values. See L<Yancy::Plugin::Auth::Role::RequireUser/require_user>.
89 #pod
90 #pod # Display the user dashboard, but only to logged-in users
91 #pod my $auth_route = $app->routes->under( '/user', $app->yancy->auth->require_user );
92 #pod $auth_route->get( '' )->to( 'user#dashboard' );
93 #pod
94 #pod =head2 yancy.auth.login_form
95 #pod
96 #pod Returns the rendered login button.
97 #pod
98 #pod Login with OAuth2:
99 #pod %= $c->yancy->auth->login_form
100 #pod
101 #pod =head2 yancy.auth.logout
102 #pod
103 #pod Log out any current account from any auth plugin. Use this in your own
104 #pod route handlers to perform a logout.
105 #pod
106 #pod =head1 TEMPLATES
107 #pod
108 #pod To override these templates, add your own at the designated path inside
109 #pod your app's C<templates/> directory.
110 #pod
111 #pod =head2 yancy/auth/oauth2/login_form.html.ep
112 #pod
113 #pod Display the button to log in using this OAuth2 provider.
114 #pod
115 #pod =head2 layouts/yancy/auth.html.ep
116 #pod
117 #pod The layout that Yancy uses when displaying the login form, the
118 #pod unauthorized error message, and other auth-related pages.
119 #pod
120 #pod =head1 SEE ALSO
121 #pod
122 #pod L<Yancy::Plugin::Auth>
123 #pod
124 #pod =cut
125  
126 3 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=0.0
127 3 ▶use Role::Tiny::With;
Subroutine BEGIN: called CC=1 SCAR=0.0
128 3 with 'Yancy::Plugin::Auth::Role::RequireUser';
129 3 ▶use Yancy::Util qw( currym match );
Subroutine BEGIN: called CC=1 SCAR=0.0
130 3 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
131 3 ▶use Mojo::URL;
Subroutine BEGIN: called CC=1 SCAR=0.0
132  
133 0 ▶has ua => sub { Mojo::UserAgent->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
134 3 has route =>;
135 3 has moniker => 'oauth2';
136 3 has client_id =>;
137 3 has client_secret =>;
138 3 has authorize_url =>;
139 3 has token_url =>;
140 3 has login_label => 'Login';
141 3 has logout_route =>;
142  
143 sub register {
144 my ( $self, $app, $config ) = @_;
145 $self->init( $app, $config );
146 $app->helper(
147 'yancy.auth.current_user' => currym( $self, 'current_user' ),
148 );
149 $app->helper(
150 'yancy.auth.logout' => currym( $self, 'logout' ),
151 );
152 $app->helper(
153 'yancy.auth.login_form' => currym( $self, 'login_form' ),
154 );
155 }
156  
157 sub init {
158 0 ▶ my ( $self, $app, $config ) = @_;
Subroutine init: not called CC=5 SCAR=34.0
Pod undocumented
159 0 for my $attr ( qw( moniker ua client_id client_secret login_label ) ) {
160 0 ▶ next if !$config->{ $attr };
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{$attr} 0 0 0
161 0 $self->$attr( $config->{ $attr } );
162 }
163 0 for my $url_attr ( qw( authorize_url token_url ) ) {
164 0 ▶ next if !$config->{ $url_attr };
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{$url_attr} 0 0 0
165 0 $self->$url_attr( Mojo::URL->new( $config->{ $url_attr } ) );
166 }
167 $self->route(
168 $app->yancy->routify(
169 $config->{route},
170 0 '/yancy/auth/' . $self->moniker,
171 )
172 );
173 0 $self->route->get( '' )->to( cb => currym( $self, '_handle_auth' ) );
174 0 $self->logout_route(
175 $self->route->get( '/logout' )->to( cb => currym( $self, '_handle_logout' ) )
176 ->name( 'yancy.auth.' . $self->moniker . '.logout' )
177 );
178 }
179  
180 #pod =method current_user
181 #pod
182 #pod Returns the access token of the currently-logged-in user.
183 #pod
184 #pod =cut
185  
186 sub current_user {
187 0 ▶ my ( $self, $c ) = @_;
Subroutine current_user: not called CC=2 SCAR=17.9
Pod documented
188 0 ▶ return $c->session->{yancy}{ $self->moniker }{access_token} || undef;
Condition0%0/2
$c->session->{'yancy'}{$self->moniker}{'access_token'} || undef
l!l
00
MC/DC0%0/1
$c->session->{'yancy'}{$self->moniker}{'access_token'} || undef
$c->session->{'yancy'}{$self->moniker}{'access_token'}
Truth table0%0/2
A
A= $c->session->{'yancy'}{$self->moniker}{'access_token'}
Aresult
11
00
189 }
190  
191 #pod =method logout
192 #pod
193 #pod Clear any currently-logged-in user.
194 #pod
195 #pod =cut
196  
197 sub logout {
198 0 ▶ my ( $self, $c ) = @_;
Subroutine logout: not called CC=1 SCAR=6.9
Pod documented
199 0 delete $c->session->{yancy}{ $self->moniker };
200 0 return;
201 }
202  
203 #pod =method login_form
204 #pod
205 #pod Get a link to log in using this OAuth2 provider.
206 #pod
207 #pod =cut
208  
209 sub login_form {
210 0 ▶ my ( $self, $c ) = @_;
Subroutine login_form: not called CC=1 SCAR=6.9
Pod documented
211 0 return $c->render_to_string(
212 'yancy/auth/oauth2/login_form',
213 label => $self->login_label,
214 url => $self->route->render,
215 );
216 }
217  
218 sub _handle_auth {
219 0 ▶ my ( $self, $c ) = @_;
Subroutine _handle_auth: not called CC=7 SCAR=40.3
220  
221 # This sub handles both steps of authentication. If we have a code,
222 # we can get a token.
223 0 ▶ if ( my $code = $c->param( 'code' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $code = $c->param("code")) 0 0 0
224 0 my %client_info = (
225 client_id => $self->client_id,
226 client_secret => $self->client_secret,
227 code => $code,
228 );
229 $self->ua->post_p( $self->token_url, form => \%client_info )
230 ->then( sub {
231 0 ▶ my ( $tx ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
232 0 my $token = $tx->res->body_params->param( 'access_token' );
233 0 $c->session->{yancy}{ $self->moniker }{ access_token } = $token;
234 $self->handle_token_p( $c, $token )
235 ->then( sub {
236 0 ▶ my $return_to = $c->session->{ yancy }{ $self->moniker }{ return_to };
Subroutine __ANON__: not called CC=1 SCAR=6.9
237 0 $c->redirect_to( $return_to );
238 } )
239 ->catch( sub {
240 0 ▶ my ( $err ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
241 0 $c->render( text => $err );
242 0 } );
243 } )
244 ->catch( sub {
245 0 ▶ my ( $err ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
246 0 $c->render(
247 text => $err,
248 );
249 0 } );
250 0 return $c->render_later;
251 }
252  
253 # If we do not have a code, we need to get one
254 0 my $to = $c->param( 'return_to' );
255  
256 # Do not allow return_to to redirect the user to another site.
257 # http://cwe.mitre.org/data/definitions/601.html
258 0 ▶ if ( $to && $to =~ m{^(?:\w+:|//)} ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($to and $to =~ m[^(?:\w+:|//)]u) { } 0 0 0
elsif (not $to || $c->req->headers->referrer =~ m[^(?:\w+:|//)]u) { } 0 0 0
elsif (not $to) { } 0 0 0
Condition0%0/3
$to and $to =~ m[^(?:\w+:|//)]u
!ll&&!rl&&r
000
MC/DC0%0/2
$to and $to =~ m[^(?:\w+:|//)]u
$to $to =~ m[^(?:\w+:|//)]u
Truth table0%0/3
A and B
A= $toB= $to =~ m[^(?:\w+:|//)]u
ABresult
0X0
100
111
259 0 return $c->reply->exception(
260 q{`return_to` can not contain URL scheme or host},
261 );
262 }
263 ▶ elsif ( !$to && $c->req->headers->referrer !~ m{^(?:\w+:|//)} ) {
Condition0%0/3
$to || $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
l!l&&r!l&&!r
000
MC/DC0%0/2
$to || $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
$to $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
Truth table0%0/3
A || B
A= $toB= $c->req->headers->referrer =~ m[^(?:\w+:|//)]u
ABresult
1X1
011
000
264 0 $to = $c->req->headers->referrer;
265 }
266 elsif ( !$to ) {
267 0 $to = '/';
268 }
269  
270 0 $c->session->{yancy}{ $self->moniker }{ return_to } = $to;
271 0 $c->redirect_to( $self->get_authorize_url( $c ) );
272 }
273  
274 #pod =method get_authorize_url
275 #pod
276 #pod my $url = $self->get_authorize_url( $c );
277 #pod
278 #pod Get a full authorization URL with query parameters. Override this in
279 #pod a subclass to customize the authorization parameters.
280 #pod
281 #pod =cut
282  
283 sub get_authorize_url {
284 0 ▶ my ( $self, $c ) = @_;
Subroutine get_authorize_url: not called CC=1 SCAR=6.9
Pod documented
285 0 my %client_info = (
286 client_id => $self->client_id,
287 );
288 0 return $self->authorize_url->clone->query( \%client_info );
289 }
290  
291 #pod =method handle_token_p
292 #pod
293 #pod my $p = $self->handle_token_p( $c, $token );
294 #pod
295 #pod Handle the receipt of the token. Override this in a subclass to make any
296 #pod API requests to identify the user. Returns a L<Mojo::Promise> that will
297 #pod be fulfilled when the information is complete.
298 #pod
299 #pod =cut
300  
301 sub handle_token_p {
302 0 ▶ my ( $self, $c, $token ) = @_;
Subroutine handle_token_p: not called CC=1 SCAR=6.9
Pod documented
303 0 return Mojo::Promise->new->resolve;
304 }
305  
306 sub _handle_logout {
307 0 ▶ my ( $self, $c ) = @_;
Subroutine _handle_logout: not called CC=4 SCAR=30.0
308 0 $self->logout( $c );
309 0 $c->res->code( 303 );
310 0 ▶ my $redirect_to = $c->param( 'redirect_to' ) // $c->req->headers->referrer // '/';
Condition0%0/5
($c->param("redirect_to") // $c->req->headers->referrer) // "/"
l!l
00
$c->param("redirect_to") // $c->req->headers->referrer
l!l&&r!l&&!r
000
MC/DC0%0/2
($c->param("redirect_to") // $c->req->headers->referrer) // "/"
$c->param("redirect_to") $c->req->headers->referrer
Truth table0%0/3
A // B
A= $c->param("redirect_to")B= $c->req->headers->referrer
ABresult
1X1
011
000
311 0 ▶ if ( $redirect_to eq $c->req->url->path ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($redirect_to eq $c->req->url->path) 0 0 0
312 0 $redirect_to = '/';
313 }
314 0 return $c->redirect_to( $redirect_to );
315 }
316  
317 3 1;
318  
319 __END__
« Yancy/Plugin/Auth/Role/RequireUser.pm ↑ Summary Yancy/Plugin/Auth/Github.pm »