Commit 32cc2f0f authored by Birte Kristina Friesel's avatar Birte Kristina Friesel
Browse files

More refactoring

parent 0243a114
Loading
Loading
Loading
Loading
+57 −174
Original line number Diff line number Diff line
@@ -27,23 +27,6 @@ my $cache_iris_rt = Cache::File->new(
	lock_level      => Cache::File::LOCK_LOCAL(),
);

my $dbname = $ENV{TRAVELYNX_DB_FILE} // 'travelynx.sqlite';

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));
my %token_type   = (
	status  => 1,
	history => 2,
	action  => 3,
);
my @token_types = (qw(status history action));

sub hash_password {
	my ($password) = @_;
	my @salt_bytes = map { int( rand(255) ) + 1 } ( 1 .. 16 );
@@ -135,6 +118,29 @@ $self->sessions->default_expiration( 60 * 60 * 24 * 180 );

$self->defaults( layout => 'default' );

$self->attr(action_type => sub {
	return {
	checkin        => 1,
	checkout       => 2,
	undo           => 3,
	cancelled_from => 4,
	cancelled_to   => 5,
}});
$self->attr(action_types => sub {
	return [
	qw(checkin checkout undo cancelled_from cancelled_to)
]});
$self->attr(token_type => sub {
	return {
	status  => 1,
	history => 2,
	action  => 3,
}});
$self->attr(token_types => sub {
	return [
	qw(status history action)
]});

$self->attr(
	add_station_query => sub {
		my ($self) = @_;
@@ -242,6 +248,8 @@ $self->attr(
	dbh => sub {
		my ($self) = @_;

		my $dbname = $ENV{TRAVELYNX_DB_FILE} // 'travelynx.sqlite';

		return DBI->connect( "dbi:SQLite:dbname=${dbname}", q{}, q{} );
	}
);
@@ -442,7 +450,7 @@ $self->attr(
			insert into user_actions (
				user_id, action_id, action_time
			) values (
				?, $action_type{undo}, ?
				?, $self->app->action_type->{undo}, ?
			)
		}
		);
@@ -494,7 +502,7 @@ $self->helper('get_departures' => sub {
$self->helper('checkin' => sub {
	my ( $self, $station, $train_id, $action_id ) = @_;

	$action_id //= $action_type{checkin};
	$action_id //= $self->app->action_type->{checkin};

	my $status = $self->get_departures($station);
	if ( $status->{errstr} ) {
@@ -566,11 +574,11 @@ $self->helper('undo' => sub {
	$self->app->get_last_actions_query->execute($uid);
	my $rows = $self->app->get_last_actions_query->fetchall_arrayref;

	if ( @{$rows} and $rows->[0][0] == $action_type{undo} ) {
	if ( @{$rows} and $rows->[0][0] == $self->app->action_type->{undo} ) {
		return 'Nested undo (undoing an undo) is not supported';
	}

	if ( @{$rows} > 1 and $rows->[1][0] == $action_type{undo} ) {
	if ( @{$rows} > 1 and $rows->[1][0] == $self->app->action_type->{undo} ) {
		return 'Repeated undo is not supported';
	}

@@ -590,7 +598,7 @@ $self->helper('undo' => sub {
$self->helper('checkout' => sub {
	my ( $self, $station, $force, $action_id ) = @_;

	$action_id //= $action_type{checkout};
	$action_id //= $self->app->action_type->{checkout};

	my $status   = $self->get_departures( $station, 180 );
	my $user     = $self->get_user_status;
@@ -632,7 +640,7 @@ $self->helper('checkout' => sub {
	else {
		my $success = $self->app->action_query->execute(
			$self->current_user->{id},
			$action_type{checkout},
			$self->app->action_type->{checkout},
			$self->get_station_id(
				ds100 => $status->{station_ds100},
				name  => $status->{station_name}
@@ -730,7 +738,7 @@ $self->helper('get_api_token' => sub {
	my $rows  = $self->app->get_api_tokens_query->fetchall_arrayref;
	my $token = {};
	for my $row ( @{$rows} ) {
		$token->{ $token_types[ $row->[0] - 1 ] } = $row->[1];
		$token->{ $self->app->token_types->[ $row->[0] - 1 ] } = $row->[1];
	}
	return $token;
});
@@ -822,10 +830,10 @@ $self->helper('get_user_travels' => sub {
	else {
		$query->execute($uid);
	}
	my @match_actions = ( $action_type{checkout}, $action_type{checkin} );
	my @match_actions = ( $self->app->action_type->{checkout}, $self->app->action_type->{checkin} );
	if ( $opt{cancelled} ) {
		@match_actions
		  = ( $action_type{cancelled_to}, $action_type{cancelled_from} );
		  = ( $self->app->action_type->{cancelled_to}, $self->app->action_type->{cancelled_from} );
	}

	my @travels;
@@ -918,7 +926,7 @@ $self->helper('get_user_travels' => sub {
					/ 3600 );
			}
			if (    $opt{checkin_epoch}
				and $action == $action_type{cancelled_from} )
				and $action == $self->app->action_type->{cancelled_from} )
			{
				$ref->{cancelled} = 1;
			}
@@ -940,7 +948,7 @@ $self->helper('get_user_status' => sub {
		my $now = DateTime->now( time_zone => 'Europe/Berlin' );

		my @cols = @{ $rows->[0] };
		if ( @{$rows} > 2 and $rows->[0][0] == $action_type{undo} ) {
		if ( @{$rows} > 2 and $rows->[0][0] == $self->app->action_type->{undo} ) {
			@cols = @{ $rows->[2] };
		}

@@ -960,8 +968,8 @@ $self->helper('get_user_status' => sub {
			}
		}
		return {
			checked_in      => ( $cols[0] == $action_type{checkin} ),
			cancelled       => ( $cols[0] == $action_type{cancelled_from} ),
			checked_in      => ( $cols[0] == $self->app->action_type->{checkin} ),
			cancelled       => ( $cols[0] == $self->app->action_type->{cancelled_from} ),
			timestamp       => $action_ts,
			timestamp_delta => $now->epoch - $action_ts->epoch,
			sched_ts        => $sched_ts,
@@ -1025,41 +1033,20 @@ $self->helper('navbar_class' => sub {

my $r = $self->routes;

$r->get('/')->to('traveling#homepage');

$r->get('/about' => sub {
	my ($self) = @_;

	$self->render( 'about', version => $VERSION );
});

$r->get('/impressum' => sub {
	my ($self) = @_;

	$self->render('imprint');
});

$r->get('/imprint' => sub {
	my ($self) = @_;

	$self->render('imprint');
});

$r->post('/geolocation')->to('traveling#geolocation');

$r->post('/list_departures')->to('traveling#redirect_to_station');

$r->get('/')->to('traveling#homepage');
$r->get('/about')->to('static#about');
$r->get('/impressum')->to('static#imprint');
$r->get('/imprint')->to('static#imprint');
$r->get('/api/v0/:user_action/:token')->to('api#get_v0');

$r->get('/login')->to('login#login_form');
$r->post('/login')->to('login#do_login');

$r->get('/register')->to('login#registration_form');
$r->post('/register')->to('login#register');

$r->get('/reg/:id/:token')->to('login#verify');

$r->get('/login')->to('account#login_form');
$r->get('/register')->to('account#registration_form');
$r->get('/reg/:id/:token')->to('account#verify');
$r->post('/action')->to('traveling#log_action');
$r->post('/geolocation')->to('traveling#geolocation');
$r->post('/list_departures')->to('traveling#redirect_to_station');
$r->post('/login')->to('account#do_login');
$r->post('/register')->to('account#register');

my $authed_r = $r->under(sub {
	my ($self) = @_;
@@ -1070,119 +1057,15 @@ my $authed_r = $r->under(sub {
	return undef;
});

$authed_r->get('/account' => sub {
	my ($self) = @_;

	$self->render('account');
});

$authed_r->get('/history' => sub {
	my ($self) = @_;
	my $cancelled = $self->param('cancelled') ? 1 : 0;

	$self->respond_to(
		json =>
		  { json => [ $self->get_user_travels( cancelled => $cancelled ) ] },
		any => { template => 'history' }
	);
});

$authed_r->get('/history.json' => sub {
	my ($self) = @_;
	my $cancelled = $self->param('cancelled') ? 1 : 0;

	$self->render(
		json => [ $self->get_user_travels( cancelled => $cancelled ) ] );
});

$authed_r->get('/journey/:id' => sub {
	my ($self) = @_;
	my ( $uid, $checkin_ts, $checkout_ts ) = split( qr{-}, $self->stash('id') );

	if ( $uid != $self->current_user->{id} ) {
		$self->render(
			'journey',
			error   => 'notfound',
			journey => {}
		);
		return;
	}

	my @journeys = $self->get_user_travels(
		uid            => $uid,
		checkin_epoch  => $checkin_ts,
		checkout_epoch => $checkout_ts,
		verbose        => 1,
	);
	if ( @journeys == 0 ) {
		$self->render(
			'journey',
			error   => 'notfound',
			journey => {}
		);
		return;
	}

	$self->render(
		'journey',
		error   => undef,
		journey => $journeys[0]
	);
});

$authed_r->get('/export.json' => sub {
	my ($self) = @_;
	my $uid    = $self->current_user->{id};
	my $query  = $self->app->get_all_actions_query;

	$query->execute($uid);

	my @entries;

	while ( my @row = $query->fetchrow_array ) {
		my (
			$action,       $raw_ts,      $ds100,     $name,
			$train_type,   $train_line,  $train_no,  $train_id,
			$raw_sched_ts, $raw_real_ts, $raw_route, $raw_messages
		) = @row;

		$name         = decode( 'UTF-8', $name );
		$raw_route    = decode( 'UTF-8', $raw_route );
		$raw_messages = decode( 'UTF-8', $raw_messages );
		push(
			@entries,
			{
				action        => $action_types[ $action - 1 ],
				action_ts     => $raw_ts,
				station_ds100 => $ds100,
				station_name  => $name,
				train_type    => $train_type,
				train_line    => $train_line,
				train_no      => $train_no,
				train_id      => $train_id,
				scheduled_ts  => $raw_sched_ts,
				realtime_ts   => $raw_real_ts,
				messages      => $raw_messages
				? [ map { [ split(qr{:}) ] } split( qr{[|]}, $raw_messages ) ]
				: undef,
				route => $raw_route ? [ split( qr{[|]}, $raw_route ) ]
				: undef,
			}
		);
	}

	$self->render(
		json => [@entries],
	);
});

$authed_r->post('/delete')->to('login#delete');

$authed_r->post('/logout')->to('login#do_logout');

$authed_r->post('/set_token')->to('api#set_token');

$authed_r->get('/account')->to('account#account');
$authed_r->get('/export.json')->to('account#json_export');
$authed_r->get('/history')->to('traveling#history');
$authed_r->get('/history.json')->to('traveling#json_history');
$authed_r->get('/journey/:id')->to('traveling#journey_details');
$authed_r->get('/s/*station')->to('traveling#station');
$authed_r->post('/delete')->to('account#delete');
$authed_r->post('/logout')->to('account#do_logout');
$authed_r->post('/set_token')->to('api#set_token');

}

+282 −0
Original line number Diff line number Diff line
package Travelynx::Controller::Account;
use Mojo::Base 'Mojolicious::Controller';

use Crypt::Eksblowfish::Bcrypt qw(bcrypt en_base64);
use Encode qw(decode);
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');
}

sub account {
	my ($self) = @_;

	$self->render('account');
}

sub json_export {
	my ($self) = @_;
	my $uid    = $self->current_user->{id};
	my $query  = $self->app->get_all_actions_query;

	$query->execute($uid);

	my @entries;

	while ( my @row = $query->fetchrow_array ) {
		my (
			$action,       $raw_ts,      $ds100,     $name,
			$train_type,   $train_line,  $train_no,  $train_id,
			$raw_sched_ts, $raw_real_ts, $raw_route, $raw_messages
		) = @row;

		$name         = decode( 'UTF-8', $name );
		$raw_route    = decode( 'UTF-8', $raw_route );
		$raw_messages = decode( 'UTF-8', $raw_messages );
		push(
			@entries,
			{
				action        => $self->app->action_types->[ $action - 1 ],
				action_ts     => $raw_ts,
				station_ds100 => $ds100,
				station_name  => $name,
				train_type    => $train_type,
				train_line    => $train_line,
				train_no      => $train_no,
				train_id      => $train_id,
				scheduled_ts  => $raw_sched_ts,
				realtime_ts   => $raw_real_ts,
				messages      => $raw_messages
				? [ map { [ split(qr{:}) ] } split( qr{[|]}, $raw_messages ) ]
				: undef,
				route => $raw_route ? [ split( qr{[|]}, $raw_route ) ]
				: undef,
			}
		);
	}

	$self->render(
		json => [@entries],
	);
}

1;
+1 −8
Original line number Diff line number Diff line
@@ -4,13 +4,6 @@ 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);
}
@@ -105,7 +98,7 @@ sub set_token {
		return;
	}
	my $token    = make_token();
	my $token_id = $token_type{ $self->param('token') };
	my $token_id = $self->app->token_type->{ $self->param('token') };

	if ( not $token_id ) {
		$self->redirect_to('account');
+18 −0
Original line number Diff line number Diff line
package Travelynx::Controller::Static;
use Mojo::Base 'Mojolicious::Controller';

my $travelynx_version = qx{git describe --dirty} || 'experimental';

sub about {
	my ($self) = @_;

	$self->render( 'about', version => $travelynx_version );
}

sub imprint {
	my ($self) = @_;

	$self->render('imprint');
}

1;
+56 −11
Original line number Diff line number Diff line
@@ -3,15 +3,6 @@ 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 ) {
@@ -145,7 +136,7 @@ sub log_action {
	elsif ( $params->{action} eq 'cancelled_from' ) {
		my ( undef, $error )
		  = $self->checkin( $params->{station}, $params->{train},
			$action_type{cancelled_from} );
			$self->app->action_type->{cancelled_from} );

		if ($error) {
			$self->render(
@@ -165,7 +156,7 @@ sub log_action {
	}
	elsif ( $params->{action} eq 'cancelled_to' ) {
		my $error = $self->checkout( $params->{station}, 1,
			$action_type{cancelled_to} );
			$self->app->action_type->{cancelled_to} );

		if ($error) {
			$self->render(
@@ -238,4 +229,58 @@ sub redirect_to_station {
	$self->redirect_to("/s/${station}");
}

sub history {
	my ($self) = @_;
	my $cancelled = $self->param('cancelled') ? 1 : 0;

	$self->respond_to(
		json =>
		  { json => [ $self->get_user_travels( cancelled => $cancelled ) ] },
		any => { template => 'history' }
	);
}

sub json_history {
	my ($self) = @_;
	my $cancelled = $self->param('cancelled') ? 1 : 0;

	$self->render(
		json => [ $self->get_user_travels( cancelled => $cancelled ) ] );
}

sub journey_details {
	my ($self) = @_;
	my ( $uid, $checkin_ts, $checkout_ts ) = split( qr{-}, $self->stash('id') );

	if ( $uid != $self->current_user->{id} ) {
		$self->render(
			'journey',
			error   => 'notfound',
			journey => {}
		);
		return;
	}

	my @journeys = $self->get_user_travels(
		uid            => $uid,
		checkin_epoch  => $checkin_ts,
		checkout_epoch => $checkout_ts,
		verbose        => 1,
	);
	if ( @journeys == 0 ) {
		$self->render(
			'journey',
			error   => 'notfound',
			journey => {}
		);
		return;
	}

	$self->render(
		'journey',
		error   => undef,
		journey => $journeys[0]
	);
}

1;