Created
March 1, 2014 22:16
-
-
Save onyxrev/9298321 to your computer and use it in GitHub Desktop.
General hackery with API-based auth and 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
class ApplicationController < ActionController::Base | |
# ... | |
private | |
# from https://gist.github.com/josevalim/fb706b1e933ef01e4fb6 | |
def authenticate_user_from_token! | |
email = params[:email].presence | |
user = email && User.where(email: email).first | |
# Notice how we use Devise.secure_compare to compare the token | |
# in the database with the token given in the params, mitigating | |
# timing attacks. | |
if user && Devise.secure_compare(user.authentication_token, params[:user_token]) | |
sign_in user, store: false | |
end | |
end | |
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 CsrfController < ApplicationController | |
def show | |
return render :json => { | |
'csrfParam' => request_forgery_protection_token, | |
'csrfToken' => form_authenticity_token | |
} | |
end | |
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 SessionsController < Devise::SessionsController | |
def destroy | |
super | |
end | |
# here we have to send back fresh CSRF tokens because the session is changing. | |
# clients will have to update their token cache on their end from the params | |
# we send back. | |
# Inspired by http://blog.softr.li/post/43146401263/finally-correctly-dealing-with-rails-csrf-protection | |
def create | |
self.resource = warden.authenticate!(auth_options) | |
set_flash_message(:notice, :signed_in) if is_navigational_format? | |
sign_in(resource_name, resource) | |
return api_response(:success, :user_logged_in, { | |
:meta => { | |
'csrfParam' => request_forgery_protection_token, | |
'csrfToken' => form_authenticity_token | |
} | |
})) | |
end | |
protected | |
def after_sign_out_path_for(resource) | |
root_path(:signed_out => true) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment