-- Deploy numerus:login to pg
-- requires: roles
-- requires: schema_numerus
-- requires: schema_auth
-- requires: email
-- requires: user

begin;

set search_path to numerus, auth;

create or replace function login(email email, password text) returns name as
$$
declare
	user_role name;
begin
	select role
	into user_role
	from "user"
	where "user".email = login.email
	and "user".password = crypt(login.password, "user".password);

	if user_role is null then
		raise invalid_password using message = 'invalid user or password';
	end if;

	return user_role;
end;
$$
language plpgsql
stable
security definer
set search_path = auth, numerus, pg_temp;

comment on function login(email, text) is
'Checks that the email and password pair is valid and returns the user’s databasse role.';

revoke execute on function login(email, text) from public;
grant execute on function login(email, text) to guest;

commit;
