Skip to content
Snippets Groups Projects
Select Git revision
  • a0b686664b4e57a4acec12e16526ba56e99cf185
  • master default protected
  • 2024-11
  • oprava-babel
  • 2024-1
  • 2023
  • 2022
7 results

Home.js

Blame
  • CF.pm 2.77 KiB
    package CF;
    use Mojo::Base 'Mojolicious';
    use Mojo::Pg;
    use Mojo::JWT;
    use CF::Schema;
    
    # This method will run once at server start
    sub startup {
        my $self = shift;
    
        my $cfg = $self->plugin('Config' => { file => 'cf.conf'} );
        $self->helper( cfg => sub { return $cfg; } );
    
        # Konfigurace z ENV ma prednost
        KEY:
        foreach my $key ( keys %ENV ) {
            if ( $key =~ /^CFG_(.+)/i ) {
                $cfg->{lc($1)} = $ENV{$key};
            }
        }
    
        # migrace schematu
        my $pg = Mojo::Pg->new
            ->dsn($cfg->{db_dsn})
            ->username($cfg->{db_username})
            ->password($cfg->{db_password})
        ;
        $pg->migrations->from_dir($self->home . '/sql');
        $pg->migrations->migrate();
        $self->helper( pg => sub { return $pg; } );
    
        # DB Schema
        my $schema = CF::Schema->connect({
            dsn      => $cfg->{db_dsn},
            user     => $cfg->{db_username},
            password => $cfg->{db_password}
        });
        $self->helper( schema => sub { return $schema; } );
    
        $self->plugin('CF::Helpers::Core');
        $self->plugin('CF::Helpers::Auth');
    
        $self->plugin("OpenAPI" => {
            url    => $self->home . '/openapi.yaml',
            schema => 'v3',
            plugins                        => [qw(+SpecRenderer +Cors +Security)],
            render_specification           => 1,
            render_specification_for_paths => 1,
            default_response_codes         => [400, 401, 403, 404, 500, 501],
    
            security => {
                Bearer => sub {
                    my ($c, $definition, $scopes, $cb ) = @_;
    
                    my $key = $c->req->headers->authorization;
    
                    # moznost nepovinneho bez tokenu
                    return $c->$cb() if $scopes->[0] && $scopes->[0] eq 'optional' && ! $key;
    
                    return $c->$cb('Authorization header not present') if ! $key;
                    return $c->$cb('Unsupported authorization type') if $key !~ s/Bearer\s+//i;
    
                    $c->oauth_token($key);
    
                    if (! $c->user ) {
                        return $c->$cb('Invalid user');
                    }
    
                    my $user = $c->schema->resultset('User')->find_or_create(
                        $c->user, { key => 'uuid'}