Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # app/controllers/application_controller.rb
- class ApplicationController < ActionController::API
- rescue_from BasicAuthenticate::NotAuthenticated, with: :not_authenticated
- private
- def authorize!
- AuthenticateByToken.new(request.headers['Authorization']).call
- end
- def not_authenticated
- render json: { error: ['Not Authenticated'] }, status: :unauthorized
- end
- end
- # app/controllers/authentication_controller.rb
- class AuthenticationController < ApplicationController
- def create
- token = GetToken.new(email: params[:email], password: params[:password]).call
- render json: { auth_token: token }, status: :ok
- end
- end
- # app/controllers/pictures_controller.rb
- class PicturesController < ApplicationController
- before_action :authorize!
- # ...
- end
- # lib/basic_authenticate.rb
- module BasicAuthenticate
- class NotAuthenticated < StandardError; end
- private
- def secret
- @secret = Rails.application.secrets.secret_key_base
- end
- end
- # app/services/get_token.rb
- class GetToken
- include BasicAuthenticate
- attr_reader :email, :password
- def initialize(email:, password:)
- @email = email
- @password = password
- end
- def call
- user = User.find_by(email: email)
- if user&.authenticate(password)
- payload = { 'sub' => user.id }
- encode_payload(payload)
- else
- raise NotAuthenticated
- end
- end
- private
- def encode_payload(payload)
- JWT.encode(payload, secret)
- end
- end
- # app/services/authenticate_by_token.rb
- class AuthenticateByToken
- include BasicAuthenticate
- attr_reader :token
- def initialize(token)
- @token = token
- end
- def call
- user_id = decode_payload(token)
- User.find(user_id['sub'])
- rescue
- raise NotAuthenticated
- end
- private
- def decode_payload(payload)
- JWT.decode(payload, secret).first
- end
- end
Add Comment
Please, Sign In to add comment