Class: Anoubis::Core::ApplicationController

Inherits:
ActionController::API
  • Object
show all
Includes:
ActionController::MimeResponds
Defined in:
app/controllers/anoubis/core/application_controller.rb

Overview

Application controller for Anubis library.

Instance Attribute Summary collapse

Block of authorization collapse

Block of UUID functions collapse

Instance Method Summary collapse

Instance Attribute Details

#current_userActiveRecord

Returns Specifies current user (defaults to: nil).

Returns:

  • (ActiveRecord)

    Specifies current user (defaults to: nil).



23
24
25
# File 'app/controllers/anoubis/core/application_controller.rb', line 23

def current_user
  @current_user
end

#etcAnoubis::Etc::Base

Returns global system parameters.

Returns:



35
36
37
# File 'app/controllers/anoubis/core/application_controller.rb', line 35

def etc
  @etc
end

#exportsAnoubis::Export

Returns Export data class.

Returns:



39
40
41
# File 'app/controllers/anoubis/core/application_controller.rb', line 39

def exports
  @exports
end

#localeString

Parameters receive from URL or user definition

Returns:

  • (String)

    Specifies the current language locale (defaults to: ‘ru’).



19
20
21
# File 'app/controllers/anoubis/core/application_controller.rb', line 19

def locale
  @locale
end

#outputAnoubis::Output

Returns standard output.

Returns:



27
28
29
# File 'app/controllers/anoubis/core/application_controller.rb', line 27

def output
  @output
end

#versionInteger

Returns Specifies the api version. Parameters receive from URL (defaults to: 0).

Returns:

  • (Integer)

    Specifies the api version. Parameters receive from URL (defaults to: 0).



14
15
16
# File 'app/controllers/anoubis/core/application_controller.rb', line 14

def version
  @version
end

#writerObject

Returns Specifies access of current user to this controller (defaults to: false).

Returns:

  • (Object)

    Specifies access of current user to this controller (defaults to: false).



31
32
33
# File 'app/controllers/anoubis/core/application_controller.rb', line 31

def writer
  @writer
end

Instance Method Details

#access_allowed?Boolean

Check access for API.

Returns:

  • (Boolean)

    access for requested client



241
242
243
244
245
# File 'app/controllers/anoubis/core/application_controller.rb', line 241

def access_allowed?
  allowed_sites = [request.env['HTTP_ORIGIN']]

  allowed_sites.include?(request.env['HTTP_ORIGIN'])
end

#after_initializationObject

Calls after first controller initialization



101
102
103
# File 'app/controllers/anoubis/core/application_controller.rb', line 101

def after_initialization

end

#anubis_core_initializationObject

Sets default parameters for application controller.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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/anoubis/core/application_controller.rb', line 49

def anubis_core_initialization
  self.version = 0

  if defined? params
    self.etc = Anoubis::Etc::Base.new({ params: params })
  else
    self.etc = Anoubis::Etc::Base.new
  end
  self.output = nil
  self.exports = nil
  self.writer = false

  self.current_user = nil
  self.locale = params[:locale] if params.has_key? :locale
  self.locale = 'ru' unless self.locale
  self.locale = 'ru' if self.locale == ''
  begin
    I18n.locale = self.locale
  rescue
    I18n.locale = 'ru'
  end

  return if request.method == 'OPTIONS'

  if !params.has_key? :version
    self.error_exit({ error: I18n.t('errors.no_api_version') })
    return
  end

  if self.access_allowed?
    self.set_access_control_headers
  else
    self.error_exit({ error: I18n.t('errors.access_not_allowed') })
  end

  self.version = params[:version]

  if self.authenticate?
    if self.authentication
      if self.check_menu_access?
        return if !self.menu_access params[:controller]
      end
    end
  end

  #self.user_time_zone if self.current_user
  Time.zone = self.current_user.timezone if self.current_user
  self.after_initialization
end

#authenticate?Boolean

