Class: RubyAuthMetamask::UsersController

Inherits:
ApplicationController show all
Defined in:
app/controllers/ruby_auth_metamask/users_controller.rb

Instance Method Summary collapse

Instance Method Details

#signinObject



16
17
18
19
20
21
22
23
# File 'app/controllers/ruby_auth_metamask/users_controller.rb', line 16

def 
  if session[:user_id].nil?
    @message = "ruby_auth_metamask:#{SecureRandom.hex}"
    session[:message] = @message
  else
    redirect_to main_app.root_path
  end
end

#verifyObject



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
# File 'app/controllers/ruby_auth_metamask/users_controller.rb', line 25

def verify
  address = sanitize_and_return_address
  my_signature = sanitize_and_return_my_signature
  if address.nil? || my_signature.nil?
    redirect_to main_app.root_path, notice: 'Address or signature is invalid'
    return
  end

  hash = metamask_digest(session[:message])
  if hash.nil?
    redirect_to main_app.root_path, notice: 'User authentication failed'
    return
  end

  public_key = recover_public_key(hash, my_signature)
  if public_key.nil?
    redirect_to main_app.root_path, notice: 'User authentication failed'
    return
  end

  unless verify_public_key_and_address(public_key, address)
    redirect_to main_app.root_path, notice: 'User address does not match public key'
    return
  end

  valid = ECDSA.valid_signature?(public_key, hash, my_signature.sig_obj) rescue false
  redirect_to main_app.root_path, notice: 'User authentication failed' unless valid

  user = User.find_by_address(address) || User.create(address: address)
  session[:user_id] = user.id
  redirect_to main_app.root_path, notice: 'User authentication succeeded'
end