Created
July 31, 2014 14:34
-
-
Save joejwright/bc6f3b09f00d65f3b642 to your computer and use it in GitHub Desktop.
Devise Token Controller
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
class Api::V1::TokensController < ApplicationController | |
skip_before_filter :verify_authenticity_token | |
respond_to :json | |
def create | |
email = params[:email] | |
password = params[:password] | |
if request.format != :json | |
render :status=>406, :json=>{:message=>"The request must be json"} | |
return | |
end | |
if email.nil? or password.nil? | |
render :status=>400, | |
:json=>{:message=>"The request must contain the user email and password."} | |
return | |
end | |
@user=User.find_by_email(email.downcase) | |
if @user.nil? | |
logger.info("User #{email} failed signin, user cannot be found.") | |
render :status=>401, :json=>{:message=>"Invalid email or passoword."} | |
return | |
end | |
# http://rdoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable | |
@user.ensure_authentication_token | |
if not @user.valid_password?(password) | |
logger.info("User #{email} failed signin, password \"#{password}\" is invalid") | |
render :status=>401, :json=>{:message=>"Invalid email or password."} | |
else | |
render :status=>200, :json=>{:token=>@user.authentication_token} | |
end | |
end | |
def destroy | |
@user=User.find_by_authentication_token(params[:id]) | |
if @user.nil? | |
logger.info("Token not found.") | |
render :status=>404, :json=>{:message=>"Invalid token."} | |
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