Class: Oauth2Token

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Timestamps
Defined in:
app/models/oauth2_token.rb

Constant Summary collapse

CODE_EXPIRY =

Lifetime of token authorization code in seconds.

60
TOKEN_EXPIRY =

Lifetime of token in seconds. 0 will never expire token.

0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.find!(args = {}) ⇒ Object

Returns a token by given parameters. If token is given a valid Oauth2Token will be returned. If client_id and redirect_url is given the code provided will be exchanged for a token.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/models/oauth2_token.rb', line 30

def self.find!(args = {})
  if tok = args[:token]
    token = Oauth2Token.where(:token => tok).first
    raise Vidibus::Oauth2Server::InvalidTokenError unless token
    raise Vidibus::Oauth2Server::ExpiredTokenError if token.token_expires_at and token.token_expires_at < Time.now
  else
    client_id = args[:client_id]
    redirect_url = args[:redirect_url]
    code = args[:code]

    raise Vidibus::Oauth2Server::MissingClientIdError if client_id.blank?
    raise Vidibus::Oauth2Server::MissingRedirectUrlError if redirect_url.blank?
    raise Vidibus::Oauth2Server::MissingCodeError if code.blank?

    token = Oauth2Token.where(:client_id => client_id).and(:code => code).first
    raise Vidibus::Oauth2Server::InvalidCodeError unless token
    raise Vidibus::Oauth2Server::InvalidRedirectUrlError unless redirect_url == token.redirect_url

    token.exchange!
  end
  token
end

Instance Method Details

#exchange!Object

Exchanges the code for a token if given code is valid and has not expired yet.



54
55
56
57
58
59
60
61
62
63
# File 'app/models/oauth2_token.rb', line 54

def exchange!
  raise Vidibus::Oauth2Server::InvalidCodeError unless code
  raise Vidibus::Oauth2Server::ExpiredCodeError unless code_expires_at >= Time.now
  self.code = nil
  self.code_expires_at = nil
  self.token = SecureRandom.hex(60)
  self.token_expires_at = Time.now + TOKEN_EXPIRY if TOKEN_EXPIRY > 0
  save!
  return code
end