mirror of
https://github.com/ryankazokas/turbovault-app.git
synced 2026-04-17 02:52:55 +00:00
Moving to github
This commit is contained in:
38
app/controllers/api/v1/base_controller.rb
Normal file
38
app/controllers/api/v1/base_controller.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
module Api
|
||||
module V1
|
||||
class BaseController < ApplicationController
|
||||
skip_before_action :verify_authenticity_token
|
||||
before_action :authenticate_api_token
|
||||
|
||||
rescue_from ActiveRecord::RecordNotFound, with: :not_found
|
||||
rescue_from ActiveRecord::RecordInvalid, with: :unprocessable_entity
|
||||
|
||||
private
|
||||
|
||||
def authenticate_api_token
|
||||
token = request.headers["Authorization"]&.split(" ")&.last
|
||||
@api_token = ApiToken.active.find_by(token: token)
|
||||
|
||||
if @api_token
|
||||
@api_token.touch_last_used!
|
||||
@current_user = @api_token.user
|
||||
set_rls_user_id(@current_user.id)
|
||||
else
|
||||
render json: { error: "Invalid or missing API token" }, status: :unauthorized
|
||||
end
|
||||
end
|
||||
|
||||
def current_user
|
||||
@current_user
|
||||
end
|
||||
|
||||
def not_found(exception)
|
||||
render json: { error: exception.message }, status: :not_found
|
||||
end
|
||||
|
||||
def unprocessable_entity(exception)
|
||||
render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user