Module: Persephone

Defined in:
lib/persephone.rb,
lib/persephone/engine.rb,
lib/persephone/version.rb,
app/models/persephone/app.rb,
app/models/persephone/auth.rb,
lib/persephone/unauthorized_error.rb,
app/controllers/persephone/tokens_controller.rb

Defined Under Namespace

Classes: App, Auth, Engine, TokensController, UnauthorizedError

Constant Summary collapse

DEFAULT_SCOPE =
'public'.freeze
VERSION =
'2.0.0'

Class Method Summary collapse

Class Method Details

.auth_token(headers) ⇒ Object



63
64
65
66
# File 'lib/persephone.rb', line 63

def self.auth_token(headers)
  return headers['Authorization'].split[1] unless headers.nil? || headers['Authorization'].nil?
  return false
end

.authenticate(client_id, client_secret) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/persephone.rb', line 45

def self.authenticate(client_id, client_secret)
  app = App.where(client_id: client_id, client_secret: client_secret).first
  if app
    app.auth&.destroy
    app.auth = Persephone::Auth.create(app: app)
    app.save
  end
  app
end

.authorization(headers) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/persephone.rb', line 17

def self.authorization(headers)
  token = auth_token(headers)
  if token
    app = App.where('auth.token' => token).first
    raise UnauthorizedError.new('token not found') if app.nil?
    app.auth
  else
    raise UnauthorizedError.new('invalid token')
  end
end

.authorized?(headers, scopes = [DEFAULT_SCOPE]) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
# File 'lib/persephone.rb', line 12

def self.authorized?(headers, scopes = [DEFAULT_SCOPE])
  auth = self.authorization(headers)
  auth && self.in_scope?(auth.app, scopes) && !self.expired?(auth)
end

.current_application(headers) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/persephone.rb', line 28

def self.current_application(headers)
  token = auth_token(headers)
  if token
    app = App.where('auth.token' => token).first
  else
    nil
  end
end

.expired?(auth) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
# File 'lib/persephone.rb', line 37

def self.expired?(auth)
  if auth.expires < Time.now.utc
    raise UnauthorizedError.new('token has expired; please get a new one')
  else
    false
  end
end

.in_scope?(app, scopes) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/persephone.rb', line 55

def self.in_scope?(app, scopes)
  if !(app.scopes & scopes).empty?
    true
  else
    raise UnauthorizedError.new('application does not have access (scope)')
  end
end