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



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'app/controllers/concerns/shoplift_client.rb', line 164

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
    handle_not_authorized '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
    handle_not_authorized 'Request not authorized'
  end

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

#authenticate_userObject



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
140
141
142
143
144
# File 'app/controllers/concerns/shoplift_client.rb', line 115

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_hash = @current_user = JSON.parse x.response.body
      unless @current_user['scopes'].is_a? String
        user_scopes = @current_user['scopes']
      else
        user_scopes = JSON.parse @current_user['scopes']
      end
      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'],
                           name: current_user['company']['name'],
                           logo_code: current_user['company']['logo_code']
    rescue OAuth2::Error
      return false
    end
  else
    return false
  end
  true
end

#authenticate_user!Object



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

def authenticate_user!
  redirect_unauthorized unless authenticate_user
end

#authenticate_user_or_api!Object



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

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

#clientObject



243
244
245
246
247
# File 'app/controllers/concerns/shoplift_client.rb', line 243

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

#company_infoObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/controllers/concerns/shoplift_client.rb', line 41

def company_info
  return @company_info if @company_info.present?

  @company_info = JSON.parse srv.get('/api/users/company_info').body
  ["clients", "suppliers"].each do |partner_type|
    @company_info[partner_type].each do |partner|
      partner[:company] = Company.find_or_create_by! code: partner['code']
      partner[:company].name = partner['name']
      partner[:company].info ||= {}
      partner[:company].info[:company_info] = partner['info']
      partner[:company].save!
    end
  end
  @company_info
end

#company_logo_path_definedObject



249
250
251
252
253
254
255
# File 'app/controllers/concerns/shoplift_client.rb', line 249

def company_logo_path_defined
  if  defined? self.company_logo_path
    company_logo_path
  else
    "https://media.shoplift.fi/company_logos/#{@current_user_json_hash['company']['logo_code']}_company_logo_24.png"
  end
end

#current_companyObject



206
207
# File 'app/controllers/concerns/shoplift_client.rb', line 206

def current_company
end

#current_userObject



200
201
202
203
204
# File 'app/controllers/concerns/shoplift_client.rb', line 200

def current_user
  return @current_user if @current_user.present?

  @current_user
end

#current_user_jsonObject



196
197
198
# File 'app/controllers/concerns/shoplift_client.rb', line 196

def current_user_json
  current_user.to_json
end

#find_company_by_code(code, parameters = {}) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'app/controllers/concerns/shoplift_client.rb', line 95

def find_company_by_code(code, parameters = {})
  begin
    @current_company ||= Company.find_or_create_by! code: code do |new_company|
      fail if parameters.empty?
      new_company.name = parameters[:name]
      new_company.info = parameters.to_json
    end
  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



227
228
229
230
231
232
233
234
235
236
237
# File 'app/controllers/concerns/shoplift_client.rb', line 227

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

#handle_not_authorized(message) ⇒ Object



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

def handle_not_authorized(message)
  if request.format.html?
    redirect_unauthorized
  else
    fail ActionController::RoutingError, message
  end
end

#hide_search_for_this_actionObject



57
58
59
# File 'app/controllers/concerns/shoplift_client.rb', line 57

def hide_search_for_this_action
  @do_hide_search_for_this_action = true
end

#local_authlift_redirect_uriObject



73
74
75
76
77
78
79
# File 'app/controllers/concerns/shoplift_client.rb', line 73

def local_authlift_redirect_uri
  if respond_to? :app_authlift_redirect_uri
    app_authlift_redirect_uri
  else
    Rails.configuration.settings['authlift_redirect_uri']
  end
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.



215
216
217
218
219
220
221
222
223
224
225
# File 'app/controllers/concerns/shoplift_client.rb', line 215

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



81
82
83
84
85
86
87
88
89
# File 'app/controllers/concerns/shoplift_client.rb', line 81

def redirect_unauthorized
  return if performed?
  session.clear
  session[:previous_url] = request.fullpath

  redirect_to client.auth_code.authorize_url(
    redirect_uri: local_authlift_redirect_uri,
    scope: scope)
end

#scopeObject



91
92
93
# File 'app/controllers/concerns/shoplift_client.rb', line 91

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


65
66
67
# File 'app/controllers/concerns/shoplift_client.rb', line 65

def session_cookie
  session["authlift_session_id"]
end

#session_cookie=(new_value) ⇒ Object



69
70
71
# File 'app/controllers/concerns/shoplift_client.rb', line 69

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

#show_search_for_this_actionObject



61
62
63
# File 'app/controllers/concerns/shoplift_client.rb', line 61

def show_search_for_this_action
  @do_hide_search_for_this_action = false
end

#srvObject



239
240
241
# File 'app/controllers/concerns/shoplift_client.rb', line 239

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

#user_signed_in?Boolean

Returns:

  • (Boolean)


209
210
211
# File 'app/controllers/concerns/shoplift_client.rb', line 209

def user_signed_in?
  !current_user.nil?
end