Created
January 16, 2014 16:32
-
-
Save felippemr/8458092 to your computer and use it in GitHub Desktop.
Aqui estão alguns métodos e classes que eu uso na autenticação da api.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _provided_valid_password? | |
params[:user][:password] && UserAuthenticationService.authenticate_with_password!(@user, params[:user][:password]) | |
end | |
class ApiController < ApplicationController | |
before_filter :api_session_token_authenticate! | |
private | |
def signed_in? | |
!!current_api_session_token.user | |
end | |
def current_user | |
current_api_session_token.user | |
end | |
def api_session_token_authenticate! | |
return _not_authorized unless _authorization_header && current_api_session_token.valid? | |
end | |
def current_api_session_token | |
@current_api_session_token ||= ApiSessionToken.new(_authorization_header) | |
end | |
def _authorization_header | |
request.headers['HTTP_AUTHORIZATION'] | |
end | |
def _not_authorize message = "Not Authorized" | |
render json: {error: message}, status: 401 | |
end | |
end | |
class ApiSessionToken | |
extend ActiveModel::Naming | |
include ActiveModel::Serialization | |
TTL = 20.minutes | |
def self.store | |
@store ||= Hash.new | |
end | |
def initialize(existing_token=nil) | |
@token = existing_token | |
self.last_seen = Time.now unless expired? | |
end | |
def token | |
@token ||= MicroToken.generate 128 | |
end | |
def ttl | |
return TTL unless last_seen | |
elapsed = Time.now - last_seen | |
remaining = (TTL - elapsed).floor | |
remaining > 0 ? remaining : 0 | |
end | |
def last_seen | |
store[:last_seen_at] | |
end | |
def last_seen=(as_at) | |
store[:last_seen_at] = as_at | |
end | |
def user | |
return if expired? | |
store[:user] | |
end | |
def user=(user) | |
store[:user] = user | |
end | |
def expired? | |
ttl < 1 | |
end | |
def valid? | |
!expired? | |
end | |
private | |
def store | |
self.class.store[token] ||= {} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment