加密密码触发器

时间:2016-08-15 15:57:05

标签: sql postgresql encryption triggers plpgsql

我尝试使用触发器加密PostgreSQL数据库中的密码,但我无法让它工作,我也不知道我的错误在哪里。 这是代码:

CREATE TABLE mms_user ( 
uid serial,
mail text NOT NULL,
passwd text NOT NULL,
usertype integer NOT NULL,
PRIMARY KEY (uid)
);

CREATE FUNCTION encrypt_password() RETURNS TRIGGER AS $$
BEGIN
 NEW.passwd = digest(NEW.passwd, 'sha1');
 RETURN NEW; END; $$LANGUAGE 'plpgsql';

 CREATE TRIGGER encrypt_userdata AFTER INSERT ON mms_user EXECUTE PROCEDURE encrypt_password();

 INSERT INTO mms_user values (default, 'who', 'me', 1);

执行时说明了这一点:

ERROR:  record "new" is not assigned yet
DETAIL:  The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT:  PL/pgSQL function encrypt_password() line 3 at assignment

如果不是NEW,我如何访问我插入的记录?

1 个答案:

答案 0 :(得分:0)

除了安全性和加密注意事项(请参阅注释),以解决您的实际PL / pgSQL问题:

触发功能基本上没问题。一些清理:

CREATE FUNCTION encrypt_password()
  RETURNS TRIGGER AS
$func$
BEGIN
 NEW.passwd := digest(NEW.passwd, 'sha1');  -- or some other function?
 RETURN NEW;
END
$func$ LANGUAGE plpgsql;  -- don't quote the language name

但要使其有效,您必须触发 BEFORE INSERT

CREATE TRIGGER encrypt_userdata
BEFORE INSERT ON mms_user
EXECUTE PROCEDURE encrypt_password();

我建议使用手册herehere