blob: 04a90b2a287a0ab6c04d07ce09f957e3847a7421 [file] [log] [blame]
Akron80027d12016-01-20 17:36:36 +01001package Kalamar::Plugin::KalamarUser;
2use Mojo::Base 'Mojolicious::Plugin';
Akron864c2932018-11-16 17:18:55 +01003use Mojo::Util qw/deprecated/;
Akron32396632018-10-11 17:08:37 +02004use Mojo::Promise;
Akron80027d12016-01-20 17:36:36 +01005use Mojo::ByteStream 'b';
6
7has 'api';
Akrondadacf12016-01-22 19:24:59 +01008has 'ua';
Akron80027d12016-01-20 17:36:36 +01009
10sub register {
11 my ($plugin, $mojo, $param) = @_;
12
13 # Load parameter from config file
14 if (my $config_param = $mojo->config('Kalamar')) {
15 $param = { %$param, %$config_param };
16 };
17
Akron2cb9a3d2016-02-09 23:59:46 +010018 # Load 'notifications' plugin
19 unless (exists $mojo->renderer->helpers->{notify}) {
20 $mojo->plugin(Notifications => {
21 HTML => 1
22 });
23 };
24
Akron80027d12016-01-20 17:36:36 +010025 # Set API!
26 $plugin->api($param->{api}) or return;
Akronc95c9e72017-03-30 21:53:51 +020027 $plugin->ua(Mojo::UserAgent->new(
Akrona3c353c2019-02-14 23:50:00 +010028 connect_timeout => 90,
Akronacef8dc2018-08-29 18:16:08 +020029 inactivity_timeout => 120,
30 max_redirects => 3
Akronc95c9e72017-03-30 21:53:51 +020031 ));
Akron80027d12016-01-20 17:36:36 +010032
Akronbe9d5b32017-04-05 20:48:24 +020033 # Set app to server
34 $plugin->ua->server->app($mojo);
35
Akron8bbbecf2019-07-01 18:57:30 +020036 # Get a user agent object for Kalamar
37 $mojo->helper(
38 'kalamar_ua' => sub {
39 return $plugin->ua;
40 }
41 );
42
Akron864c2932018-11-16 17:18:55 +010043 # Get user handle
44 $mojo->helper(
45 'user_handle' => sub {
46 my $c = shift;
47
48 # Get from stash
49 my $user = $c->stash('user');
50 return $user if $user;
51
52 # Get from session
53 $user = $c->session('user');
54
55 # Set in stash
56 if ($user) {
57 $c->stash(user => $user);
58 return $user;
59 };
60
61 return 'not_logged_in';
62 }
63 );
64
65 # This is a new general korap_request helper,
66 # that can trigger some hooks for, e.g., authentication
67 # or analysis. It returns a promise.
68 $mojo->helper(
69 'korap_request' => sub {
70 my $c = shift;
71 my $method = shift;
72 my $path = shift;
73
74 # Get plugin user agent
75 my $ua = $plugin->ua;
76
77 my $url = Mojo::URL->new($path);
78 my $tx = $ua->build_tx(uc($method), $url, @_);
79
80 # Set X-Forwarded for
81 $tx->req->headers->header(
82 'X-Forwarded-For' => $c->client_ip
83 );
84
Akron864c2932018-11-16 17:18:55 +010085 # Emit Hook to alter request
86 $c->app->plugins->emit_hook(
87 before_korap_request => ($c, $tx)
88 );
89
90 return $ua->start_p($tx);
91 }
92 );
Akron80027d12016-01-20 17:36:36 +010093};
94
Akron80027d12016-01-20 17:36:36 +0100951;
96
97
98__END__
Akrondadacf12016-01-22 19:24:59 +010099