Best flexible rails password security implementation [closed]

最后都变了- 提交于 2019-12-04 08:45:55

we've been using devise security extension for a while now. It has a lot of interesting features (e.g. password history, password expiration...).

For password complexity we wanted something that was a bit more configurable (in your example: letting customer choose how many levels of comlexity they wanted).

So we rolled out our own solution based on a score: 3 out of 5 (in you example) means that we're testing each characterisitc and give one point if it's found. If the total score is equal or greater than required score, then the password is fine.

In terms of code, our validation looks like this:

validate :password_complexity

def password_complexity
 return if password.nil?

 if password.size < 8
   errors.add :password, "Must be at least 8 characters long."
   return
 end

 required_complexity = 3 # we're actually storing this in the configuration of each customer

 if !CheckPasswordComplexityService.new(password, required_complexity).valid?
   errors.add :password, "Your password does not match the security requirements."
 end
end

and the service that checks for the complexity looks like this:

class CheckPasswordComplexityService

  attr_reader :password, :required_complexity

  def initialize(password, required_complexity)
    @password = password
    @required_complexity = required_complexity
  end

  def valid?
    score = has_uppercase_letters? + has_digits? + has_extra_chars? + has_downcase_letters?

    score >= required_complexity
  end

  private

  def has_uppercase_letters?
    password.match(/[A-Z]/) ? 1 : 0
  end

  def has_digits?
    password.match(/\d/) ? 1 : 0
  end

  def has_extra_chars?
    password.match(/\W/) ? 1 : 0
  end

  def has_downcase_letters?
    password.match(/[a-z]{1}/) ? 1 : 0
  end
end

Then it becomes very easy to add some new characteristics you want to check.

CaptChrisD

I don't think a gem is the correct thing to use here. Just use a validation:

validate :secure_password

def secure_password
    return false if (password =~ /[a-z]/).blank? #lower letter test
    return false if (password =~ /[A-Z]/).blank? #upper letter test
    return false if (password =~ /[0-9]/).blank? #number test
    ...
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!