Push session management into helper functions as per #18

This commit is contained in:
ngoomie 2024-08-22 03:07:50 -06:00
parent f246841ca2
commit dca1e2bca5
3 changed files with 40 additions and 25 deletions

View File

@ -8,6 +8,7 @@ use feature ':5.20';
use Mojo::Base 'Mojolicious', -signatures; use Mojo::Base 'Mojolicious', -signatures;
use CharmBoard::Model::Schema; use CharmBoard::Model::Schema;
use CharmBoard::Util::Crypt::Seasoning;
# this method will run once at server start # this method will run once at server start
sub startup { sub startup {
@ -65,6 +66,43 @@ sub startup {
$self->helper(schema => sub { $schema }) $self->helper(schema => sub { $schema })
} }
# session helpers
## create session
$self->helper(session_create => sub {
my $self = shift;
my $_session_key = seasoning(16);
# create session entry in db
$self->schema->resultset('Session')->create({
session_key => $_session_key,
user_id => $_[0],
session_expiry => time + 604800,
is_ip_bound => 0,
bound_ip => undef
});
# now create session cookie
$self->session(is_auth => 1 );
$self->session(user_id => $_[0] );
$self->session(session_key => $_session_key);
$self->session(expiration => 604800 );
});
## destroy session
$self->helper(session_destroy => sub {
my $self = shift;
my $_session_key = $self->session('session_key');
# destroy entry for this session in the database
$self->schema->resultset('Session')
->search({ session_key => $_session_key })
->delete;
# now nuke the actual session cookie
$self->session(expires => 1);
});
# router # router
my $r = $self->routes; my $r = $self->routes;

View File

@ -53,24 +53,7 @@ sub login_do {
# get user ID for session creation # get user ID for session creation
$user_id = $user_info->get_column('user_id')->first; $user_id = $user_info->get_column('user_id')->first;
# gen session key $self->session_create($user_id);
$session_key = seasoning(16);
# add session to database
$self->schema->resultset('Session')->create({
session_key => $session_key,
user_id => $user_id,
session_expiry => time + 604800,
is_ip_bound => 0,
bound_ip => undef
})
or die;
# now create session cookie for user
$self->session(is_auth => 1 );
$self->session(user_id => $user_id );
$self->session(session_key => $session_key);
$self->session(expiration => 604800 );
# redirect to index upon success # redirect to index upon success
$self->redirect_to('/') $self->redirect_to('/')

View File

@ -11,13 +11,7 @@ use Mojo::Base 'Mojolicious::Controller', -signatures;
sub logout_do { sub logout_do {
my $self = shift; my $self = shift;
# destroy entry for this session in the database $self->session_destroy;
$self->schema->resultset('Session')
->search({ session_key => $self->session('session_key') })
->delete;
# now nuke the actual session cookie
$self->session(expires => 1);
# redirect to index # redirect to index
$self->redirect_to('/') $self->redirect_to('/')