| 1 | package Mojolicious::Plugin::Config::Structured::Bootstrap 0.06; | ||
| 2 | use v5.26; | ||
| 3 | use warnings; | ||
| 4 | |||
| 5 | # ABSTRACT: Autoconfigure Mojolicious application and plugins | ||
| 6 | |||
| 7 | use Mojo::Base 'Mojolicious::Plugin'; | ||
| 8 | |||
| 9 | use Array::Utils qw(intersect); | ||
| 10 | use Hash::Merge; | ||
| 11 | use HTTP::Status qw(:constants status_message); | ||
| 12 | use List::MoreUtils qw(arrayify); | ||
| 13 | use Module::Loadable qw(module_loadable); | ||
| 14 | use DateTime::Format::MySQL; | ||
| 15 | use Readonly; | ||
| 16 | use Syntax::Keyword::Try; | ||
| 17 | |||
| 18 | use experimental qw(signatures); | ||
| 19 | |||
| 20 | Readonly::Hash my %RENDER_FAIL => ( | ||
| 21 | badreq => HTTP_BAD_REQUEST, | ||
| 22 | unauth => HTTP_UNAUTHORIZED, | ||
| 23 | notfound => HTTP_NOT_FOUND, | ||
| 24 | ); | ||
| 25 | Readonly::Hash my %RENDER_SUCCESS => (nocontent => HTTP_NO_CONTENT); | ||
| 26 | |||
| 27 | sub register($self, $app, $app_config) { | ||
| 28 | $app->log->debug("=================-CSBootstrap Starting-==================="); | ||
| 29 | |||
| 30 | my $cfg_dir = $app->home->child('cfg'); | ||
| 31 | my $merge = Hash::Merge->new('RIGHT_PRECEDENT'); | ||
| 32 | |||
| 33 | my $ns_append = sub (@suffixes) { | ||
| 34 | return join('::', ucfirst($app->moniker), @suffixes); | ||
| 35 | }; | ||
| 36 | |||
| 37 | my $load = sub($name, $get_defaults = undef, $force_load = 0) { | ||
| 38 | return unless (module_loadable("Mojolicious::Plugin::$name")); | ||
| 39 | return if (!$force_load && exists($app_config->{$name}) && !defined($app_config->{$name})); | ||
| 40 | try { | ||
| 41 | my $defaults = ref($get_defaults) eq 'CODE' ? $get_defaults->() : {}; | ||
| 42 | $app->plugin($name, $merge->merge($defaults, $app_config->{$name} // {})); | ||
| 43 | $app->log->debug("CSBootstrap loaded plugin '$name'"); | ||
| 44 | } catch ($e) { | ||
| 45 | if ($e =~ /Can't locate object method "(.*)" via package "PKG0x/) { | ||
| 46 | $e = "Config::Structured node '$1' does not exist"; | ||
| 47 | } | ||
| 48 | chomp($e); | ||
| 49 | $app->log->error("CSBootstrap failed to load plugin '$name': $e"); | ||
| 50 | } | ||
| 51 | }; | ||
| 52 | |||
| 53 | $load->( | ||
| 54 | 'Config::Structured' => sub { | ||
| 55 | { | ||
| 56 | structure_file => $cfg_dir->child(sprintf('%s-conf.yml', lc($app->moniker)))->to_string, | ||
| 57 | config_file => $ENV{uc($app->moniker) . '_CONFIG'}, | ||
| 58 | } | ||
| 59 | }, | ||
| 60 | 1 | ||
| 61 | ); | ||
| 62 | |||
| 63 | # Sessionless | ||
| 64 | $load->('Sessionless'); | ||
| 65 | |||
| 66 | # ORM::DBIx | ||
| 67 | $load->( | ||
| 68 | 'ORM::DBIx' => sub { | ||
| 69 | { | ||
| 70 | dsn => $app->conf->db->dsn, | ||
| 71 | username => $app->conf->db->user, | ||
| 72 | password => $app->conf->db->pass(1), | ||
| 73 | feature_bundle => 'v' . join(q{.}, @{$^V->{version}}[0, 1]), | ||
| 74 | tidy_format_skipping => ['## no tidy', '## use tidy'], | ||
| 75 | connect_params => {quote_names => 1}, | ||
| 76 | } | ||
| 77 | } | ||
| 78 | ); | ||
| 79 | |||
| 80 | # Migration::Sqitch | ||
| 81 | $load->( | ||
| 82 | 'Migration::Sqitch' => sub { | ||
| 83 | { | ||
| 84 | dsn => $app->conf->db->dsn, | ||
| 85 | registry => $app->conf->db->migration->registry, | ||
| 86 | username => $app->conf->db->migration->user, | ||
| 87 | password => $app->conf->db->migration->pass(1), | ||
| 88 | directory => $app->conf->db->migration->directory, | ||
| 89 | } | ||
| 90 | } | ||
| 91 | ); | ||
| 92 | |||
| 93 | # SendEmail | ||
| 94 | $load->( | ||
| 95 | 'SendEmail' => sub { | ||
| 96 | { | ||
| 97 | from => $app->conf->email->from, | ||
| 98 | host => $app->conf->email->smtp->host, | ||
| 99 | port => $app->conf->email->smtp->port, | ||
| 100 | ssl => $app->conf->email->smtp->ssl, | ||
| 101 | sasl_username => $app->conf->email->smtp->sasl_username || undef, | ||
| 102 | sasl_password => $app->conf->email->smtp->sasl_password(1) || undef, | ||
| 103 | |||
| 104 | recipient_resolver => sub($add) { | ||
| 105 | if (defined($add)) { | ||
| 106 | return [arrayify(map {__SUB__->($_)} $add->@*)] if (ref($add) eq 'ARRAY'); | ||
| 107 | return $add if ($add =~ /@/); | ||
| 108 | return __SUB__->($app->conf->email->recipients->{$add} // $app->conf->email->recipients->{default}) unless (ref($add)); | ||
| 109 | } | ||
| 110 | return (); | ||
| 111 | }, | ||
| 112 | } | ||
| 113 | } | ||
| 114 | ); | ||
| 115 | |||
| 116 | $load->( | ||
| 117 | 'Cron::Scheduler' => sub { | ||
| 118 | { | ||
| 119 | namespaces => [$ns_append->('Cron')], | ||
| 120 | schedules => $app->conf->scheduled_tasks->to_hash, | ||
| 121 | } | ||
| 122 | } | ||
| 123 | ); | ||
| 124 | |||
| 125 | $load->( | ||
| 126 | 'Authentication::OIDC' => sub { | ||
| 127 | { | ||
| 128 | client_secret => $app->conf->auth->client_secret(1), | ||
| 129 | public_key => $app->conf->auth->public_key, | ||
| 130 | well_known_url => $app->conf->auth->well_known_url, | ||
| 131 | base_url => $app->conf->urls->backend, | ||
| 132 | login_path => '/api/auth/login', | ||
| 133 | make_routes => 0, | ||
| 134 | |||
| 135 | get_token => sub ($c) { | ||
| 136 | if (my $t = $c->cookie('oidc_auth_token')) {return $t;} | ||
| 137 | if (($c->req->headers->authorization // '') =~ /^Bearer (.*)/) {return $1;} | ||
| 138 | if (($c->req->headers->header('Sec-WebSocket-Protocol') // '') =~ /^access_token, (.*)/) {return $1;} | ||
| 139 | return undef; | ||
| 140 | }, | ||
| 141 | get_user => sub ($token) { | ||
| 142 | my $person = $app->model('Person')->find_or_create( | ||
| 143 | { | ||
| 144 | firstname => $token->{given_name}, | ||
| 145 | lastname => $token->{family_name}, | ||
| 146 | } | ||
| 147 | ); | ||
| 148 | my $user = $app->model("User")->update_or_create( | ||
| 149 | { | ||
| 150 | username => $token->{preferred_username}, | ||
| 151 | email => $token->{email}, | ||
| 152 | email_verified => $token->{email_verified} ? 'Y' : 'N', | ||
| 153 | person => $person, | ||
| 154 | } | ||
| 155 | ); | ||
| 156 | }, | ||
| 157 | role_map => $app->conf->auth->role_map, | ||
| 158 | get_roles => sub ($user, $token) { | ||
| 159 | $token->{realm_access}->{roles}; | ||
| 160 | }, | ||
| 161 | |||
| 162 | on_success => sub ($c, $token, $url) { | ||
| 163 | $c->cookie(oidc_auth_token => $token, {path => '/api', expires => time + 60, sameSite => 'Lax'}); | ||
| 164 | $c->redirect_to($url); | ||
| 165 | }, | ||
| 166 | on_login => sub ($c, $u) { | ||
| 167 | my $now = DateTime::Format::MySQL->format_datetime(DateTime->now(time_zone => 'local')); | ||
| 168 | $u->update({last_login_at => $now}); | ||
| 169 | $u->update({last_activity_at => $now}); | ||
| 170 | }, | ||
| 171 | on_activity => sub ($c, $u) { | ||
| 172 | my $now = DateTime::Format::MySQL->format_datetime(DateTime->now(time_zone => 'local')); | ||
| 173 | $u->update({last_activity_at => $now}); | ||
| 174 | if ($app->conf->auth->enable_media_access) { | ||
| 175 | if (my $token = $c->__oidc_token(undef, 0)) { | ||
| 176 | $c->cookie(oidc_auth_token => $token, {path => '/api', expires => time + 300, samesite => 'Strict'}); | ||
| 177 | return; | ||
| 178 | } | ||
| 179 | } | ||
| 180 | $c->cookie(oidc_auth_token => '', {path => '/api', expires => 1}); | ||
| 181 | } | ||
| 182 | } | ||
| 183 | } | ||
| 184 | ); | ||
| 185 | |||
| 186 | $load->( | ||
| 187 | 'Authorization::AccessControl' => sub { | ||
| 188 | {} | ||
| 189 | } | ||
| 190 | ); | ||
| 191 | |||
| 192 | $load->( | ||
| 193 | 'Data::Transfigure' => sub { | ||
| 194 | {renderers => [qw(openapi json)]} | ||
| 195 | } | ||
| 196 | ); | ||
| 197 | |||
| 198 | $load->( | ||
| 199 | OpenAPI => sub { | ||
| 200 | { | ||
| 201 | url => $app->home->child('cfg')->child(sprintf('%s-api.yml', lc($app->moniker)))->to_string, | ||
| 202 | op_spec_to_route => sub($plugin, $op_spec, $route, $t) { | ||
| 203 | $route->to($op_spec->{operationId} =~ s/->/#/r) if ($op_spec->{operationId}); | ||
| 204 | }, | ||
| 205 | security => { | ||
| 206 | Token => sub($c, $definition, $scopes, $cb) { | ||
| 207 | try { | ||
| 208 | my $u = $c->authn->current_user(); | ||
| 209 | return $c->$cb('User not authenticated') unless (defined($u)); | ||
| 210 | return $c->$cb('User email not verified') unless ($u->email_verified); | ||
| 211 | return $c->$cb('User disabled/deleted') | ||
| 212 | if ($u->can('deleted_at') && defined($u->deleted_at) && $u->deleted_at < DateTime->now()); | ||
| 213 | return $c->$cb() unless ($scopes->@*); | ||
| 214 | return $c->$cb() if (intersect($scopes->@*, $c->authn->current_user_roles->@*)); | ||
| 215 | return $c->$cb('User not authorized'); | ||
| 216 | } catch ($e) { | ||
| 217 | $e =~ s/( at \/.*)$//; | ||
| 218 | chomp($e); | ||
| 219 | $c->$cb($e) | ||
| 220 | } | ||
| 221 | } | ||
| 222 | } | ||
| 223 | } | ||
| 224 | } | ||
| 225 | ); | ||
| 226 | |||
| 227 | $load->( | ||
| 228 | 'Module::Loader' => sub { | ||
| 229 | { | ||
| 230 | command_namespaces => [$ns_append->('Command')], | ||
| 231 | plugin_namespaces => [$ns_append->('Plugin')], | ||
| 232 | } | ||
| 233 | } | ||
| 234 | ); | ||
| 235 | |||
| 236 | foreach my $k (keys(%RENDER_FAIL)) { | ||
| 237 | my $code = $RENDER_FAIL{$k}; | ||
| 238 | $app->helper( | ||
| 239 | "render_failure.$k" => sub($c, $message = status_message($code)) { | ||
| 240 | chomp($message); | ||
| 241 | $c->render(status => $code, openapi => {status => $code, errors => [{message => $message}]}); | ||
| 242 | } | ||
| 243 | ); | ||
| 244 | } | ||
| 245 | foreach my $k (keys(%RENDER_SUCCESS)) { | ||
| 246 | my $code = $RENDER_SUCCESS{$k}; | ||
| 247 | $app->helper( | ||
| 248 | "render_success.$k" => sub($c, $message = status_message($code)) { | ||
| 249 | chomp($message); | ||
| 250 | if ($code == HTTP_NO_CONTENT) { | ||
| 251 | $c->render(status => $code, text => $message); | ||
| 252 | } else { | ||
| 253 | $c->render(status => $code, openapi => {status => $code, errors => [{message => $message}]}); | ||
| 254 | } | ||
| 255 | } | ||
| 256 | ); | ||
| 257 | } | ||
| 258 | |||
| 259 | } | ||
| 260 | |||
| 261 | =head1 NAME | ||
| 262 | |||
| 263 | Mojolicious::Plugin::Config::Structured::Bootstrap - an extremely opinionated plugin for initializing a full-featured Mojolicious application | ||
| 264 | |||
| 265 | =head1 SYNOPSIS | ||
| 266 | |||
| 267 | # in app startup | ||
| 268 | $self->plugin('Config::Structured::Bootstrap'); | ||
| 269 | |||
| 270 | $self->plugin('Config::Structured::Bootstrap' => { | ||
| 271 | $plugin_name => \%plugin_config, ... | ||
| 272 | }); | ||
| 273 | |||
| 274 | =head1 DESCRIPTION | ||
| 275 | |||
| 276 | This plugin loads and initializes a specific set of other mojo plugins based on | ||
| 277 | a predefined (though overridable) configuration structure: | ||
| 278 | |||
| 279 | =over | ||
| 280 | |||
| 281 | =item * L<Mojolicious::Plugin::Config::Structured> | ||
| 282 | |||
| 283 | =item * L<Mojolicious::Plugin::Authentication::OIDC> | ||
| 284 | |||
| 285 | =item * L<Mojolicious::Plugin::Authorization::AccessControl> | ||
| 286 | |||
| 287 | =item * L<Mojolicious::Plugin::Cron::Scheduler> | ||
| 288 | |||
| 289 | =item * L<Mojolicious::Plugin::Data::Transfigure> | ||
| 290 | |||
| 291 | =item * L<Mojolicious::Plugin::Migration::Sqitch> | ||
| 292 | |||
| 293 | =item * L<Mojolicious::Plugin::Module::Loader> | ||
| 294 | |||
| 295 | =item * L<Mojolicious::Plugin::OpenAPI> | ||
| 296 | |||
| 297 | =item * L<Mojolicious::Plugin::ORM::DBIx> | ||
| 298 | |||
| 299 | =item * L<Mojolicious::Plugin::SendEmail> | ||
| 300 | |||
| 301 | =item * L<Mojolicious::Plugin::Sessionless> | ||
| 302 | |||
| 303 | =back | ||
| 304 | |||
| 305 | Any plugin that is not installed is silently skipped; you can also disable any | ||
| 306 | plugin by setting it to an undefined configuration during initialization, e.g.,: | ||
| 307 | |||
| 308 | $self->plugin('Config::Structured::Bootstrap' => { | ||
| 309 | Sessionless => undef | ||
| 310 | }); | ||
| 311 | |||
| 312 | Further documentation on how to manually/automatically configure these plugins | ||
| 313 | is forthcoming... | ||
| 314 | |||
| 315 | =head1 METHODS | ||
| 316 | |||
| 317 | L<Mojolicious::Plugin::Data::Transfigure> inherits all methods from | ||
| 318 | L<Mojolicious::Plugin> and implements the following new ones | ||
| 319 | |||
| 320 | =head2 register | ||
| 321 | |||
| 322 | Register the plugin in a Mojolicious application. Takes a HashRef as its | ||
| 323 | configuration argument. Each key of the HashRef is the name of a sub-plugin | ||
| 324 | (e.g., C<Migration::Sqitch>, with or without its C<Mojolicious::Plugin::>) | ||
| 325 | prefix. Setting the config value for a plugin to C<undef> prevents loading that | ||
| 326 | plugin. | ||
| 327 | |||
| 328 | =head1 AUTHOR | ||
| 329 | |||
| 330 | Mark Tyrrell C<< <mark@tyrrminal.dev> >> | ||
| 331 | |||
| 332 | =head1 LICENSE | ||
| 333 | |||
| 334 | Copyright (c) 2024 Mark Tyrrell | ||
| 335 | |||
| 336 | Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 337 | of this software and associated documentation files (the "Software"), to deal | ||
| 338 | in the Software without restriction, including without limitation the rights | ||
| 339 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 340 | copies of the Software, and to permit persons to whom the Software is | ||
| 341 | furnished to do so, subject to the following conditions: | ||
| 342 | |||
| 343 | The above copyright notice and this permission notice shall be included in all | ||
| 344 | copies or substantial portions of the Software. | ||
| 345 | |||
| 346 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 347 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 348 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 349 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 350 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 351 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 352 | SOFTWARE. | ||
| 353 | |||
| 354 | =cut | ||
| 355 | |||
| 356 | 1; | ||
| 357 | |||
| 358 | __END__ |