prolog-point-of-sale/views/login.pl

100 lines
2.8 KiB
Perl
Raw Normal View History

2019-11-03 01:05:33 +00:00
:- http_handler(root(login), login_view(Method), [method(Method), methods([get, post])]).
2019-11-03 15:19:31 +00:00
:- http_handler(root(logout), logout_view, []).
2019-11-03 01:05:33 +00:00
:- http_handler(root('style.css'), http_reply_file('style.css', []), []).
2019-11-03 15:19:31 +00:00
login_reason -->
{
http_session_data(reason(Reason)),
http_session_retract(reason(_))
}, !,
html(div(class=login__reason, Reason)).
login_reason --> [].
2019-11-03 01:05:33 +00:00
login_view(get, _Request) :-
reply_html_page(
[
title('point of shit'),
link([
type('text/css'),
rel('stylesheet'),
href('style.css')
])
],
[
h1('Login'),
2019-11-03 15:19:31 +00:00
\login_reason,
2019-11-03 01:05:33 +00:00
form([method=post], [
div([
label(for=username, 'Username'),
input([
type=text,
placeholder='Username',
name=username,
2019-11-03 15:19:31 +00:00
id=username,
autofocus,
required
2019-11-03 01:05:33 +00:00
])
]),
div([
label(for=password, 'Password'),
input([
type=password,
placeholder='Username',
name=password,
2019-11-03 15:19:31 +00:00
id=password,
required
2019-11-03 01:05:33 +00:00
])
]),
div(
input([
type=submit,
value='Log in'
])
)
])
]
).
login_view(post, Request) :-
http_read_data(Request, [username=Username, password=Password], []),
2019-11-03 15:19:31 +00:00
handle_login(Username, Password, Request).
create_user(Username, _) :-
user(Username, _), !,
format("User already exists.~n"),
false.
create_user(Username, Password) :-
crypto_password_hash(Password, Hash),
assert_user(Username, Hash).
2019-11-03 01:05:33 +00:00
% Handles logging in, returning the correct Json in Reply.
2019-11-03 15:19:31 +00:00
handle_login(Username, Password, Request) :-
2019-11-03 01:05:33 +00:00
user(Username, Hash),
crypto_password_hash(Password, Hash), !,
2019-11-03 15:19:31 +00:00
http_session_assert(user(Username)),
(http_session_retract(from(From)); From = .),
http_redirect(see_other, root(From), Request).
2019-11-03 01:05:33 +00:00
2019-11-03 15:19:31 +00:00
handle_login(Username, _, Request) :-
2019-11-03 01:05:33 +00:00
user(Username, _), !,
2019-11-03 15:19:31 +00:00
http_session_assert(reason('Invalid password.')),
http_redirect(see_other, root(login), Request).
handle_login(_, _, Request) :-
http_session_assert(reason('Unknown username.')),
http_redirect(see_other, root(login), Request).
logout_view(Request) :-
http_session_retract(user(_)),
http_redirect(see_other, root(.), Request).
2019-11-03 01:05:33 +00:00
2019-11-03 15:19:31 +00:00
logout_view(Request) :-
http_redirect(see_other, root(.), Request).