我需要从 django 和我的自定义应用程序访问相同的 BD。
我喜欢在 postgress 9 上实现与 django 相同的功能。
这是我的尝试:
CREATE EXTENSION pgcrypto
SCHEMA public;
-- Genera una cadena aleatoria del tamaño especificado
CREATE OR REPLACE FUNCTION random_string(length integer)
RETURNS TEXT
AS $$
DECLARE
chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
result text := '';
i integer := 0;
BEGIN
IF length < 0 THEN
raise exception 'Given length cannot be less than 0';
END IF;
FOR i IN 1..length LOOP
result := result || chars[1+random()*(array_length(chars, 1)-1)];
END LOOP;
RETURN result;
END;
$$
LANGUAGE plpgsql;
-- Encripta con SHA1 una cadena y retorna el tipo de algoritmo + salt + hash
CREATE OR REPLACE FUNCTION encryp_text(_text text)
RETURNS TEXT
AS $$
DECLARE
hash text := '';
salt text := '';
BEGIN
salt := random_string(12);
hash := encode( digest(random_string(12) || _text, 'SHA1'), 'hex');
RETURN 'sha1$' || salt || '$' || hash;
END;
$$
LANGUAGE 'plpgsql';
-- Resetea el pwd del usuario
CREATE OR REPLACE FUNCTION create_user (_username text, _password text, name text, lastname text, email text, isadmin bool, isstaff bool)
RETURNS BOOLEAN
AS $$
BEGIN
IF isadmin THEN
isstaff := isadmin;
END IF;
INSERT INTO auth_user(
username,
first_name,
last_name,
email,
password,
is_staff,
is_active,
is_superuser)
VALUES (_username,
name,
lastname,
email,
encryp_text(_password),
isstaff,
true,
isadmin);
END;
$$
LANGUAGE 'plpgsql';
SELECT create_user('sample','123','sample','user','s@s.com',true,true)
但是,在 django 中,当尝试进行身份验证时:
from django.contrib.auth import authenticate
authenticate(username='sample', password='123')
它失败。我需要做什么?
更新:
相同的密码:
Django:sha1$46uim9Staj7A$d472909885d27a21bc6e489641e27cc6e4ed25b6 后退:sha1$CP5CDALuPntn$d85f6aec18ae781c02cddbaa53e7c92e1b2c7ab1
更新:我忘记了这个问题。已解决,如如何使用 postgres 9.1 重新实现 django 的 BCryptPasswordHasher并升级到新的 bcrypt 方法。