summaryrefslogtreecommitdiff
path: root/users/config/initializers/warden.rb
blob: 98dd99cc857ce6a04d1a4e234485819d905ca95a (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
Rails.configuration.middleware.use RailsWarden::Manager do |config|
  config.default_strategies :secure_remote_password
  config.failure_app = SessionsController
  config.default_scope = :user
  config.scope_defaults :user, :action => :new
end

# Setup Session Serialization
class Warden::SessionSerializer
  def serialize(record)
    [record.class.name, record.id]
  end

  def deserialize(keys)
    klass, id = keys
    klass.find(id)
  end
end

Warden::Strategies.add(:secure_remote_password) do

  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!
    srp_session = session.delete(:handshake)
    user = srp_session.authenticate(params['client_auth'].hex)
    user.nil? ? fail!("Could not log in") : success!(user)
  end

  def initialize!
    user = User.find_by_param(id)
    session[:handshake] = user.initialize_auth(params['A'].hex)
    custom! json_response(session[:handshake])
  rescue RECORD_NOT_FOUND
    fail! "User not found!"
  end

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

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