summaryrefslogtreecommitdiff
path: root/lib/warden/strategies/secure_remote_password.rb
blob: 2c334c610e6394995f092fb6e82f7999b721a2c6 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module Warden
  module Strategies
    class SecureRemotePassword < Warden::Strategies::Base

      def valid?
        handshake? || authentication?
      end

      def authenticate!
        if authentication?
          validate!
        else  # handshake
          initialize!
        end
      end

      protected

      def handshake?
        params['A'] && params['login']
      end

      def authentication?
        params['client_auth'] && session[:handshake]
      end

      def validate!
        if client = validate
          success!(User.find_by_login(client.username))
        else
          Rails.logger.warn "Login attempt failed."
          Rails.logger.debug debug_info
          Rails.logger.debug "Received: #{params['client_auth']}"
          session.delete(:handshake)
          fail!(:base => "invalid_user_pass")
        end
      end

      def validate
        session[:handshake].authenticate(params['client_auth'])
      end

      def initialize!
        if user = User.find_by_login(id)
          client = SRP::Client.new user.username,
            :verifier => user.verifier,
            :salt => user.salt
          session[:handshake] = SRP::Session.new(client, params['A'])
          custom! json_response(session[:handshake])
        else
          fail! :base => 'invalid_user_pass'
        end
      rescue SRP::InvalidEphemeral
        fail!(:base => "invalid_ephemeral")
      end

      def json_response(object)
        [ 200,
          {"Content-Type" => "application/json; charset=utf-8"},
          [object.to_json]
        ]
      end

      def id
        params["id"] || params["login"]
      end

      protected

      def debug_info
        JSON.pretty_generate(session[:handshake].internal_state)
      end

    end
  end
  Warden::Strategies.add :secure_remote_password,
    Warden::Strategies::SecureRemotePassword

end