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;
