Module: ShopliftClient

Extended by:
ActiveSupport::Concern
Included in:
ApiController, AuthController, UserAuthenticatedController, UserAuthenticatedOrApiController
Defined in:
app/controllers/concerns/shoplift_client.rb

Instance Method Summary collapse

Instance Method Details

#authenticate_company!(soft = false) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'app/controllers/concerns/shoplift_client.rb', line 109

def authenticate_company!(soft = false)
  return true if authenticate_user

  @api_key = if params['key'].present?
               params['key'].match(/[0-9a-f]+/).to_s
             elsif request.headers['AUTHORIZATION'].present? && !request.headers['AUTHORIZATION'].include?('Basic')
               request.headers['AUTHORIZATION'].gsub(/^Bearer ?/, '')
             else
               Rails.configuration.settings['authlift_default_app_key']
             end

  if @api_key.blank?
    return false if soft
    fail ActionController::RoutingError, 'Authentication token missing'
  end

  response = srv.post 'auth/api_key',
                      body: {
                        api_key: api_key,
                        requested_action: "#{self.controller_name}##{self.action_name}"
                      }

  if response.blank?
    return false if soft
    fail ActionController::RoutingError, 'Request not authorized'
  end

  @authentication = JSON.parse response.body
  find_company_by_code authentication['company']
  true
end

#authenticate_userObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/controllers/concerns/shoplift_client.rb', line 74

def authenticate_user
  if session_cookie.present?
    @token = OAuth2::AccessToken.new client, session_cookie, scope: scope
    begin
      x = srv.get '/api/users/profile'
      @current_user = JSON.parse x.response.body
      user_scopes = JSON.parse @current_user['scopes']
      unless user_scopes.include? 'admin'
        (self.class.required_scopes || []).each do |required_scope|
          unless user_scopes.include? required_scope
            render(file: 'shopapp/403.html', status: 403, layout: false, locals: { missing_scope: required_scope })
            return false
          end
        end
      end
      find_company_by_code current_user['company']['code']
    rescue OAuth2::Error
      return false
    end
  else
    return false
  end
  true
end

#authenticate_user!Object



99
100
101
# File 'app/controllers/concerns/shoplift_client.rb', line 99

def authenticate_user!
  redirect_unauthorized unless authenticate_user
end

#authenticate_user_or_api!Object



103
104
105
106
107
# File 'app/controllers/concerns/shoplift_client.rb', line 103

def authenticate_user_or_api!
  unless authenticate_company!(true)
    redirect_unauthorized
  end
end

#clientObject



184
185
186
187
188
# File 'app/controllers/concerns/shoplift_client.rb', line 184

def client
  @oauth ||= OAuth2::Client.new Rails.configuration.settings['authlift_app_id'],
                                Rails.configuration.settings['authlift_app_secret'],
                                site: Rails.configuration.settings['authlift_url']
end

#current_companyObject



147
148
# File 'app/controllers/concerns/shoplift_client.rb', line 147

def current_company
end

#current_userObject



141
142
143
144
145
# File 'app/controllers/concerns/shoplift_client.rb', line 141

def current_user
  return @current_user if @current_user.present?

  @current_user
end

#find_company_by_code(code) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/controllers/concerns/shoplift_client.rb', line 58

def find_company_by_code(code)
  begin
    @current_company ||= Company.find_or_create_by! code: code
  rescue ActiveRecord::StatementInvalid
    if $!.cause.is_a? PG::UndefinedTable
      fail <<-ERROR.strip_heredoc
        You have not defined a company, and that is compulsory even if
        you are not planning to add any additional fields. You do not need to
        seed it, so following is enough forever:

            rails g model company code:string; rake db:migrate
      ERROR
    end
  end
end

#get(url, params = {}) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
# File 'app/controllers/concerns/shoplift_client.rb', line 168

def get(url, params = {})
  puts 'co_cli: get'
  puts "url: #{url}"
  puts "params: #{params}"
  response = srv.request(:get, url, body: params)
  JSON.parse(response.body)
rescue OAuth2::Error
  raise "Server fault, could not perform post to #{srv.client.site}#{url}"
rescue
  raise "Unknown error, could not perform post to #{srv.client.site}#{url}"
end

#post(url, params) ⇒ Object

To create/update a model, params must be of form { model_name: { attr1: value1, attr2: value2 } } and attr1, attr2 must be in the list of allowed params the Rails way.



156
157
158
159
160
161
162
163
164
165
166
# File 'app/controllers/concerns/shoplift_client.rb', line 156

def post(url, params)
  puts 'co_cli: post'
  puts "url: #{url}"
  puts "params: #{params}"
  response = srv.request(:post, url, body: params)
  JSON.parse(response.body)
rescue OAuth2::Error
  raise "Server fault, could not perform post to #{srv.client.site}#{url}"
rescue
  raise "Unknown error, could not perform post to #{srv.client.site}#{url}"
end

#redirect_unauthorizedObject



45
46
47
48
49
50
51
52
# File 'app/controllers/concerns/shoplift_client.rb', line 45

def redirect_unauthorized
  return if performed?
  session.clear
  session[:previous_url] = request.fullpath
  redirect_to client.auth_code.authorize_url(
    redirect_uri: Rails.configuration.settings['authlift_redirect_uri'],
    scope: scope)
end

#scopeObject



54
55
56
# File 'app/controllers/concerns/shoplift_client.rb', line 54

def scope
  [Rails.configuration.settings['authlift_default_scope'], 'public'].compact.join ' '
end


37
38
39
# File 'app/controllers/concerns/shoplift_client.rb', line 37

def session_cookie
  session["authlift_session_id"]
end

#session_cookie=(new_value) ⇒ Object



41
42
43
# File 'app/controllers/concerns/shoplift_client.rb', line 41

def session_cookie=(new_value)
  session["authlift_session_id"] = new_value
end

#srvObject



180
181
182
# File 'app/controllers/concerns/shoplift_client.rb', line 180

def srv
  @token ||= client.client_credentials.get_token scope: scope
end

#user_signed_in?Boolean

Returns:

  • (Boolean)


150
151
152
# File 'app/controllers/concerns/shoplift_client.rb', line 150

def user_signed_in?
  !current_user.nil?
end