I have a PhoneGap app with a Rails backend. I\'m trying to figure out what the best way is to authenticate a user from the mobile app using json.
I am using devise c
You should override devise's sessions and registrations controller. I'll only show you how to override the sessions controller:
First, go to your User model and add the Token Authenticatable module. Something like this:
devise :token_authenticatable
before_save :ensure_authentication_token
Then edit your devise.rb file to configure that module:
# You can skip storage for :http_auth and :token_auth by adding those symbols to the array below.
config.skip_session_storage = [:token_auth]
# Defines name of the authentication token params key
config.token_authentication_key = :auth_token
Now edit your routes and point to your new controllers:
devise_for :users, :controllers => { :registrations => 'registrations', :sessions => 'sessions' }
And then create your controller like this:
class SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html {
super
}
format.json {
build_resource
user = User.find_for_database_authentication(:email => params[:user][:email])
return invalid_login_attempt unless resource
if user.valid_password?(params[:user][:password])
render :json => { :auth_token => user.authentication_token }, success: true, status: :created
else
invalid_login_attempt
end
}
end
end
def destroy
respond_to do |format|
format.html {
super
}
format.json {
user = User.find_by_authentication_token(params[:auth_token])
if user
user.reset_authentication_token!
render :json => { :message => 'Session deleted.' }, :success => true, :status => 204
else
render :json => { :message => 'Invalid token.' }, :status => 404
end
}
end
end
protected
def invalid_login_attempt
warden.custom_failure!
render json: { success: false, message: 'Error with your login or password' }, status: 401
end
end
Devise has a page about this, but it only points to some already outdated guides. But maybe it will help you.