Guest User

Untitled

a guest
Nov 16th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. # app/controllers/application_controller.rb
  2. class ApplicationController < ActionController::API
  3. rescue_from BasicAuthenticate::NotAuthenticated, with: :not_authenticated
  4.  
  5. private
  6.  
  7. def authorize!
  8. AuthenticateByToken.new(request.headers['Authorization']).call
  9. end
  10.  
  11. def not_authenticated
  12. render json: { error: ['Not Authenticated'] }, status: :unauthorized
  13. end
  14. end
  15.  
  16. # app/controllers/authentication_controller.rb
  17. class AuthenticationController < ApplicationController
  18. def create
  19. token = GetToken.new(email: params[:email], password: params[:password]).call
  20. render json: { auth_token: token }, status: :ok
  21. end
  22. end
  23.  
  24. # app/controllers/pictures_controller.rb
  25. class PicturesController < ApplicationController
  26. before_action :authorize!
  27. # ...
  28. end
  29.  
  30. # lib/basic_authenticate.rb
  31. module BasicAuthenticate
  32. class NotAuthenticated < StandardError; end
  33.  
  34. private
  35.  
  36. def secret
  37. @secret = Rails.application.secrets.secret_key_base
  38. end
  39. end
  40.  
  41. # app/services/get_token.rb
  42. class GetToken
  43. include BasicAuthenticate
  44.  
  45. attr_reader :email, :password
  46.  
  47. def initialize(email:, password:)
  48. @email = email
  49. @password = password
  50. end
  51.  
  52. def call
  53. user = User.find_by(email: email)
  54. if user&.authenticate(password)
  55. payload = { 'sub' => user.id }
  56. encode_payload(payload)
  57. else
  58. raise NotAuthenticated
  59. end
  60. end
  61.  
  62. private
  63.  
  64. def encode_payload(payload)
  65. JWT.encode(payload, secret)
  66. end
  67. end
  68.  
  69. # app/services/authenticate_by_token.rb
  70. class AuthenticateByToken
  71. include BasicAuthenticate
  72.  
  73. attr_reader :token
  74.  
  75. def initialize(token)
  76. @token = token
  77. end
  78.  
  79. def call
  80. user_id = decode_payload(token)
  81. User.find(user_id['sub'])
  82. rescue
  83. raise NotAuthenticated
  84. end
  85.  
  86. private
  87.  
  88. def decode_payload(payload)
  89. JWT.decode(payload, secret).first
  90. end
  91. end
Add Comment
Please, Sign In to add comment