Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 59 lines (47 sloc) 1.361 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 47 48 49 50 51 52 53 54 55 56 57 58
module Clearance
  module PasswordStrategies
    module BCryptMigrationFromSHA1
      class BCryptUser
        include Clearance::PasswordStrategies::BCrypt

        def initialize(user)
          @user = user
        end

        delegate :encrypted_password, :encrypted_password=, to: :@user
      end

      class SHA1User
        include Clearance::PasswordStrategies::SHA1

        def initialize(user)
          @user = user
        end

        delegate :salt, :salt=, :encrypted_password, :encrypted_password=, to: :@user
      end

      def authenticated?(password)
        authenticated_with_sha1?(password) || authenticated_with_bcrypt?(password)
      end

      def password=(new_password)
        @password = new_password
        BCryptUser.new(self).password = new_password
      end

      private

      def authenticated_with_bcrypt?(password)
        begin
          BCryptUser.new(self).authenticated? password
        rescue ::BCrypt::Errors::InvalidHash
          false
        end
      end

      def authenticated_with_sha1?(password)
        if sha1_password?
          if SHA1User.new(self).authenticated? password
            self.password = password
            self.save
            true
          end
        end
      end

      def sha1_password?
        self.encrypted_password =~ /^[a-f0-9]{40}$/
      end
    end
  end
end
Something went wrong with that request. Please try again.