From 75134c0cf6a9dc67f7194f950277218acd683117 Mon Sep 17 00:00:00 2001 From: Sijmen Schoon Date: Fri, 1 Nov 2019 01:13:23 +0100 Subject: [PATCH] why am i making a login system --- main.pl | 18 ++++++++++++++++++ routes/login.pl | 30 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 routes/login.pl diff --git a/main.pl b/main.pl index 38f4f7a..07c568a 100644 --- a/main.pl +++ b/main.pl @@ -1,6 +1,7 @@ :- use_module(library(http/http_server)). :- use_module(library(http/http_client)). :- use_module(library(http/http_json)). +:- use_module(library(http/http_header)). :- use_module(library(http/json_convert)). :- use_module(library(http/json)). :- use_module(library(persistency)). @@ -16,4 +17,21 @@ :- persistent product(name:atom, price:integer). +:- json_object + login(username:atom, password:atom). + +:- json_object + user(username:atom, password_hash:atom). +:- persistent + user(username:atom, password_hash:atom). + +:- json_object + token(username:atom, token:atom). +:- persistent + token(username:atom, token:atom). + +:- json_object + error(error:atom). + :- consult('routes/products.pl'). +:- consult('routes/login.pl'). diff --git a/routes/login.pl b/routes/login.pl new file mode 100644 index 0000000..9407b81 --- /dev/null +++ b/routes/login.pl @@ -0,0 +1,30 @@ +:- http_handler( + root(login), + login_route, + [] +). + +% Handles logging in, returning the correct Json in Reply. +handle_login(Username, Password, Reply) :- + user(Username, Hash), + crypto_password_hash(Password, Hash), !, + crypto_n_random_bytes(16, Bytes), + hex_bytes(Token, Bytes), + assert_token(Username, Token), + prolog_to_json(token(Username, Token), Reply). + +handle_login(Username, _, Reply) :- + user(Username, _), !, + prolog_to_json(error(incorrect_password), Reply). + +handle_login(_, _, Reply) :- + prolog_to_json(error(unknown_user), Reply). + + +% POST /login +login_route(Request) :- + member(method(post), Request), !, + http_read_data(Request, Json, []), + json_to_prolog(Json, login(Username, Password)), + handle_login(Username, Password, Reply), + reply_json(Reply).