Users & Auth
This commit is contained in:
@ -1,4 +1,31 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
class ApplicationController < ActionController::API
|
||||
include Pundit
|
||||
|
||||
before_action :authenticate_request
|
||||
after_action :verify_authorized, except: :index
|
||||
after_action :verify_policy_scoped, only: :index
|
||||
|
||||
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
|
||||
|
||||
def index; end
|
||||
|
||||
private
|
||||
|
||||
def current_user
|
||||
@current_user ||= authenticate_request
|
||||
end
|
||||
|
||||
def authenticate_request
|
||||
return nil if request.authorization.blank?
|
||||
|
||||
@authenticate_request ||= AuthorizeRequest.new(request.headers).perform
|
||||
end
|
||||
|
||||
def user_not_authorized
|
||||
render \
|
||||
json: { authorization: ["You are not authorized to perform this action."] },
|
||||
status: :unauthorized
|
||||
end
|
||||
end
|
||||
|
23
app/controllers/v1/authentication_controller.rb
Normal file
23
app/controllers/v1/authentication_controller.rb
Normal file
@ -0,0 +1,23 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module V1
|
||||
class AuthenticationController < ApplicationController
|
||||
skip_after_action :verify_authorized
|
||||
skip_after_action :verify_policy_scoped
|
||||
|
||||
def authenticate
|
||||
command = AuthenticateUser.new(auth_params)
|
||||
@token = command.perform
|
||||
@user = command.user
|
||||
render "v1/authentication/authenticate" and return unless @token.nil?
|
||||
|
||||
render json: command.errors, status: :unauthorized
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def auth_params
|
||||
params.permit(:email, :password)
|
||||
end
|
||||
end
|
||||
end
|
47
app/controllers/v1/users_controller.rb
Normal file
47
app/controllers/v1/users_controller.rb
Normal file
@ -0,0 +1,47 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module V1
|
||||
class UsersController < ApplicationController
|
||||
before_action :set_user, only: %i[show update destroy]
|
||||
|
||||
def index
|
||||
@users = policy_scope User.all
|
||||
end
|
||||
|
||||
def show; end
|
||||
|
||||
def create
|
||||
@user = User.new(user_params)
|
||||
authorize @user
|
||||
|
||||
if @user.save
|
||||
render :show, status: :created, location: v1_users_url(@user)
|
||||
else
|
||||
render json: @user.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def update
|
||||
if @user.update(user_params)
|
||||
render :show, status: :ok, location: v1_users_url(@user)
|
||||
else
|
||||
render json: @user.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@user.destroy
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_user
|
||||
@user = User.find(params[:id])
|
||||
authorize @user
|
||||
end
|
||||
|
||||
def user_params
|
||||
params.require(:user).permit(policy(User).permitted_attributes)
|
||||
end
|
||||
end
|
||||
end
|
Reference in New Issue
Block a user