2011-11-09 34 views
1

我目前有一個需要遷移到rails的django系統。我正在使用Devise進行Rails授權。舊的Django系統有它自己的一組用戶,我需要遷移到rails。我關心的是用戶的密碼。它使用sha1算法進行加密。所以,我如何修改設計,使其與舊用戶的密碼兼容。將django用戶遷移到rails

回答

2

每個用戶都得到自己的隨機鹽,這樣如果密碼錶泄露,彩虹表不會幫助獲取實際的密碼。

結帳django/contrib/auth.models.pycheck_password(raw_password, enc_password)是你需要在你的Rails身份驗證系統實現的東西:

def get_hexdigest(algorithm, salt, raw_password): 
    """ 
    Returns a string of the hexdigest of the given plaintext password and salt 
    using the given algorithm ('md5', 'sha1' or 'crypt'). 
    """ 
    raw_password, salt = smart_str(raw_password), smart_str(salt) 
    if algorithm == 'crypt': 
     try: 
      import crypt 
     except ImportError: 
      raise ValueError('"crypt" password algorithm not supported in this environment') 
     return crypt.crypt(raw_password, salt) 

    if algorithm == 'md5': 
     return md5_constructor(salt + raw_password).hexdigest() 
    elif algorithm == 'sha1': 
     return sha_constructor(salt + raw_password).hexdigest() 
    raise ValueError("Got unknown password algorithm type in password.") 

def check_password(raw_password, enc_password): 
    """ 
    Returns a boolean of whether the raw_password was correct. Handles 
    encryption formats behind the scenes. 
    """ 
    algo, salt, hsh = enc_password.split('$') 
    return constant_time_compare(hsh, get_hexdigest(algo, salt, raw_password)) 
1

我在我的用戶模型下面的方法:

def valid_password?(pwd) 
    begin 
     super(pwd) 
    rescue 
     my_pwds = self.encrypted_password.split '$' 
     Digest::SHA1.hexdigest(my_pwds[1] + pwd) == my_pwds[2] rescue false 
    end 
end 

這擴展了default_password?方法由Devise使用,以查看用戶是否提交了正確的密碼。首先使用正常的設計邏輯檢查用戶,如果不起作用,Django sha1邏輯運行。這樣設計密碼也是可以的,所以你在將來不會遇到兼容性問題。