Skip to content

Instantly share code, notes, and snippets.

@dsaronin
Last active March 22, 2017 07:09
Show Gist options
  • Save dsaronin/8155622 to your computer and use it in GitHub Desktop.
Save dsaronin/8155622 to your computer and use it in GitHub Desktop.
token_authentication handling using milia & devise
## token_authentication
# at the head of of controllers which will need token authentication instead of password/session authentication:
skip_before_action :authenticate_tenant!
before_action :authenticate_by_token!
# then in application_controller.rb:
def authenticate_by_token!
if (user = User.find_user_by_token( params[:id] ) )
reset_session # purge any existing session
sign_in( :user, user ) # devise signs in user
set_current_tenant # must come IMMEDIATELY after devise sign_in
true # ok to continue filter chain
else # authorization rejected
logger.info( "SECURITY - access denied") # and another info you want to log
flash[:notice] = "sign-in required"
render( :nothing => true, :status => :forbidden)
nil # aborts further processing
end
end
# in models/user.rb
# returns nil if invalid authentication attempt; else returns an authorized user object
def self.find_user_by_token( token_key )
return nil if token_key.blank? # neither key present; invalid
# find by the key; nil if invalid
return User.where( :authentication_token => token_key ).first
end
# in db/migrate you'll need a migration to
add_column :users, :authentication_token, :string
# Somewhere within user.rb, you'll need as way to generate random but secure tokens and place them into user.authentication_token.
Commentary
You'll have to figure out what strategy you'll use:
- can all users sign in with a token?
- just some?
- or only for certain actions?
these issues are outside the scope of milia. My application only has the third case: I have certain "global" actions which permit access to specialized information for an organization. to accomplish that, I have a "global user" for an organization (tenant), and corresponding controller#actions only for that kind of access (such as, seeing all of the public events for the organization).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment