Skip to content

Instantly share code, notes, and snippets.

View promisepreston's full-sized avatar
💭
Gifted and Result-Oriented

Promise Chukwuenyem promisepreston

💭
Gifted and Result-Oriented
View GitHub Profile
@promisepreston
promisepreston / users_controller.rb
Last active September 4, 2019 14:10
Multi-tenant application for universities
<code data-gist-id="ec8cc541c45705a34988c68225627ecb" data-gist-hide-line-numbers="true"></code>
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
# define a command class
class AuthenticateUser
# put SimpleCommand before the class' ancestors chain
prepend SimpleCommand
include ActiveModel::Validations
# optional, initialize the command with some arguments
def initialize(email, password)
@email = email
@password = password
# config/locales/en.yml
en:
activemodel:
errors:
models:
authenticate_user:
failure: Wrong email or password
# app/controllers/authentication_controller.rb
class AuthenticationController < ApplicationController
skip_before_action :authenticate_request
def create
command = AuthenticateUser.call(params[:email], params[:password])
if command.success?
render json: { auth_token: command.result }
# config/application.rb
module ApiApp
class Application < Rails::Application
#.....
config.eager_load_paths << Rails.root.join('lib')
#.....
end
end
require 'jwt'
payload = { data: 'test' }
hmac_secret = 'my$ecretK3y'
token = JWT.encode(payload, hmac_secret, 'HS256')
#eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y
puts token
#config/routes.rb
namespace :api do
namespace :v1 do
post 'signin', to: 'authentication#create'
end
end
# lib/json_web_token.rb
class JsonWebToken
HMAC_SECRET = Rails.application.secrets.secret_key_base
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, HMAC_SECRET)
end
# app/services/authenticate_user.rb
class AuthenticateUser
def initialize(email, password)
@email = email
@password = password
end
def call
JsonWebToken.encode(user_id: user.id) if user
# app/services/authorize_api_request.rb
class AuthorizeApiRequest
def initialize(headers = {})
@headers = headers
end
def call
{ user: user }