使用DatamApper和Sinatra的attr_encrypted



我对DatamApper和Sinatra,尤其是Attr_encrypted我很新。我想要的是存储密码加密,然后能够通过用户名和密码搜索用户。我阅读了attr_encrypted的文档,但我仍然不明白该怎么做:(

您可以使用这两种技术给我一些项目的示例,或者告诉如何更改我的代码以工作:(

我的用户类:

  class User
    include DataMapper::Resource
    attr_encryptor :password, :key => 'secret key'
    property :id,       Serial
    property :encrypted_password, Text
  end

当我保存用户时,我这样做:

  username = params[:username]
  password = params[:password]
  user = User.new(:username => username, :encrypted_password => password)
  user.save

保存原始密码,而不是加密密码。

我不知道密码加密时如何搜索用户:(

现在是这样的:

  @user = User.all(:username => username, :password => password)

请原谅我的新手Quiestion,但我真的不太了解:(

非常感谢您!

您需要在之后添加attr_encryptor您已指定了数据映射属性。这可以防止DatamApper仅使用其自己的encrypted_password访问器替换:

class User
  include DataMapper::Resource
  property :id,       Serial
  property :encrypted_password, Text
  # this line moved down from above
  attr_encryptor :password, :key => 'secret key'
end

然后用:

创建用户
user = User.new(:username => username, :password => password)

您确定要根据加密密码搜索用户吗?通常,您会根据例如用户名,然后只检查密码匹配。

如果您想执行此操作,则必须在代码中重新创建加密密码并使用此搜索(您需要检查文档以查看如何进行加密):

User.all(:username => username, :encrypted_password => encrypt(password))

或者获取所有匹配用户并在您的代码中过滤它们:

User.all(:username => name).select {|u| u.password == password}

您的加密密码是:password,因此您必须执行

User.new(:username => username, :password => password)

要通过用户名和密码找到用户,您应该只做

User.first(:username => username, :password => password)

无论如何,您可以避免使用该宝石而代替bcrypt这样做这样的事情。

最新更新