Class: Lanes::API::AuthenticationProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/lanes/access/authentication_provider.rb,
lib/lanes/api/null_authentication_provider.rb

Constant Summary collapse

USER =
DummyUser.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request) ⇒ AuthenticationProvider

Returns a new instance of AuthenticationProvider.



7
8
9
# File 'lib/lanes/access/authentication_provider.rb', line 7

def initialize(request)
    @request=request
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



5
6
7
# File 'lib/lanes/access/authentication_provider.rb', line 5

def request
  @request
end

Instance Method Details

#allowed_access_to?(klass) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lanes/access/authentication_provider.rb', line 35

def allowed_access_to?(klass)
    return false if current_user.nil?
    case request.request_method
    when 'GET'
        klass.can_read_attributes?(request.params,current_user)
    when 'POST','PATCH','PUT'
        klass.can_write_attributes?(request.params,current_user)
    when 'DELETE'
        klass.can_delete_attributes?(request.params,current_user)
    else
        false
    end
end

#current_userObject



11
12
13
14
15
16
17
18
19
# File 'lib/lanes/access/authentication_provider.rb', line 11

def current_user
    @current_user ||= (
        if Lanes.env.test? && request.env['HTTP_X_TESTING_USER'].present?
            Lanes::User.where(login: request.env['HTTP_X_TESTING_USER']).first
        else
            Lanes::User.where(id: request.session['user_id']).first
        end
    )
end

#error_messageObject



21
22
23
# File 'lib/lanes/access/authentication_provider.rb', line 21

def error_message
    current_user ? "User not found" : error_message_for_access
end

#error_message_for_accessObject



25
26
27
28
29
30
31
32
33
# File 'lib/lanes/access/authentication_provider.rb', line 25

def error_message_for_access
    return "Unable to " + case request.request_method
                          when 'GET' then "read"
                          when 'POST','PATCH','PUT' then "write"
                          when 'DELETE' then "delete"
                          else
                              "perform action"
                          end
end

#wrap_reply(model, req) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/lanes/access/authentication_provider.rb', line 50

def wrap_reply(model, req)
    if allowed_access_to?(model)
        ::Lanes::User.scoped_to(current_user) do | user |
            yield
        end
    else
        Lanes.logger.warn "Unauthorized access attempted to #{req}"
        req.halt( 401, Oj.dump({
          success:false, errors: {user: "Access Denied"}, message: "Access Denied"
        }))
    end
end