Checks if needed user authentication.

Returns:

  • (Boolean)

    if true, then user must be authenticated.



148
149
150
# File 'app/controllers/anoubis/core/application_controller.rb', line 148

def authenticate?
  return true
end

#authenticationObject

Authenticates user in the system



154
155
156
157
158
159
160
161
162
163
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'app/controllers/anoubis/core/application_controller.rb', line 154

def authentication
  if !self.token
    self.error_exit({ error: I18n.t('errors.authentication_required') })
    return false
  end

  # Check session presence
  session = self.redis.get(self.redis_prefix + 'session:' + self.token)
  if !session
    self.error_exit({ error: I18n.t('errors.session_expired') })
    return false
  end

  session = JSON.parse(session, { symbolize_names: true })

  if !session.has_key?(:uuid) || !session.has_key?(:ttl)
    self.error_exit({ error: I18n.t('errors.session_expired') })
    return false
  end

  if session[:ttl] < Time.now
    self.error_exit({ error: I18n.t('errors.session_expired') })
    self.redis.del(self.redis_prefix + 'session:' + self.token)
    return false
  end

  # Load user data from redis database
  user_json = self.redis.get(self.redis_prefix + 'user:' + session[:uuid])
  if !user_json
    # Check user presence based on session user UUID
    user = self.get_user_model.where(uuid_bin: self.uuid_to_bin(session[:uuid])).first
    if !user
      self.error_exit({ error: I18n.t('errors.authentication_required') })
      return false
    end
    user_json = self.redis_save_user user
  end

  begin
    self.current_user = self.get_user_model.new(JSON.parse(user_json,{ symbolize_names: true }))
  rescue
    self.current_user = nil
  end

  if !self.current_user
    self.error_exit({ error: I18n.t('errors.authentication_required') })
    return false
  end

  session[:time] = Time.now
  session[:ttl] = session[:time] + self.current_user.timeout
  self.redis.set(self.redis_prefix + 'session:' + self.token, session.to_json)

  true
end

#bin_to_uuid(data) ⇒ String?

Decodes binary UUID data into the UUID string

Parameters:

  • data (Binary)

    binary representation of UUID

Returns:

  • (String, nil)

    string representation of UUID or nil if can’t be decoded



264
265
266
267
268
269
270
271
# File 'app/controllers/anoubis/core/application_controller.rb', line 264

def bin_to_uuid(data)
  begin
    data = data.unpack('H*')[0]
    return data[0..7]+'-'+data[8..11]+'-'+data[12..15]+'-'+data[16..19]+'-'+data[20..31]
  rescue
    return nil
  end
end

#check_menu_access?Boolean

Checks user must have access for current controller.

Returns:

  • (Boolean)

    if true, then user must have access for this controller.



213
214
215
# File 'app/controllers/anoubis/core/application_controller.rb', line 213

def check_menu_access?
  true
end

#default_localeObject

Returns default defined locale



329
330
331
# File 'app/controllers/anoubis/core/application_controller.rb', line 329

def default_locale
  Rails.configuration.i18n.default_locale.to_s
end

#error_exit(data) ⇒ Object

Gracefully terminate script execution with code 422 (Unprocessable entity). And JSON data

Parameters:

  • data (Hash)

    Resulting data

Options Hash (data):

  • :code (Integer)

    resulting error code

  • :error (String)

    resulting error message



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'app/controllers/anoubis/core/application_controller.rb', line 111

def error_exit(data)
  result = {
    result: -1,
    message: 'Error'
  }
  result[:result] = data[:code] if data.has_key? :code
  result[:message] = data[:error] if data.has_key? :error
  respond_to do |format|
    format.json { render json: result, status: :unprocessable_entity }
  end
  begin
    exit
  rescue SystemExit => e

  end
end

#get_user_modelActiveRecord

Get current user model

Returns:

  • (ActiveRecord)

    defined user model. It is used for get current user data. May be redefined when user model is changed



