From 3a82baec9d793edf81ac2b151b0f4d4159641375 Mon Sep 17 00:00:00 2001
From: Freya Murphy <freya@freyacat.org>
Date: Mon, 1 Apr 2024 11:09:25 -0400
Subject: login and register, liking on homepage

---
 src/db/rest/login/api_login.sql | 41 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 41 insertions(+)
 create mode 100644 src/db/rest/login/api_login.sql

(limited to 'src/db/rest/login/api_login.sql')

diff --git a/src/db/rest/login/api_login.sql b/src/db/rest/login/api_login.sql
new file mode 100644
index 0000000..0cf0535
--- /dev/null
+++ b/src/db/rest/login/api_login.sql
@@ -0,0 +1,41 @@
+CREATE FUNCTION api.login(
+	username TEXT,
+	password TEXT
+)
+RETURNS sys.JWT
+LANGUAGE plpgsql VOLATILE
+AS $BODY$
+DECLARE
+	_role NAME;
+	_user_id INTEGER;
+	_token sys.JWT;
+BEGIN
+	SELECT role INTO _role
+		FROM admin.user u
+		WHERE u.username = login.username
+		AND u.password = login.password;
+
+	IF _role IS NULL THEN
+		PERFORM _api.raise(
+			_msg => 'api_invalid_login'
+		);
+		RETURN NULL;
+	END IF;
+
+	SELECT id INTO _user_id
+		FROM admin.user u
+		WHERE u.username = login.username;
+
+	_token = _api.sign_jwt(
+		_role,
+		_user_id
+	);
+
+	RETURN _token;
+END
+$BODY$;
+
+GRANT EXECUTE ON FUNCTION api.login(TEXT, TEXT)
+	TO rest_anon, rest_user;
+GRANT SELECT ON TABLE admin.user
+	TO rest_anon, rest_user;
-- 
cgit v1.2.3-freya

