class OauthToken
  include MongoMapper::Document

  key :token, String, :unique => true, :required => true
  key :secret, String
  key :callback_url, String
  key :verifier, String
  key :scope, String
  key :authorized_at, Time
  key :invalidated_at, Time
  key :expires_at, Time
  timestamps!

  #index :token, :unique => true
  ensure_index :token, :unique => true

  belongs_to :user
  belongs_to :client_application, :required => true

  before_validation do
    generate_keys if new_record?
  end

  def invalidated?
    !invalidated_at.nil?
  end

  def invalidate!
    update_attribute(:invalidated_at, Time.now)
  end

  def authorized?
    !authorized_at.nil? && !invalidated?
  end

  def to_query
    "oauth_token=#{token}&oauth_token_secret=#{secret}"
  end

  protected
  def generate_keys
    self.token = OAuth::Helper.generate_key(40)[0,40]
    self.secret = OAuth::Helper.generate_key(40)[0,40]
  end
end