131
132
133
# File 'app/controllers/anoubis/core/application_controller.rb', line 131

def get_user_model
  nil
end

#get_user_model_exceptArray

Get current user model filed json exception

Returns:

  • (Array)

    defined user exception for to_json function



138
139
140
# File 'app/controllers/anoubis/core/application_controller.rb', line 138

def get_user_model_except
  []
end

Check menu access for current user of current controller

Returns:

  • (Boolean)

    if true, then user have access for this controller.



220
221
222
223
224
# File 'app/controllers/anoubis/core/application_controller.rb', line 220

def menu_access(controller, exit = true)
  self.writer = true

  true
end

#new_session_idstring

Generates new session ID

Returns:

  • (string)

    string representation of session (64 bytes)



295
296
297
# File 'app/controllers/anoubis/core/application_controller.rb', line 295

def new_session_id
  SecureRandom.hex(32)
end

#new_uuidString

Generates new UUID data

Returns:

  • (String)

    string representation of UUID



288
289
290
# File 'app/controllers/anoubis/core/application_controller.rb', line 288

def new_uuid
  SecureRandom.uuid
end

#optionsObject

Default route for OPTIONS method



335
336
337
338
339
340
341
342
# File 'app/controllers/anoubis/core/application_controller.rb', line 335

def options
  if self.access_allowed?
    self.set_access_control_headers
    head :ok
  else
    head :forbidden
  end
end

#redisObject

Returns redis database class



43
44
45
# File 'app/controllers/anoubis/core/application_controller.rb', line 43

def redis
  @redis ||= Redis.new
end

#redis_prefixObject

Returns defined application prefix for redis cache for controller. Default value ”



317
318
319
320
321
322
323
324
325
# File 'app/controllers/anoubis/core/application_controller.rb', line 317

def redis_prefix
  begin
    value = Rails.configuration.redis_prefix
  rescue
    return ''
  end

  value + ':'
end

#redis_save_user(user) ⇒ String

Saves user data into redis database and returns user JSON representation

Parameters:

  • user (ActiveRecord)

    current user data

Returns:

  • (String)

    JSON representation of user data



305
306
307
308
309
310
311
312
313
# File 'app/controllers/anoubis/core/application_controller.rb', line 305

def redis_save_user(user)
  user_json = user.to_json(except: self.get_user_model_except)
  user_hash = JSON.parse user_json, { symbolize_names: true }
  user_hash[:uuid] = user.uuid
  user_json = user_hash.to_json
  self.redis.set(self.redis_prefix + 'user:' + user.uuid, user_json)

  user_json
end

#set_access_control_headersObject

Set allow header information for multi-domain requests. Requested for browsers when API is not in the same address as Frontend application.



250
251
252
253
254
255
# File 'app/controllers/anoubis/core/application_controller.rb', line 250

def set_access_control_headers
  headers['Access-Control-Allow-Origin'] = request.env['HTTP_ORIGIN']
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE, PUT, PATCH'
  headers['Access-Control-Max-Age'] = '1000'
  headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,Authorization'
end

#tokenString

Get current token based on HTTP Authorization

Returns:

  • (String)

    current token



229
230
231
232
233
234
# File 'app/controllers/anoubis/core/application_controller.rb', line 229

def token
  if Rails.env.development?
    return params[:token] if params[:token]
  end
  request.env.fetch('HTTP_AUTHORIZATION', '').scan(/Bearer (.*)$/).flatten.last
end

#uuid_to_bin(data) ⇒ Binary?

Encodes string UUID data into the binary UUID

Parameters:

  • data (Binary)

    string representation of UUID

Returns:

  • (Binary, nil)

    binary representation of UUID or nil if can’t be encoded



277
278
279
280
281
282
283
# File 'app/controllers/anoubis/core/application_controller.rb', line 277

def uuid_to_bin(data)
  begin
    return [data.delete('-')].pack('H*')
  rescue
    return nil
  end
end