summaryrefslogtreecommitdiff
path: root/lib/Travelynx
diff options
context:
space:
mode:
authorDaniel Friesel <derf@finalrewind.org>2019-03-21 22:12:45 +0100
committerDaniel Friesel <derf@finalrewind.org>2019-03-21 22:12:45 +0100
commit21fe8a6990e996a556066e0142ede258df429a5b (patch)
tree4f4fed261f1aba3a75e514a5fbb54c9a02945d11 /lib/Travelynx
parent0a9d2e4c88f46fb8f5ea91009b16c84403d546e2 (diff)
Initiate transition to a Mojolicious MVC web application
Diffstat (limited to 'lib/Travelynx')
-rwxr-xr-xlib/Travelynx/Controller/Api.pm126
-rwxr-xr-xlib/Travelynx/Controller/Login.pm230
-rwxr-xr-xlib/Travelynx/Controller/Traveling.pm241
3 files changed, 597 insertions, 0 deletions
diff --git a/lib/Travelynx/Controller/Api.pm b/lib/Travelynx/Controller/Api.pm
new file mode 100755
index 0000000..435c644
--- /dev/null
+++ b/lib/Travelynx/Controller/Api.pm
@@ -0,0 +1,126 @@
+package Travelynx::Controller::Api;
+use Mojo::Base 'Mojolicious::Controller';
+
+use Travel::Status::DE::IRIS::Stations;
+use UUID::Tiny qw(:std);
+
+my %token_type = (
+ status => 1,
+ history => 2,
+ action => 3,
+);
+my @token_types = (qw(status history action));
+
+sub make_token {
+ return create_uuid_as_string(UUID_V4);
+}
+
+sub get_v0 {
+ my ($self) = @_;
+
+ my $api_action = $self->stash('user_action');
+ my $api_token = $self->stash('token');
+ if ( $api_action !~ qr{ ^ (?: status | history | action ) $ }x ) {
+ $self->render(
+ json => {
+ error => 'Invalid action',
+ },
+ );
+ return;
+ }
+ if ( $api_token !~ qr{ ^ (?<id> \d+ ) - (?<token> .* ) $ }x ) {
+ $self->render(
+ json => {
+ error => 'Malformed token',
+ },
+ );
+ return;
+ }
+ my $uid = $+{id};
+ $api_token = $+{token};
+ my $token = $self->get_api_token($uid);
+ if ( $api_token ne $token->{$api_action} ) {
+ $self->render(
+ json => {
+ error => 'Invalid token',
+ },
+ );
+ return;
+ }
+ if ( $api_action eq 'status' ) {
+ my $status = $self->get_user_status($uid);
+
+ my @station_descriptions;
+ my $station_eva = undef;
+ my $station_lon = undef;
+ my $station_lat = undef;
+
+ if ( $status->{station_ds100} ) {
+ @station_descriptions
+ = Travel::Status::DE::IRIS::Stations::get_station(
+ $status->{station_ds100} );
+ }
+ if ( @station_descriptions == 1 ) {
+ ( undef, undef, $station_eva, $station_lon, $station_lat )
+ = @{ $station_descriptions[0] };
+ }
+ $self->render(
+ json => {
+ deprecated => \0,
+ checked_in => (
+ $status->{checked_in}
+ or $status->{cancelled}
+ ) ? \1 : \0,
+ station => {
+ ds100 => $status->{station_ds100},
+ name => $status->{station_name},
+ uic => $station_eva,
+ longitude => $station_lon,
+ latitude => $station_lat,
+ },
+ train => {
+ type => $status->{train_type},
+ line => $status->{train_line},
+ no => $status->{train_no},
+ },
+ actionTime => $status->{timestamp}->epoch,
+ scheduledTime => $status->{sched_ts}->epoch,
+ realTime => $status->{real_ts}->epoch,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ error => 'not implemented',
+ },
+ );
+ }
+}
+
+sub set_token {
+ my ($self) = @_;
+ if ( $self->validation->csrf_protect->has_error('csrf_token') ) {
+ $self->render( 'account', invalid => 'csrf' );
+ return;
+ }
+ my $token = make_token();
+ my $token_id = $token_type{ $self->param('token') };
+
+ if ( not $token_id ) {
+ $self->redirect_to('account');
+ return;
+ }
+
+ if ( $self->param('action') eq 'delete' ) {
+ $self->app->drop_api_token_query->execute( $self->current_user->{id},
+ $token_id );
+ }
+ else {
+ $self->app->set_api_token_query->execute( $self->current_user->{id},
+ $token_id, $token );
+ }
+ $self->redirect_to('account');
+}
+
+1;
diff --git a/lib/Travelynx/Controller/Login.pm b/lib/Travelynx/Controller/Login.pm
new file mode 100755
index 0000000..9752414
--- /dev/null
+++ b/lib/Travelynx/Controller/Login.pm
@@ -0,0 +1,230 @@
+package Travelynx::Controller::Login;
+use Mojo::Base 'Mojolicious::Controller';
+
+use Crypt::Eksblowfish::Bcrypt qw(bcrypt en_base64);
+use Encode qw(decode encode);
+use Email::Sender::Simple qw(try_to_sendmail);
+use Email::Simple;
+use UUID::Tiny qw(:std);
+
+sub hash_password {
+ my ($password) = @_;
+ my @salt_bytes = map { int( rand(255) ) + 1 } ( 1 .. 16 );
+ my $salt = en_base64( pack( 'C[16]', @salt_bytes ) );
+
+ return bcrypt( $password, '$2a$12$' . $salt );
+}
+
+sub make_token {
+ return create_uuid_as_string(UUID_V4);
+}
+
+sub login_form {
+ my ($self) = @_;
+ $self->render('login');
+}
+
+sub do_login {
+ my ($self) = @_;
+ my $user = $self->req->param('user');
+ my $password = $self->req->param('password');
+
+ # Keep cookies for 6 months
+ $self->session( expiration => 60 * 60 * 24 * 180 );
+
+ if ( $self->validation->csrf_protect->has_error('csrf_token') ) {
+ $self->render(
+ 'login',
+ invalid => 'csrf',
+ );
+ }
+ else {
+ if ( $self->authenticate( $user, $password ) ) {
+ $self->redirect_to( $self->req->param('redirect_to') // '/' );
+ }
+ else {
+ my $data = $self->get_user_password($user);
+ if ( $data and $data->{status} == 0 ) {
+ $self->render( 'login', invalid => 'confirmation' );
+ }
+ else {
+ $self->render( 'login', invalid => 'credentials' );
+ }
+ }
+ }
+}
+
+sub registration_form {
+ my ($self) = @_;
+ $self->render('register');
+}
+
+sub register {
+ my ($self) = @_;
+ my $user = $self->req->param('user');
+ my $email = $self->req->param('email');
+ my $password = $self->req->param('password');
+ my $password2 = $self->req->param('password2');
+ my $ip = $self->req->headers->header('X-Forwarded-For');
+ my $ua = $self->req->headers->user_agent;
+ my $date = DateTime->now( time_zone => 'Europe/Berlin' )
+ ->strftime('%d.%m.%Y %H:%M:%S %z');
+
+ # In case Mojolicious is not running behind a reverse proxy
+ $ip
+ //= sprintf( '%s:%s', $self->tx->remote_address, $self->tx->remote_port );
+
+ if ( $self->validation->csrf_protect->has_error('csrf_token') ) {
+ $self->render(
+ 'register',
+ invalid => 'csrf',
+ );
+ return;
+ }
+
+ if ( not length($user) ) {
+ $self->render( 'register', invalid => 'user_empty' );
+ return;
+ }
+
+ if ( not length($email) ) {
+ $self->render( 'register', invalid => 'mail_empty' );
+ return;
+ }
+
+ if ( $user !~ m{ ^ [0-9a-zA-Z_-]+ $ }x ) {
+ $self->render( 'register', invalid => 'user_format' );
+ return;
+ }
+
+ if ( $self->check_if_user_name_exists($user) ) {
+ $self->render( 'register', invalid => 'user_collision' );
+ return;
+ }
+
+ if ( $self->check_if_mail_is_blacklisted($email) ) {
+ $self->render( 'register', invalid => 'mail_blacklisted' );
+ return;
+ }
+
+ if ( $password ne $password2 ) {
+ $self->render( 'register', invalid => 'password_notequal' );
+ return;
+ }
+
+ if ( length($password) < 8 ) {
+ $self->render( 'register', invalid => 'password_short' );
+ return;
+ }
+
+ my $token = make_token();
+ my $pw_hash = hash_password($password);
+ $self->app->dbh->begin_work;
+ my $user_id = $self->add_user( $user, $email, $token, $pw_hash );
+ my $reg_url = $self->url_for('reg')->to_abs->scheme('https');
+ my $imprint_url = $self->url_for('impressum')->to_abs->scheme('https');
+
+ my $body = "Hallo, ${user}!\n\n";
+ $body .= "Mit deiner E-Mail-Adresse (${email}) wurde ein Account bei\n";
+ $body .= "travelynx angelegt.\n\n";
+ $body
+ .= "Falls die Registrierung von dir ausging, kannst du den Account unter\n";
+ $body .= "${reg_url}/${user_id}/${token}\n";
+ $body .= "freischalten.\n\n";
+ $body
+ .= "Falls nicht, ignoriere diese Mail bitte. Nach etwa 48 Stunden wird deine\n";
+ $body
+ .= "Mail-Adresse erneut zur Registrierung freigeschaltet. Falls auch diese fehlschlägt,\n";
+ $body
+ .= "werden wir sie dauerhaft sperren und keine Mails mehr dorthin schicken.\n\n";
+ $body .= "Daten zur Registrierung:\n";
+ $body .= " * Datum: ${date}\n";
+ $body .= " * Verwendete IP: ${ip}\n";
+ $body .= " * Verwendeter Browser gemäß User Agent: ${ua}\n\n\n";
+ $body .= "Impressum: ${imprint_url}\n";
+
+ my $reg_mail = Email::Simple->create(
+ header => [
+ To => $email,
+ From => 'Travelynx <travelynx@finalrewind.org>',
+ Subject => 'Registrierung bei travelynx',
+ 'Content-Type' => 'text/plain; charset=UTF-8',
+ ],
+ body => encode( 'utf-8', $body ),
+ );
+
+ my $success = try_to_sendmail($reg_mail);
+ if ($success) {
+ $self->app->dbh->commit;
+ $self->render( 'login', from => 'register' );
+ }
+ else {
+ $self->app->dbh->rollback;
+ $self->render( 'register', invalid => 'sendmail' );
+ }
+}
+
+sub verify {
+ my ($self) = @_;
+
+ my $id = $self->stash('id');
+ my $token = $self->stash('token');
+
+ my @db_user = $self->get_user_token($id);
+
+ if ( not @db_user ) {
+ $self->render( 'register', invalid => 'token' );
+ return;
+ }
+
+ my ( $db_name, $db_status, $db_token ) = @db_user;
+
+ if ( not $db_name or $token ne $db_token or $db_status != 0 ) {
+ $self->render( 'register', invalid => 'token' );
+ return;
+ }
+ $self->app->set_status_query->execute( 1, $id );
+ $self->render( 'login', from => 'verification' );
+}
+
+sub delete {
+ my ($self) = @_;
+ if ( $self->validation->csrf_protect->has_error('csrf_token') ) {
+ $self->render( 'account', invalid => 'csrf' );
+ return;
+ }
+
+ my $now = DateTime->now( time_zone => 'Europe/Berlin' )->epoch;
+
+ if ( $self->param('action') eq 'delete' ) {
+ if (
+ not $self->authenticate(
+ $self->current_user->{name},
+ $self->param('password')
+ )
+ )
+ {
+ $self->render( 'account', invalid => 'password' );
+ return;
+ }
+ $self->app->mark_for_deletion_query->execute( $now,
+ $self->current_user->{id} );
+ }
+ else {
+ $self->app->mark_for_deletion_query->execute( undef,
+ $self->current_user->{id} );
+ }
+ $self->redirect_to('account');
+}
+
+sub do_logout {
+ my ($self) = @_;
+ if ( $self->validation->csrf_protect->has_error('csrf_token') ) {
+ $self->render( 'login', invalid => 'csrf' );
+ return;
+ }
+ $self->logout;
+ $self->redirect_to('/login');
+}
+
+1;
diff --git a/lib/Travelynx/Controller/Traveling.pm b/lib/Travelynx/Controller/Traveling.pm
new file mode 100755
index 0000000..8d71d95
--- /dev/null
+++ b/lib/Travelynx/Controller/Traveling.pm
@@ -0,0 +1,241 @@
+package Travelynx::Controller::Traveling;
+use Mojo::Base 'Mojolicious::Controller';
+
+use Travel::Status::DE::IRIS::Stations;
+
+my %action_type = (
+ checkin => 1,
+ checkout => 2,
+ undo => 3,
+ cancelled_from => 4,
+ cancelled_to => 5,
+);
+my @action_types = (qw(checkin checkout undo cancelled_from cancelled_to));
+
+sub homepage {
+ my ($self) = @_;
+ if ( $self->is_user_authenticated ) {
+ $self->render( 'landingpage', with_geolocation => 1 );
+ }
+ else {
+ $self->render( 'landingpage', intro => 1 );
+ }
+}
+
+sub geolocation {
+ my ($self) = @_;
+
+ my $lon = $self->param('lon');
+ my $lat = $self->param('lat');
+
+ if ( not $lon or not $lat ) {
+ $self->render( json => { error => 'Invalid lon/lat received' } );
+ }
+ else {
+ my @candidates = map {
+ {
+ ds100 => $_->[0][0],
+ name => $_->[0][1],
+ eva => $_->[0][2],
+ lon => $_->[0][3],
+ lat => $_->[0][4],
+ distance => $_->[1],
+ }
+ } Travel::Status::DE::IRIS::Stations::get_station_by_location( $lon,
+ $lat, 5 );
+ $self->render(
+ json => {
+ candidates => [@candidates],
+ }
+ );
+ }
+}
+
+sub log_action {
+ my ($self) = @_;
+ my $params = $self->req->json;
+
+ if ( not exists $params->{action} ) {
+ $params = $self->req->params->to_hash;
+ }
+
+ if ( not $self->is_user_authenticated ) {
+
+ # We deliberately do not set the HTTP status for these replies, as it
+ # confuses jquery.
+ $self->render(
+ json => {
+ success => 0,
+ error => 'Session error, please login again',
+ },
+ );
+ return;
+ }
+
+ if ( not $params->{action} ) {
+ $self->render(
+ json => {
+ success => 0,
+ error => 'Missing action value',
+ },
+ );
+ return;
+ }
+
+ my $station = $params->{station};
+
+ if ( $params->{action} eq 'checkin' ) {
+
+ my ( $train, $error )
+ = $self->checkin( $params->{station}, $params->{train} );
+
+ if ($error) {
+ $self->render(
+ json => {
+ success => 0,
+ error => $error,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ success => 1,
+ },
+ );
+ }
+ }
+ elsif ( $params->{action} eq 'checkout' ) {
+ my $error = $self->checkout( $params->{station}, $params->{force} );
+
+ if ($error) {
+ $self->render(
+ json => {
+ success => 0,
+ error => $error,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ success => 1,
+ },
+ );
+ }
+ }
+ elsif ( $params->{action} eq 'undo' ) {
+ my $error = $self->undo;
+ if ($error) {
+ $self->render(
+ json => {
+ success => 0,
+ error => $error,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ success => 1,
+ },
+ );
+ }
+ }
+ elsif ( $params->{action} eq 'cancelled_from' ) {
+ my ( undef, $error )
+ = $self->checkin( $params->{station}, $params->{train},
+ $action_type{cancelled_from} );
+
+ if ($error) {
+ $self->render(
+ json => {
+ success => 0,
+ error => $error,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ success => 1,
+ },
+ );
+ }
+ }
+ elsif ( $params->{action} eq 'cancelled_to' ) {
+ my $error = $self->checkout( $params->{station}, 1,
+ $action_type{cancelled_to} );
+
+ if ($error) {
+ $self->render(
+ json => {
+ success => 0,
+ error => $error,
+ },
+ );
+ }
+ else {
+ $self->render(
+ json => {
+ success => 1,
+ },
+ );
+ }
+ }
+ else {
+ $self->render(
+ json => {
+ success => 0,
+ error => 'invalid action value',
+ },
+ );
+ }
+}
+
+sub station {
+ my ($self) = @_;
+ my $station = $self->stash('station');
+ my $train = $self->param('train');
+
+ my $status = $self->get_departures($station);
+
+ if ( $status->{errstr} ) {
+ $self->render(
+ 'landingpage',
+ with_geolocation => 1,
+ error => $status->{errstr}
+ );
+ }
+ else {
+ # You can't check into a train which terminates here
+ my @results = grep { $_->departure } @{ $status->{results} };
+
+ @results = map { $_->[0] }
+ sort { $b->[1] <=> $a->[1] }
+ map { [ $_, $_->departure->epoch // $_->sched_departure->epoch ] }
+ @results;
+
+ if ($train) {
+ @results
+ = grep { $_->type . ' ' . $_->train_no eq $train } @results;
+ }
+
+ $self->render(
+ 'departures',
+ ds100 => $status->{station_ds100},
+ results => \@results,
+ station => $status->{station_name},
+ title => "travelynx: $status->{station_name}",
+ );
+ }
+}
+
+sub redirect_to_station {
+ my ($self) = @_;
+ my $station = $self->param('station');
+
+ $self->redirect_to("/s/${station}");
+}
+
+1;