<NME> access_token.rb
<BEF> module Rack
  module OAuth2
    class Server

      # Access token. This is what clients use to access resources.
      #
      # An access token is a unique code, associated with a client, an identity
      # and scope. It may be revoked, or expire after a certain period.
      class AccessToken
        class << self

          # Find AccessToken from token. Does not return revoked tokens.
          def from_token(token)
            Server.new_instance self, collection.find_one({ :_id=>token, :revoked=>nil })
          end

          # Get an access token (create new one if necessary).
          #
          # You can set optional expiration in seconds. If zero or nil, token
          # never expires.
          def get_token_for(identity, client, scope, expires = nil)
            raise ArgumentError, "Identity must be String or Integer" unless String === identity || Integer === identity
            scope = Utils.normalize_scope(scope) & client.scope # Only allowed scope

            token = collection.find_one({
              :$or=>[{:expires_at=>nil}, {:expires_at=>{:$gt=>Time.now.to_i}}],
              :identity=>identity, :scope=>scope,
              :client_id=>client.id, :revoked=>nil})

            unless token
              return create_token_for(client, scope, identity, expires)
            end
            Server.new_instance self, token
          end

          # Creates a new AccessToken for the given client and scope.
          def create_token_for(client, scope, identity = nil, expires = nil)
            expires_at = Time.now.to_i + expires if expires && expires != 0
            token = { :_id=>Server.secure_random, :scope=>scope,
                      :client_id=>client.id, :created_at=>Time.now.to_i,
                      :expires_at=>expires_at, :revoked=>nil }
            token[:identity] = identity if identity
            collection.insert token
            Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })
            Server.new_instance self, token
          end

          # Find all AccessTokens for an identity.
          def from_identity(identity)
            collection.find({ :identity=>identity }).map { |fields| Server.new_instance self, fields }
          end

          # Returns all access tokens for a given client, Use limit and offset
          # to return a subset of tokens, sorted by creation date.
          def for_client(client_id, offset = 0, limit = 100)
            client_id = BSON::ObjectId(client_id.to_s)
            collection.find({ :client_id=>client_id }, { :sort=>[[:created_at, Mongo::ASCENDING]], :skip=>offset, :limit=>limit }).
              map { |token| Server.new_instance self, token }
          end

          # Returns count of access tokens.
          #
          # @param [Hash] filter Count only a subset of access tokens
          # @option filter [Integer] days Only count that many days (since now)
          # @option filter [Boolean] revoked Only count revoked (true) or non-revoked (false) tokens; count all tokens if nil
          # @option filter [String, ObjectId] client_id Only tokens grant to this client
          def count(filter = {})
            select = {}
            if filter[:days]
              now = Time.now.to_i
              range = { :$gt=>now - filter[:days] * 86400, :$lte=>now }
              select[ filter[:revoked] ? :revoked : :created_at ] = range
            elsif filter.has_key?(:revoked)
              select[:revoked] = filter[:revoked] ? { :$ne=>nil } : { :$eq=>nil }
            end
            select[:client_id] = BSON::ObjectId(filter[:client_id].to_s) if filter[:client_id]
            collection.find(select).count
          end

          def historical(filter = {})
            days = filter[:days] || 60
            select = { :$gt=> { :created_at=>Time.now - 86400 * days } }
            select = {}
            if filter[:client_id]
              select[:client_id] = BSON::ObjectId(filter[:client_id].to_s)
            end
            raw = Server::AccessToken.collection.group("function (token) { return { ts: Math.floor(token.created_at / 86400) } }",
              select, { :granted=>0 }, "function (token, state) { state.granted++ }")
            raw.sort { |a, b| a["ts"] - b["ts"] }
          end

          def collection
            prefix = Server.options[:collection_prefix]
            Server.database["#{prefix}.access_tokens"]
          end
        end

        # Access token. As unique as they come.
        attr_reader :_id
        alias :token :_id
        # The identity we authorized access to.
        attr_reader :identity
        # Client that was granted this access token.
        attr_reader :client_id
        # The scope granted to this token.
        attr_reader :scope
        # When token was granted.
        attr_reader :created_at
        # When token expires for good.
        attr_reader :expires_at
        # Timestamp if revoked.
        attr_accessor :revoked
        # Timestamp of last access using this token, rounded up to hour.
        attr_accessor :last_access
        # Timestamp of previous access using this token, rounded up to hour.
        attr_accessor :prev_access

        # Updates the last access timestamp.
        def access!
          today = (Time.now.to_i / 3600) * 3600
          if last_access.nil? || last_access < today
            AccessToken.collection.update({ :_id=>token }, { :$set=>{ :last_access=>today, :prev_access=>last_access } })
            self.last_access = today
          end
        end

        # Revokes this access token.
        def revoke!
          self.revoked = Time.now.to_i
          AccessToken.collection.update({ :_id=>token }, { :$set=>{ :revoked=>revoked } })
          Client.collection.update({ :_id=>client_id }, { :$inc=>{ :tokens_revoked=>1 } })
        end

        Server.create_indexes do
          # Used to revoke all pending access grants when revoking client.
          collection.create_index [[:client_id, Mongo::ASCENDING]]
          # Used to get/revoke access tokens for an identity, also to find and
          # return existing access token.
          collection.create_index [[:identity, Mongo::ASCENDING]]
        end
      end

    end
  end
