Created
August 27, 2012 03:35
-
-
Save raecoo/3485301 to your computer and use it in GitHub Desktop.
Simple Token Authentication for Devise
This file contains 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
# 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 |
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to add the :token_authenticatable module for Devise