Skip to content

Instantly share code, notes, and snippets.

@raecoo
Created August 27, 2012 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raecoo/3485301 to your computer and use it in GitHub Desktop.
Save raecoo/3485301 to your computer and use it in GitHub Desktop.
Simple Token Authentication for Devise
# before filter for api controller
def verify_authenticity_token
@current_user = User.find_by_authentication_token(params[:auth_token])
render status: 401, json: { message: '...' } and return unless @current_user
end
class Api::TokensController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json
def create
name = params[:name]
password = params[:password]
render status: 406, json: { message: "..."} and return if request.format != :json
render status: 400, json: { message: "..."} and return if name.nil? or password.nil?
@user = User.find_by_name(name.downcase)
render status: 401, json: { message: '...'} and return if @user.nil?
# http://rdoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable
@user.ensure_authentication_token!
if @user.valid_password?(password)
render status: 200, :json=>{ token: @user.authentication_token}
else
render status: 401, :json=>{ message: '...'}
end
end
def destroy
@user = User.find_by_authentication_token(params[:id])
if @user.nil?
render status: 404, json: { message: '...'}
else
@user.reset_authentication_token!
render status: 200, json: { :token=> params[:id] }
end
end
end
@raecoo
Copy link
Author

raecoo commented Aug 27, 2012

Don't forget to add the :token_authenticatable module for Devise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment