1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
|
package FixMyStreet::App::Controller::Auth::Social;
use Moose;
use namespace::autoclean;
BEGIN { extends 'Catalyst::Controller'; }
use Net::Facebook::Oauth2;
use Net::Twitter::Lite::WithAPIv1_1;
use OIDC::Lite::Client::WebServer::AuthCodeFlow;
use URI::Escape;
use mySociety::AuthToken;
=head1 NAME
FixMyStreet::App::Controller::Auth::Social - Catalyst Controller
=head1 DESCRIPTION
Controller for the Facebook/Twitter/OpenID Connect authentication.
=head1 METHODS
=head2 handle_sign_in
Forwards to the appropriate (facebook|twitter|oidc)_sign_in method
based on the social_sign_in parameter
=cut
sub handle_sign_in : Private {
my ($self, $c) = @_;
$c->detach('facebook_sign_in') if $c->get_param('social_sign_in') eq 'facebook';
$c->detach('twitter_sign_in') if $c->get_param('social_sign_in') eq 'twitter';
$c->detach('oidc_sign_in') if $c->get_param('social_sign_in') eq 'oidc';
}
=head2 facebook_sign_in
Starts the Facebook authentication sequence.
=cut
sub fb : Private {
my ($self, $c) = @_;
Net::Facebook::Oauth2->new(
application_id => $c->config->{FACEBOOK_APP_ID},
application_secret => $c->config->{FACEBOOK_APP_SECRET},
callback => $c->uri_for('/auth/Facebook'),
);
}
sub facebook_sign_in : Private {
my ( $self, $c ) = @_;
$c->detach( '/page_error_403_access_denied', [] ) if FixMyStreet->config('SIGNUPS_DISABLED');
my $fb = $c->forward('fb');
my $url = $fb->get_authorization_url(scope => ['email']);
my %oauth;
$oauth{return_url} = $c->get_param('r');
$oauth{detach_to} = $c->stash->{detach_to};
$oauth{detach_args} = $c->stash->{detach_args};
$c->session->{oauth} = \%oauth;
$c->res->redirect($url);
}
=head2 facebook_callback
Handles the Facebook callback request and completes the authentication sequence.
=cut
sub facebook_callback: Path('/auth/Facebook') : Args(0) {
my ( $self, $c ) = @_;
$c->detach('oauth_failure') if $c->get_param('error_code');
my $fb = $c->forward('fb');
my $access_token;
eval {
$access_token = $fb->get_access_token(code => $c->get_param('code'));
};
if ($@) {
(my $message = $@) =~ s/at [^ ]*Auth.pm.*//;
$c->detach('/page_error_500_internal_error', [ $message ]);
}
# save this token in session
$c->session->{oauth}{token} = $access_token;
my $info = $fb->get('https://graph.facebook.com/me?fields=name,email')->as_hash();
my $email = lc ($info->{email} || "");
$c->forward('oauth_success', [ 'facebook', $info->{id}, $info->{name}, $email ]);
}
=head2 twitter_sign_in
Starts the Twitter authentication sequence.
=cut
sub tw : Private {
my ($self, $c) = @_;
Net::Twitter::Lite::WithAPIv1_1->new(
ssl => 1,
consumer_key => $c->config->{TWITTER_KEY},
consumer_secret => $c->config->{TWITTER_SECRET},
);
}
sub twitter_sign_in : Private {
my ( $self, $c ) = @_;
$c->detach( '/page_error_403_access_denied', [] ) if FixMyStreet->config('SIGNUPS_DISABLED');
my $twitter = $c->forward('tw');
my $url = $twitter->get_authentication_url(callback => $c->uri_for('/auth/Twitter'));
my %oauth;
$oauth{return_url} = $c->get_param('r');
$oauth{detach_to} = $c->stash->{detach_to};
$oauth{detach_args} = $c->stash->{detach_args};
$oauth{token} = $twitter->request_token;
$oauth{token_secret} = $twitter->request_token_secret;
$c->session->{oauth} = \%oauth;
$c->res->redirect($url);
}
=head2 twitter_callback
Handles the Twitter callback request and completes the authentication sequence.
=cut
sub twitter_callback: Path('/auth/Twitter') : Args(0) {
my ( $self, $c ) = @_;
my $request_token = $c->req->param('oauth_token');
my $verifier = $c->req->param('oauth_verifier');
my $oauth = $c->session->{oauth};
$c->detach('oauth_failure') if $c->get_param('denied') || $request_token ne $oauth->{token};
my $twitter = $c->forward('tw');
$twitter->request_token($oauth->{token});
$twitter->request_token_secret($oauth->{token_secret});
eval {
# request_access_token no longer returns UID or name
$twitter->request_access_token(verifier => $verifier);
};
if ($@) {
(my $message = $@) =~ s/at [^ ]*Auth.pm.*//;
$c->detach('/page_error_500_internal_error', [ $message ]);
}
my $info = $twitter->verify_credentials();
$c->forward('oauth_success', [ 'twitter', $info->{id}, $info->{name} ]);
}
sub oidc : Private {
my ($self, $c) = @_;
my $config = $c->cobrand->feature('oidc_login');
OIDC::Lite::Client::WebServer::AuthCodeFlow->new(
id => $config->{client_id},
secret => $config->{secret},
authorize_uri => $config->{auth_uri},
access_token_uri => $config->{token_uri},
);
}
sub oidc_sign_in : Private {
my ( $self, $c ) = @_;
$c->detach( '/page_error_403_access_denied', [] ) if FixMyStreet->config('SIGNUPS_DISABLED');
my $cfg = $c->cobrand->feature('oidc_login');
$c->detach( '/page_error_400_bad_request', [] ) unless $cfg;
my $oidc = $c->forward('oidc');
my $nonce = $self->generate_nonce();
my $url = $oidc->uri_to_redirect(
redirect_uri => $c->uri_for('/auth/OIDC'),
scope => 'openid',
state => 'login',
extra => {
response_mode => 'form_post',
nonce => $nonce,
# auth_extra_params provides a way to pass custom parameters
# to the OIDC endpoint for the intial authentication request.
# This allows, for example, a custom scope to be used,
# or the `hd` parameter which customises the appearance of
# the login form.
# This is primarily useful for Google G Suite authentication - see
# available parameters here:
# https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters
%{ $cfg->{auth_extra_params} || {} } ,
},
);
my %oauth;
$oauth{return_url} = $c->get_param('r');
$oauth{detach_to} = $c->stash->{detach_to};
$oauth{detach_args} = $c->stash->{detach_args};
$oauth{nonce} = $nonce;
# The OIDC endpoint may require a specific URI to be called to log the user
# out when they log out of FMS.
if ( my $redirect_uri = $cfg->{logout_uri} ) {
$redirect_uri .= "?post_logout_redirect_uri=";
$redirect_uri .= URI::Escape::uri_escape( $c->uri_for('/auth/sign_out') );
$oauth{logout_redirect_uri} = $redirect_uri;
}
# The OIDC endpoint may provide a specific URI for changing the user's password.
if ( my $password_change_uri = $cfg->{password_change_uri} ) {
$oauth{change_password_uri} = $oidc->uri_to_redirect(
uri => $password_change_uri,
redirect_uri => $c->uri_for('/auth/OIDC'),
scope => 'openid',
state => 'password_change',
extra => {
response_mode => 'form_post',
},
);
}
$c->session->{oauth} = \%oauth;
$c->res->redirect($url);
}
sub oidc_callback: Path('/auth/OIDC') : Args(0) {
my ( $self, $c ) = @_;
my $oidc = $c->forward('oidc');
if ($c->get_param('error')) {
my $error_desc = $c->get_param('error_description');
my $password_reset_uri = $c->cobrand->feature('oidc_login')->{password_reset_uri};
if ($password_reset_uri && $error_desc =~ /^AADB2C90118:/) {
my $url = $oidc->uri_to_redirect(
uri => $password_reset_uri,
redirect_uri => $c->uri_for('/auth/OIDC'),
scope => 'openid',
state => 'password_reset',
extra => {
response_mode => 'form_post',
},
);
$c->res->redirect($url);
$c->detach;
} elsif ($c->user_exists && $c->get_param('state') && $c->get_param('state') eq 'password_change') {
$c->flash->{flash_message} = _('Password change cancelled.');
$c->res->redirect('/my');
$c->detach;
} else {
$c->detach('oauth_failure');
}
}
$c->detach('/page_error_400_bad_request', []) unless $c->get_param('code') && $c->get_param('state');
# After a password reset on the OIDC endpoint the user isn't properly logged
# in, so redirect them to the usual OIDC login process.
if ( $c->get_param('state') eq 'password_reset' ) {
# The user may have reset their password as part of the sign-in-during-report
# process, so preserve their report and redirect them to the right place
# if that happened.
if ( $c->session->{oauth} ) {
$c->stash->{detach_to} = $c->session->{oauth}{detach_to};
$c->stash->{detach_args} = $c->session->{oauth}{detach_args};
}
$c->detach('oidc_sign_in', []);
}
# User may be coming back here after changing their password on the OIDC endpoint
if ($c->user_exists && $c->get_param('state') && $c->get_param('state') eq 'password_change') {
$c->detach('/auth/profile/change_password_success', []);
}
# The only other valid state param is 'login' at this point.
$c->detach('/page_error_400_bad_request', []) unless $c->get_param('state') eq 'login';
my $id_token;
eval {
$id_token = $oidc->get_access_token(
code => $c->get_param('code'),
redirect_uri => $c->uri_for('/auth/OIDC')
);
};
if ($@) {
(my $message = $@) =~ s/at [^ ]*Auth.pm.*//;
$c->detach('/page_error_500_internal_error', [ $message ]);
}
$c->detach('oauth_failure') unless $id_token;
# sanity check the token audience is us...
$c->detach('/page_error_500_internal_error', ['invalid id_token']) unless $id_token->payload->{aud} eq $c->cobrand->feature('oidc_login')->{client_id};
# check that the nonce matches what we set in the user session
$c->detach('/page_error_500_internal_error', ['invalid id_token']) unless $id_token->payload->{nonce} eq $c->session->{oauth}{nonce};
if (my $domains = $c->cobrand->feature('oidc_login')->{allowed_domains}) {
# Check that the hd payload is present in the token and matches the
# list of allowed domains from the config
my $hd = $id_token->payload->{hd};
my %allowed_domains = map { $_ => 1} @$domains;
$c->detach('oauth_failure') unless $allowed_domains{$hd};
}
# Some claims need parsing into a friendlier format
my $name = $id_token->payload->{name} || join(" ", $id_token->payload->{given_name}, $id_token->payload->{family_name});
my $email = $id_token->payload->{email};
# WCC Azure provides a single email address as an array for some reason
my $emails = $id_token->payload->{emails};
if ($emails && @$emails) {
$email = $emails->[0];
}
# There's a chance that a user may have multiple OIDC logins, so build a namespaced uid to prevent collisions
my $uid = join(":", $c->cobrand->moniker, $c->cobrand->feature('oidc_login')->{client_id}, $id_token->payload->{sub});
# The cobrand may want to set values in the user extra field, e.g. a CRM ID
# which is passed to Open311 with reports made by this user.
my $extra = $c->cobrand->call_hook(oidc_user_extra => $id_token);
$c->forward('oauth_success', [ 'oidc', $uid, $name, $email, $extra ]);
}
# Just a wrapper around random_token to make mocking easier.
sub generate_nonce : Private {
my ($self, $c) = @_;
return mySociety::AuthToken::random_token();
}
sub oauth_failure : Private {
my ( $self, $c ) = @_;
$c->stash->{oauth_failure} = 1;
if ($c->session->{oauth}{detach_to}) {
$c->detach($c->session->{oauth}{detach_to}, $c->session->{oauth}{detach_args});
} else {
$c->stash->{template} = 'auth/general.html';
$c->detach;
}
}
sub oauth_success : Private {
my ($self, $c, $type, $uid, $name, $email, $extra) = @_;
my $user;
if ($email) {
# Only Facebook & OIDC get here
# We've got an ID and an email address
# Remove any existing mention of this ID
my $existing;
if ($type eq 'facebook') {
$existing = $c->model('DB::User')->find( { $type . '_id' => $uid } );
$existing->update( { $type . '_id' => undef } ) if $existing;
} elsif ( $type eq 'oidc' ) {
$existing = $c->model('DB::User')->find( { oidc_ids => \[
'&& ?', [ oidc_ids => [ $uid ] ]
] } );
$existing->remove_oidc_id( $uid ) if $existing;
}
# Get or create a user, give it this Facebook/OIDC ID
$user = $c->model('DB::User')->find_or_new( { email => $email } );
if ( $type eq 'facebook' ) {
$user->facebook_id($uid);
} elsif ( $type eq 'oidc' ) {
$user->add_oidc_id($uid);
}
$user->name($name);
if ($extra) {
$user->extra({
%{ $user->get_extra() },
%$extra
});
}
$user->in_storage() ? $user->update : $user->insert;
} else {
# We've got an ID, but no email
if ($type eq 'oidc') {
$user = $c->model('DB::User')->find( { oidc_ids => \[
'&& ?', [ oidc_ids => [ $uid ] ]
] } );
} else {
$user = $c->model('DB::User')->find( { $type . '_id' => $uid } );
}
if ($user) {
# Matching ID in our database
$user->name($name);
if ($extra) {
$user->extra({
%{ $user->get_extra() },
%$extra
});
}
$user->update;
} else {
# No matching ID, store ID for use later
$c->session->{oauth}{$type . '_id'} = $uid;
$c->session->{oauth}{name} = $name;
$c->session->{oauth}{extra} = $extra;
$c->stash->{oauth_need_email} = 1;
}
}
# If we've got here with a full user, log in
if ($user) {
$c->authenticate( { email => $user->email, email_verified => 1 }, 'no_password' );
$c->stash->{login_success} = 1;
}
if ($c->session->{oauth}{detach_to}) {
$c->detach($c->session->{oauth}{detach_to}, $c->session->{oauth}{detach_args});
} elsif ($c->stash->{oauth_need_email}) {
$c->stash->{template} = 'auth/general.html';
} else {
$c->detach( '/auth/redirect_on_signin', [ $c->session->{oauth}{return_url} ] );
}
}
__PACKAGE__->meta->make_immutable;
1;
|