Module: Tinytokenauth::Authorizable

Defined in:
lib/tinytokenauth/authorizable.rb

Instance Method Summary collapse

Instance Method Details

#authorize_with_headerObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/tinytokenauth/authorizable.rb', line 16

def authorize_with_header
  token = ''
  header = request.headers['Authorization']
  token = header.split(' ').last if header

  begin
    @decoded = JsonWebToken.decode(Tinytokenauth.configuration.token_secret, token)
    @current_user = Tinytokenauth.configuration.user_class.constantize.send 'find', @decoded[:tinytokenauth_id]
  rescue ActiveRecord::RecordNotFound => e
    render json: { errors: e.message }, status: :unauthorized
  rescue JWT::DecodeError => e
    render json: { errors: e.message }, status: :unauthorized
  end
end

#current_userObject



79
80
81
# File 'lib/tinytokenauth/authorizable.rb', line 79

def current_user
  @current_user
end

#require_current_user(&block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tinytokenauth/authorizable.rb', line 31

def require_current_user(&block)
  token = cookies[Tinytokenauth.configuration.cookie_name]
  begin
    @decoded = JsonWebToken.decode(Tinytokenauth.configuration.token_secret, token)
    @current_user = Tinytokenauth.configuration.user_class.constantize.send 'find', @decoded[:tinytokenauth_id]
    @exp = @decoded[:exp]
    if Tinytokenauth.configuration.token_auto_renew_hours &&
      @exp < Tinytokenauth.configuration.token_auto_renew_hours.hours.from_now.to_i
       @current_user
    end
  rescue ActiveRecord::RecordNotFound => e
    if block_given? && current_user.nil?
      block.call
    else
      raise e
    end
  rescue JWT::DecodeError => e
    if block_given? && current_user.nil?
      block.call
    else
      raise e
    end
  end
end

#set_current_userObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/tinytokenauth/authorizable.rb', line 56

def set_current_user
  begin
    require_current_user
  rescue ActiveRecord::RecordNotFound
    # Ignored
  rescue JWT::DecodeError
    # Ignored
  end
  @current_user
end

#sign_in_with_token(user) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/tinytokenauth/authorizable.rb', line 67

def (user)
  @current_user = user
  jwt = JsonWebToken.encode(Tinytokenauth.configuration.token_validity_hours.hours.from_now,
                            Tinytokenauth.configuration.token_secret,
                            tinytokenauth_id: user.id,)
  cookies[Tinytokenauth.configuration.cookie_name] = jwt
end

#sign_out_with_tokenObject



75
76
77
# File 'lib/tinytokenauth/authorizable.rb', line 75

def sign_out_with_token
  cookies[Tinytokenauth.configuration.cookie_name] = nil
end