Module: Touth::Authenticator

Defined in:
lib/touth/authenticator.rb

Class Method Summary collapse

Class Method Details

.current(resource_name) ⇒ Object



69
70
71
# File 'lib/touth/authenticator.rb', line 69

def current(resource_name)
  Store.currents[resource_name]
end

.get_resource(token) ⇒ Object



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
# File 'lib/touth/authenticator.rb', line 30

def get_resource(token)
  return unless token

  resource = Store.access_tokens[token]

  return resource if resource

  Store.access_tokens[token] = nil

  begin
    data = Base64.urlsafe_decode64(token)
    data_sign = data.slice! -32..-1

    if data_sign == Touth.digest(data)
      data = Marshal.load data

      resource = data[:class].find data[:id]

      if token_secret(resource) == data[:secret] && Time.now.to_i < data[:expires_at]
        Store.access_tokens[token] = resource
      end
    end
  rescue
    nil
  end
end

.issue_access_token(resource, lifetime = Touth.access_token_lifetime) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/touth/authenticator.rb', line 8

def issue_access_token(resource, lifetime = Touth.access_token_lifetime)
  expires_at = Time.now.to_i + lifetime

  data = Marshal.dump({
    class:      resource.class,
    id:         resource.id,
    secret:     token_secret(resource),
    expires_at: expires_at,
  })

  data_sign = Touth.digest data

  Base64.urlsafe_encode64 [
    data,
    data_sign,
  ].join
end

.set_current(resource) ⇒ Object



62
63
64
65
66
67
# File 'lib/touth/authenticator.rb', line 62

def set_current(resource)
  return unless resource

  resource_name = Touth.get_resource_name resource.class.name
  Store.currents[resource_name] = resource
end

.token_secret(resource) ⇒ Object



57
58
59
60
# File 'lib/touth/authenticator.rb', line 57

def token_secret(resource)
  password = resource.send Touth.password_field
  Touth.digest(password)[0..16]
end

.valid_access_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/touth/authenticator.rb', line 26

def valid_access_token?(token)
  !!get_resource(token)
end