Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 47 lines (39 sloc) 1.02 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
require 'digest/sha1'

module Clearance
  module PasswordStrategies
    module SHA1
      extend ActiveSupport::Concern

      # Am I authenticated with given password?
      #
      # @param [String] plain-text password
      # @return [true, false]
      # @example
      # user.authenticated?('password')
      def authenticated?(password)
        encrypted_password == encrypt(password)
      end

      protected

      def encrypt_password
        initialize_salt_if_necessary
        if password.present?
          self.encrypted_password = encrypt(password)
        end
      end

      def generate_hash(string)
        if RUBY_VERSION >= '1.9'
          Digest::SHA1.hexdigest(string).encode('UTF-8')
        else
          Digest::SHA1.hexdigest(string)
        end
      end

      def encrypt(string)
        generate_hash("--#{salt}--#{string}--")
      end

      def initialize_salt_if_necessary
        if salt.blank?
          self.salt = generate_random_code
        end
      end
    end
  end
end
Something went wrong with that request. Please try again.