|
| 1 | +package Convos::Plugin::Auth::OAuth2; |
| 2 | +use Mojo::Base 'Convos::Plugin::Auth'; |
| 3 | + |
| 4 | +use Convos::Util qw(DEBUG require_module); |
| 5 | +use Mojo::Promise; |
| 6 | + |
| 7 | +has _provider => ''; |
| 8 | + |
| 9 | +sub register { |
| 10 | + my ($self, $app, $config) = @_; |
| 11 | + require_module('Mojolicious::Plugin::OAuth2'); |
| 12 | + |
| 13 | + my $provider = Mojo::URL->new($ENV{CONVOS_OAUTH2_PROVIDER}); |
| 14 | + $self->_provider($provider->host); |
| 15 | + $app->plugin(OAuth2 => {$provider->host, $provider->query->to_hash}); |
| 16 | + |
| 17 | + $app->helper('auth.login_p' => sub { $self->_login_p(@_) }); |
| 18 | + $app->log->debug("Loaded Convos::Plugin::Auth::OAuth2"); |
| 19 | +} |
| 20 | + |
| 21 | +sub _login_p { |
| 22 | + my ($self, $c, $params) = @_; |
| 23 | + my $p = Mojo::Promise->new; |
| 24 | + |
| 25 | + return $p->then(sub { |
| 26 | + my $ldap_msg = shift; |
| 27 | + my $core = $c->app->core; |
| 28 | + my $user = $core->get_user($params); |
| 29 | + |
| 30 | + # Try to fallback to local user on error |
| 31 | + if ($ldap_msg->code) { |
| 32 | + return $user if $user and $user->validate_password($params->{password}); |
| 33 | + return Mojo::Promise->reject('Invalid email or password.'); |
| 34 | + } |
| 35 | + |
| 36 | + # All good if user exists |
| 37 | + return $user if $user; |
| 38 | + |
| 39 | + $user = $core->user($params); |
| 40 | + $user->set_password($params->{password}); |
| 41 | + return $user->save_p; |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +1; |
| 46 | + |
| 47 | +=encoding utf8 |
| 48 | +
|
| 49 | +=head1 NAME |
| 50 | +
|
| 51 | +Convos::Plugin::Auth::OAuth2 - Convos plugin for logging in users via an OAuth2 provider |
| 52 | +
|
| 53 | +=head1 SYNOPSIS |
| 54 | +
|
| 55 | + $ CONVOS_PLUGINS=Convos::Plugin::Auth::OAuth2 \ |
| 56 | + CONVOS_OAUTH2_PROVIDER="github?key=123&secret=secret" \ |
| 57 | + ./script/convos daemon |
| 58 | +
|
| 59 | +=head1 DESCRIPTION |
| 60 | +
|
| 61 | +L<Convos::Plugin::Auth::OAuth2> allows Convos to register and login users via |
| 62 | +an OAuth2 provider. |
| 63 | +
|
| 64 | +=head1 ENVIRONMENT VARIABLES |
| 65 | +
|
| 66 | +=head2 CONVOS_OAUTH2_PROVIDER |
| 67 | +
|
| 68 | +=head1 METHODS |
| 69 | +
|
| 70 | +=head2 register |
| 71 | +
|
| 72 | +Used to register this plugin in the L<Convos> application. |
| 73 | +
|
| 74 | +=head1 SEE ALSO |
| 75 | +
|
| 76 | +L<Convos::Plugin::Auth> and L<Convos>. |
| 77 | +
|
| 78 | +=cut |
| 79 | + |
0 commit comments