|
| 1 | +require 'doorkeeper/grape/authorization_decorator' |
| 2 | + |
| 3 | +module Helpers |
| 4 | + module AuthHelper |
| 5 | + extend ActiveSupport::Concern |
| 6 | + |
| 7 | + included do |
| 8 | + use Rack::OAuth2::Server::Resource::Bearer, 'OAuth2' do |request| |
| 9 | + # Yield access token to store it in the env |
| 10 | + request.access_token |
| 11 | + end |
| 12 | + |
| 13 | + helpers HelperMethods |
| 14 | + end |
| 15 | + |
| 16 | + module HelperMethods |
| 17 | + def current_user |
| 18 | + @current_user ||= find_current_user |
| 19 | + end |
| 20 | + |
| 21 | + def current_user! |
| 22 | + current_user.anonymous? ? unauthorized! : current_user |
| 23 | + end |
| 24 | + |
| 25 | + def find_access_token |
| 26 | + @access_token ||= Doorkeeper.authenticate(doorkeeper_request, Doorkeeper.configuration.access_token_methods) |
| 27 | + end |
| 28 | + |
| 29 | + def authenticate! |
| 30 | + unauthorized! unless current_user |
| 31 | + end |
| 32 | + |
| 33 | + def authorize!(action, subject) |
| 34 | + unless abilities.allowed?(current_user, action, subject) |
| 35 | + # TODO: Un-comment on May 12, date of OAuth Scope Enforcement rollout |
| 36 | + # forbidden! |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + def require_scope!(scopes) |
| 41 | + return unless find_access_token |
| 42 | + scopes = [scopes] unless scopes.kind_of? Array |
| 43 | + |
| 44 | + unless (find_access_token.scopes.to_a & scopes) == scopes |
| 45 | + forbidden! |
| 46 | + end |
| 47 | + end |
| 48 | + |
| 49 | + def can?(object, action, subject) |
| 50 | + abilities.allowed?(object, action, subject) |
| 51 | + end |
| 52 | + |
| 53 | + private |
| 54 | + |
| 55 | + def abilities |
| 56 | + @abilities ||= begin |
| 57 | + abilities = Six.new |
| 58 | + abilities << Abilities::Ability |
| 59 | + abilities |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + def find_current_user |
| 64 | + if find_access_token |
| 65 | + lookup_owner |
| 66 | + elsif warden_current_user |
| 67 | + warden_current_user |
| 68 | + else |
| 69 | + User.anonymous |
| 70 | + end |
| 71 | + end |
| 72 | + |
| 73 | + def lookup_owner |
| 74 | + if find_access_token.resource_owner_id.present? |
| 75 | + User.find_by_id(find_access_token.resource_owner_id) |
| 76 | + else |
| 77 | + find_access_token.application.owner |
| 78 | + end |
| 79 | + end |
| 80 | + |
| 81 | + def doorkeeper_request |
| 82 | + @doorkeeper_request ||= Doorkeeper::Grape::AuthorizationDecorator.new(request) |
| 83 | + end |
| 84 | + |
| 85 | + def warden |
| 86 | + @warden ||= env['warden'] |
| 87 | + end |
| 88 | + |
| 89 | + def warden_current_user |
| 90 | + warden ? warden.user : nil |
| 91 | + end |
| 92 | + end |
| 93 | + end |
| 94 | +end |
0 commit comments