Module: Jwtauth::Controller

Defined in:
lib/jwtauth.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



226
227
228
229
230
231
232
233
# File 'lib/jwtauth.rb', line 226

def self.included(base)
  base.extend ClassMethods

  base.class_eval do
    attr_reader :current_user
    rescue_from Jwtauth::AuthorizedError, with: :user_not_authenticated
  end
end

Instance Method Details

#authorize_user!Object

Authorize user



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 'lib/jwtauth.rb', line 176

def authorize_user!
  if Jwtauth.test_mode?
    return @current_user = Jwtauth.current_user
  end

  begin
    res = Jwtauth::Session.getjwt(request)
  rescue Exception => e
    raise Jwtauth::SocketError, "authservice not available"
  end

  case res
  when Net::HTTPSuccess
    begin
      payload = Jwtauth::Session.expjwt_decode(JSON.parse(res.body)['jwt'])

      if logger && payload[1] && payload[1]["alg"] != Jwtauth.algorithm
        logger.warn "Algorithm #{Jwtauth.algorithm} is required (payload has #{payload[1]["alg"]})"
      end

      raise Jwtauth::ExpiredError, "session expired" if Time.now.to_i > payload[0]['exp']

      # Assign current session of user request
      @current_user = Jwtauth.session_entity.new(payload[0]['data'])
    rescue Exception => e
      raise Jwtauth::AuthorizedError, "payload authorized errors"
    end
  when Net::HTTPUnauthorized
    raise Jwtauth::UnauthorizedError, "You need to sign in or sign up before continuing."
  else
    raise Jwtauth::AuthorizedError, "authorized errors"
  end
end

#user_not_authenticated(exception) ⇒ Object

Handle for user not authorized



211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/jwtauth.rb', line 211

def user_not_authenticated(exception)
  status = :forbidden

  case exception
  when Jwtauth::UnauthorizedError
    status = :unauthorized
  when Jwtauth::ExpiredError
    status = :request_timeout
  when Jwtauth::SocketError
    status = :internal_server_error
  end

  render json: {errors: [exception.message]}, status: status
end