-- Deploy numerus:encrypt_password to pg
-- requires: schema_auth
-- requires: user
-- requires: extension_pgcrypto

begin;

set search_path to auth, numerus, public;

create or replace function encrypt_password() returns trigger as
$$
begin
	if tg_op = 'INSERT' or new.password <> old.password then
		new.password = crypt(new.password, gen_salt('bf'));
	end if;
	return new;
end;
$$
language plpgsql;

comment on function encrypt_password() is
'Encrypts and salts the input password with the blowfish encryption algorithm';

revoke execute on function encrypt_password() from public;

create trigger encrypt_password
before insert or update
on "user"
for each row execute procedure encrypt_password();

commit;