Skip to content

Instantly share code, notes, and snippets.

@ouranos
Created May 25, 2015 09:10
Show Gist options
  • Save ouranos/cfa34b21607e7d84850e to your computer and use it in GitHub Desktop.
Save ouranos/cfa34b21607e7d84850e to your computer and use it in GitHub Desktop.
rails-api & Warden
# lib/strategies/authentication_token_strategy.rb
class AuthenticationTokenStrategy < ::Warden::Strategies::Base
def valid?
authentication_token
end
def authenticate!
user = User.find_by_authentication_token(authentication_token)
user.nil? ? fail!('strategies.authentication_token.failed') : success!(user)
end
private
def authentication_token
params['authentication_token']
end
end
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :authentication_token
t.string :password_digest
t.timestamps null: false
t.index :authentication_token, unique: true
end
end
end
# config/routes.rb
Rails.application.routes.draw do
get 'welcome/index'.
root 'welcome#index'
end
# app/controllers/unauthorized_controller.rb
class UnauthorizedController < ActionController::Metal
def self.call(env)
@respond ||= action(:respond)
@respond.call(env)
end
def respond
self.response_body = "Unauthorized Action"
self.status = :unauthorized
end
end
# app/models/user.rb
class User < ActiveRecord::Base
after_create :generate_authentication_token!
has_secure_password
private
# Generate a session token
def generate_authentication_token!
self.authentication_token = Digest::SHA1.hexdigest("#{Time.now}-#{self.id}-#{self.created_at}")
self.save
end
end
# app/controllers/concerns/warden_helper.rb
module WardenHelper
extend ActiveSupport::Concern
included do
helper_method :warden, :signed_in?, :current_user
prepend_before_filter :authenticate!
end
def signed_in?
!current_user.nil?
end
def current_user
warden.user
end
def warden
request.env['warden']
end
def authenticate!
warden.authenticate!
end
end
# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
render text: "Welcome guest, it's #{Time.now}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment