| 1 | # | ||
| 2 | # (c) Jan Gehring <jan.gehring@gmail.com> | ||
| 3 | # | ||
| 4 | # vim: set ts=2 sw=2 tw=0: | ||
| 5 | # vim: set expandtab: | ||
| 6 | |||
| 7 | package Rex::Repositorio::Server::Docker::Mojolicious::Plugin::DockerSession; | ||
| 8 | |||
| 9 | use strict; | ||
| 10 | use warnings; | ||
| 11 | |||
| 12 | our $VERSION = '1.2.1'; # VERSION | ||
| 13 | |||
| 14 | use Mojo::Base 'Mojolicious::Plugin'; | ||
| 15 | use Data::Dumper; | ||
| 16 | use File::Spec; | ||
| 17 | use File::Path 'make_path', 'remove_tree'; | ||
| 18 | use JSON::XS; | ||
| 19 | require IO::All; | ||
| 20 | |||
| 21 | sub register { | ||
| 22 | my ( $self, $app ) = @_; | ||
| 23 | |||
| 24 | my $session_dir = | ||
| 25 | File::Spec->catdir( $app->get_repo_dir( repo => $app->repo->{name} ), | ||
| 26 | "_sessions" ); | ||
| 27 | |||
| 28 | $app->hook( | ||
| 29 | before_dispatch => sub { | ||
| 30 | my ( $self, $c ) = @_; | ||
| 31 | $app->log->debug("before_dispatch: DockerSession"); | ||
| 32 | $self->stash( "session_authenticated", 0 ); | ||
| 33 | |||
| 34 | if ( $self->req->headers->header("Authorization") ) { | ||
| 35 | my ( $type, $base64_header_line ) = | ||
| 36 | split( / /, $self->req->headers->header("Authorization"), 2 ); | ||
| 37 | if ( $type eq "Token" ) { | ||
| 38 | my ($session_id) = ( $base64_header_line =~ m/signature=([^,]+),/ ); | ||
| 39 | my $session_file = File::Spec->catfile( $session_dir, $session_id ); | ||
| 40 | if ( $session_id && -f $session_file ) { | ||
| 41 | my $ref = decode_json( IO::All->new($session_file)->slurp ); | ||
| 42 | $self->stash( "session_token", $session_id ); | ||
| 43 | $self->stash( "session_user", $ref->{user} ); | ||
| 44 | $self->stash( "session_authenticated", 1 ); | ||
| 45 | $self->stash( "upstream_docker_token", $ref->{upstream_docker_token} ); | ||
| 46 | } | ||
| 47 | } | ||
| 48 | } | ||
| 49 | }, | ||
| 50 | ); | ||
| 51 | |||
| 52 | $app->hook( | ||
| 53 | after_dispatch => sub { | ||
| 54 | my ( $self, $c ) = @_; | ||
| 55 | $app->log->debug("after_dispatch: DockerSession"); | ||
| 56 | |||
| 57 | if ( $self->stash->{session_changed} ) { | ||
| 58 | my $session_file = | ||
| 59 | File::Spec->catfile( $session_dir, $self->stash->{session_token} ); | ||
| 60 | |||
| 61 | if ( !-d $session_dir ) { | ||
| 62 | make_path $session_dir; | ||
| 63 | } | ||
| 64 | |||
| 65 | open( my $fh, ">", $session_file ) or die($!); | ||
| 66 | print $fh encode_json( | ||
| 67 | { | ||
| 68 | token => $self->stash->{session_token}, | ||
| 69 | user => $self->stash->{session_user}, | ||
| 70 | upstream_docker_token => $self->stash->{'upstream_docker_token'} || '', | ||
| 71 | } | ||
| 72 | ); | ||
| 73 | close($fh); | ||
| 74 | } | ||
| 75 | }, | ||
| 76 | ); | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; |