:- http_handler(root(login), login_view(Method), [method(Method), methods([get, post])]). :- http_handler(root(logout), logout_view, []). :- http_handler(root('style.css'), http_reply_file('style.css', []), []). login_reason --> { http_session_data(reason(Reason)), http_session_retract(reason(_)) }, !, html(div(class=login__reason, Reason)). login_reason --> []. login_view(get, _Request) :- reply_html_page( [ title('point of shit'), link([ type('text/css'), rel('stylesheet'), href('style.css') ]) ], [ h1('Login'), \login_reason, form([method=post], [ div([ label(for=username, 'Username'), input([ type=text, placeholder='Username', name=username, id=username, autofocus, required ]) ]), div([ label(for=password, 'Password'), input([ type=password, placeholder='Username', name=password, id=password, required ]) ]), div( input([ type=submit, value='Log in' ]) ) ]) ] ). login_view(post, Request) :- http_read_data(Request, [username=Username, password=Password], []), 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). % Handles logging in, returning the correct Json in Reply. handle_login(Username, Password, Request) :- user(Username, Hash), crypto_password_hash(Password, Hash), !, http_session_assert(user(Username)), (http_session_retract(from(From)); From = .), http_redirect(see_other, root(From), Request). handle_login(Username, _, Request) :- user(Username, _), !, 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). logout_view(Request) :- http_redirect(see_other, root(.), Request).