Module: Tinytokenauth::Authorizable
- Defined in:
- lib/tinytokenauth/authorizable.rb
Instance Method Summary collapse
- #authorize_with_header ⇒ Object
- #current_user ⇒ Object
- #require_current_user(&block) ⇒ Object
- #set_current_user ⇒ Object
- #sign_in_with_token(user) ⇒ Object
- #sign_out_with_token ⇒ Object
Instance Method Details
#authorize_with_header ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/tinytokenauth/authorizable.rb', line 16 def 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. }, status: :unauthorized rescue JWT::DecodeError => e render json: { errors: e. }, status: :unauthorized end end |
#current_user ⇒ Object
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 = [Tinytokenauth.configuration.] 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 sign_in_with_token @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_user ⇒ Object
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 sign_in_with_token(user) @current_user = user jwt = JsonWebToken.encode(Tinytokenauth.configuration.token_validity_hours.hours.from_now, Tinytokenauth.configuration.token_secret, tinytokenauth_id: user.id,) [Tinytokenauth.configuration.] = jwt end |
#sign_out_with_token ⇒ Object
75 76 77 |
# File 'lib/tinytokenauth/authorizable.rb', line 75 def sign_out_with_token [Tinytokenauth.configuration.] = nil end |