end

<MSG> allow token use in MongoDB cappedCollections

<DFF> @@ -38,7 +38,9 @@ module Rack
             expires_at = Time.now.to_i + expires if expires && expires != 0
             token = { :_id=>Server.secure_random, :scope=>scope,
                       :client_id=>client.id, :created_at=>Time.now.to_i,
-                      :expires_at=>expires_at, :revoked=>nil }
+                      :expires_at=>expires_at, :revoked=>nil,
+                      :last_access=>Time.now.to_i, :prev_access=>Time.now.to_i }
+
             token[:identity] = identity if identity
             collection.insert token
             Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })

{'commit': 'diff --git a/lib/rack/oauth2/models/access_token.rb b/lib/rack/oauth2/models/access_token.rb\nindex 441a95d..afb3c04 100644\n--- a/lib/rack/oauth2/models/access_token.rb\n+++ b/lib/rack/oauth2/models/access_token.rb\n@@ -38,7 +38,9 @@ module Rack\n             expires_at = Time.now.to_i + expires if expires && expires != 0\n             token = { :_id=>Server.secure_random, :scope=>scope,\n                       :client_id=>client.id, :created_at=>Time.now.to_i,\n-                      :expires_at=>expires_at, :revoked=>nil }\n+                      :expires_at=>expires_at, :revoked=>nil,\n+                      :last_access=>Time.now.to_i, :prev_access=>Time.now.to_i }\n+\n             token[:identity] = identity if identity\n             collection.insert token\n             Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })\n', 'commit_subject': 'allow token use in MongoDB cappedCollections', 'repo_name': 'assaf/rack-oauth2-server', 'committer': {'name': 'cstuss', 'email': '680aab7a65ff01bdc4f3dc139f22fc3a910cb10b@aexp.com', 'time_sec': '1373385096', 'tz_offset': '-240', 'date': {'seconds': '1373385096'}}, 'commit_tree': '27aebf458cc693cc45d6fe62702efdbe9acd4f83', 'commit_message': 'allow token use in MongoDB cappedCollections\n', 'language_name': 'Ruby', 'license': 'mit', 'hunks': '@@ -38,7 +38,9 @@ module Rack\n             expires_at = Time.now.to_i + expires if expires && expires != 0\n             token = { :_id=>Server.secure_random, :scope=>scope,\n                       :client_id=>client.id, :created_at=>Time.now.to_i,\n-                      :expires_at=>expires_at, :revoked=>nil }\n+                      :expires_at=>expires_at, :revoked=>nil,\n+                      :last_access=>Time.now.to_i, :prev_access=>Time.now.to_i }\n+\n             token[:identity] = identity if identity\n             collection.insert token\n             Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })\n', 'addition_count': 3, 'deletion_count': 1, 'src_file': 'a/lib/rack/oauth2/models/access_token.rb', 'tgt_file': 'b/lib/rack/oauth2/models/access_token.rb', 'file_extension': '.rb', 'before_file': 'module Rack\n  module OAuth2\n    class Server\n\n      # Access token. This is what clients use to access resources.\n      #\n      # An access token is a unique code, associated with a client, an identity\n      # and scope. It may be revoked, or expire after a certain period.\n      class AccessToken\n        class << self\n\n          # Find AccessToken from token. Does not return revoked tokens.\n          def from_token(token)\n            Server.new_instance self, collection.find_one({ :_id=>token, :revoked=>nil })\n          end\n\n          # Get an access token (create new one if necessary).\n          #\n          # You can set optional expiration in seconds. If zero or nil, token\n          # never expires.\n          def get_token_for(identity, client, scope, expires = nil)\n            raise ArgumentError, "Identity must be String or Integer" unless String === identity || Integer === identity\n            scope = Utils.normalize_scope(scope) & client.scope # Only allowed scope\n\n            token = collection.find_one({\n              :$or=>[{:expires_at=>nil}, {:expires_at=>{:$gt=>Time.now.to_i}}],\n              :identity=>identity, :scope=>scope,\n              :client_id=>client.id, :revoked=>nil})\n\n            unless token\n              return create_token_for(client, scope, identity, expires)\n            end\n            Server.new_instance self, token\n          end\n\n          # Creates a new AccessToken for the given client and scope.\n          def create_token_for(client, scope, identity = nil, expires = nil)\n            expires_at = Time.now.to_i + expires if expires && expires != 0\n            token = { :_id=>Server.secure_random, :scope=>scope,\n                      :client_id=>client.id, :created_at=>Time.now.to_i,\n                      :expires_at=>expires_at, :revoked=>nil }\n            token[:identity] = identity if identity\n            collection.insert token\n            Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })\n            Server.new_instance self, token\n          end\n\n          # Find all AccessTokens for an identity.\n          def from_identity(identity)\n            collection.find({ :identity=>identity }).map { |fields| Server.new_instance self, fields }\n          end\n\n          # Returns all access tokens for a given client, Use limit and offset\n          # to return a subset of tokens, sorted by creation date.\n          def for_client(client_id, offset = 0, limit = 100)\n            client_id = BSON::ObjectId(client_id.to_s)\n            collection.find({ :client_id=>client_id }, { :sort=>[[:created_at, Mongo::ASCENDING]], :skip=>offset, :limit=>limit }).\n              map { |token| Server.new_instance self, token }\n          end\n\n          # Returns count of access tokens.\n          #\n          # @param [Hash] filter Count only a subset of access tokens\n          # @option filter [Integer] days Only count that many days (since now)\n          # @option filter [Boolean] revoked Only count revoked (true) or non-revoked (false) tokens; count all tokens if nil\n          # @option filter [String, ObjectId] client_id Only tokens grant to this client\n          def count(filter = {})\n            select = {}\n            if filter[:days]\n              now = Time.now.to_i\n              range = { :$gt=>now - filter[:days] * 86400, :$lte=>now }\n              select[ filter[:revoked] ? :revoked : :created_at ] = range\n            elsif filter.has_key?(:revoked)\n              select[:revoked] = filter[:revoked] ? { :$ne=>nil } : { :$eq=>nil }\n            end\n            select[:client_id] = BSON::ObjectId(filter[:client_id].to_s) if filter[:client_id]\n            collection.find(select).count\n          end\n\n          def historical(filter = {})\n            days = filter[:days] || 60\n            select = { :$gt=> { :created_at=>Time.now - 86400 * days } }\n            select = {}\n            if filter[:client_id]\n              select[:client_id] = BSON::ObjectId(filter[:client_id].to_s)\n            end\n            raw = Server::AccessToken.collection.group("function (token) { return { ts: Math.floor(token.created_at / 86400) } }",\n              select, { :granted=>0 }, "function (token, state) { state.granted++ }")\n            raw.sort { |a, b| a["ts"] - b["ts"] }\n          end\n\n          def collection\n            prefix = Server.options[:collection_prefix]\n            Server.database["#{prefix}.access_tokens"]\n          end\n        end\n\n        # Access token. As unique as they come.\n        attr_reader :_id\n        alias :token :_id\n        # The identity we authorized access to.\n        attr_reader :identity\n        # Client that was granted this access token.\n        attr_reader :client_id\n        # The scope granted to this token.\n        attr_reader :scope\n        # When token was granted.\n        attr_reader :created_at\n        # When token expires for good.\n        attr_reader :expires_at\n        # Timestamp if revoked.\n        attr_accessor :revoked\n        # Timestamp of last access using this token, rounded up to hour.\n        attr_accessor :last_access\n        # Timestamp of previous access using this token, rounded up to hour.\n        attr_accessor :prev_access\n\n        # Updates the last access timestamp.\n        def access!\n          today = (Time.now.to_i / 3600) * 3600\n          if last_access.nil? || last_access < today\n            AccessToken.collection.update({ :_id=>token }, { :$set=>{ :last_access=>today, :prev_access=>last_access } })\n            self.last_access = today\n          end\n        end\n\n        # Revokes this access token.\n        def revoke!\n          self.revoked = Time.now.to_i\n          AccessToken.collection.update({ :_id=>token }, { :$set=>{ :revoked=>revoked } })\n          Client.collection.update({ :_id=>client_id }, { :$inc=>{ :tokens_revoked=>1 } })\n        end\n\n        Server.create_indexes do\n          # Used to revoke all pending access grants when revoking client.\n          collection.create_index [[:client_id, Mongo::ASCENDING]]\n          # Used to get/revoke access tokens for an identity, also to find and\n          # return existing access token.\n          collection.create_index [[:identity, Mongo::ASCENDING]]\n        end\n      end\n\n    end\n  end\nend\n', 'message': 'allow token use in MongoDB cappedCollections\n', 'author_name': 'cstuss', 'lang': 'rb'}