Last active
December 17, 2015 09:39
-
-
Save tatat/5589143 to your computer and use it in GitHub Desktop.
どうでしょう(Rails4コントローラ用Concern)
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
module Authenticatable | |
extend ActiveSupport::Concern | |
included do | |
helper_method :current_user, :signed_in?, :me?, :own? | |
end | |
module Exceptions | |
class Exception < SecurityError; end # SecurityError でいいのか謎 | |
class SignInRequired < Exception; end | |
class SignInFailed < Exception; end | |
class AccessDenied < Exception; end | |
end | |
module ClassMethods | |
def require_sign_in (*args, &block) | |
before_action :sign_in_required!, *args, &block | |
end | |
end | |
def require_sign_in! | |
raise Exceptions::SignInRequired | |
end | |
def sign_in_required! | |
require_sign_in! unless signed_in? | |
end | |
def signed_in? | |
not current_user.nil? | |
end | |
def sign_in_force (user) | |
@current_user = nil | |
session[:user_id] = user.id | |
end | |
def sign_in (user, password) | |
if signed_in = !! (user && user.authenticate(password)) | |
sign_in_force user | |
end | |
signed_in | |
end | |
def sign_in! (user, password) | |
raise Exceptions::SignInFailed unless sign_in(user, password) | |
end | |
def sign_out! | |
@current_user = nil | |
session[:user_id] = nil | |
reset_session | |
end | |
def current_user | |
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id] | |
end | |
def me? (user) | |
signed_in? and current_user.id == user.id | |
end | |
def own? (record, association_key = :user_id) | |
signed_in? and current_user.id == record.send(association_key) | |
end | |
def forbid_unless_me! (user) | |
forbidden! unless me? user | |
end | |
def forbid_unless_own! (record, association_key = :user_id) | |
forbidden! unless own? record, association_key | |
end | |
def forbidden! (message = nil) | |
raise Exceptions::AccessDenied.new(message) | |
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 ExamplesController < ApplicationController | |
include Authenticatable | |
require_sign_in except: [:action_sign_in_not_required] | |
rescue_from Authenticatable::Exceptions::Exception do |exception| | |
render status: 403, text: exception.message | |
end | |
def action_sign_in_not_required | |
end | |
def index | |
@nyans = Nyan.where(user_id: current_user.id) | |
end | |
def edit | |
@nyan = Nyan.find(params[:id]) | |
forbid_unless_own! @nyan | |
end | |
def require_sign_in! | |
redirect_to signin_url | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment