Skip to content

Instantly share code, notes, and snippets.

@iheanyi
Created June 11, 2015 00:55
Show Gist options
  • Save iheanyi/af4ca803c486484b40f3 to your computer and use it in GitHub Desktop.
Save iheanyi/af4ca803c486484b40f3 to your computer and use it in GitHub Desktop.
HTTP Authorization/Authentication Validators
class ApplicationController < ActionController::Base
#include Clearance::Controller
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
before_filter :authenticate_user_from_token!
private
def authenticate_user_from_token!
authenticate_with_http_token do |token, options|
user_email = options[:user_email].presence
user = user_email && User.find_by_email(user_email)
if user && Devise.secure_compare(user.authentication_token, token)
sign_in user, store: false
end
end
end
def check_user_logged_in!
if !user_signed_in?
render json: {errors: "User not logged in."}, status: :forbidden
end
end
def check_ownership(model)
if model.user != current_user
render json: {errors: "#{model.class.name.demodulize} does not belong to user.", status: :unauthorized}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment