Friday, September 20, 2024 12:06:57 AM
> settings

Customize


Authenticate

> api_controller.rb
# frozen_string_literal: true

class ApiController < ApplicationController
  API_LOGGER = Logger.new("log/api.log")

  before_action :check_for_access
  before_action :log

  private

  def check_for_access
    authorization_token = request.headers["HTTP_AUTHORIZATION"].sub("Bearer ", "")
    return unauthorized if authorization_token.blank? || authorization_token.size != 32

    @token = ApiToken.where(token: authorization_token).first
    return unauthorized if @token.nil?
  end

  def unauthorized
    render json: {code: 401, message: "401 Unauthorized"}, status: :unauthorized
  end

  def log
    API_LOGGER.info("#{@token.comment} [C:#{request.client_ip} - R:#{request.remote_ip}] - #{request.url}")
  end
end
All opinions represented herein are my own
- © 2024 itsthedevman
- build 3c15a1b