简体   繁体   中英

Count api calls with token

Im trying to create an api that requires tokens for use. Each time a page is called i check if the token exist with this before_filter in the controller:

            def restrict_access_token
                authenticate_or_request_with_http_token do |token, options|
                    ApiKey.exists?(access_token: token)
                end
            end

When an apikey is found I want to increment a count column in the ApiKey table.

I was looking for a callback in the model that triggers when the apikey is found but that don't seems to work in this case.

Any ideas?

In your model, you need to override exists? method

def self.exists?(conditions = :none)
  if super
    ...{YOUR CALLBACK}...
  end
end

Update: I would prefer to customize your method like find_and_increment(...) . so in model:

def self.find_and_increment(conditions = :none)
  if object = where(conditions).first
    object.increment!(...)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM