Skip to content

User session feature

Vladislav Trotsenko edited this page Sep 27, 2019 · 5 revisions

This is basic user session feature. It consists of 3 endpoints:

POST /api/v1/users/session

The point of this endpoint is create user session (sign in) by auth user credentials.

SessionsController#create

module Api::V1::Users
  class SessionsController < ApiController
    def create
      endpoint Api::V1::Users::Sessions::Operation::Create
    end
  end
end

Operation

module Api::V1::Users::Sessions::Operation
  class Create < ApplicationOperation
    step Macro::Contract::Schema(Api::V1::Users::Sessions::Contract::Create)
    step Contract::Validate(), fail_fast: true
    step Model(Account, :find_by_email, :email)
    fail Macro::Semantic(failure: :not_found)
    fail Macro::AddContractError(base: 'errors.session.not_found'), fail_fast: true
    step :authenticate
    fail Macro::Semantic(failure: :unauthorized)
    fail Macro::AddContractError(base: 'errors.session.wrong_credentials'), fail_fast: true
    step :set_user_tokens # sets session tokens bundle into ctx[:tokens]
    step Macro::Semantic(success: :created)
    step Macro::Renderer(serializer: Api::V1::Lib::Serializer::Account, meta: :tokens)
  end
end

Used nested & macroses

DELETE /api/v1/users/session

The point of this endpoint is destroy user session (sign out) by X-Refresh-Token.

SessionsController#destroy

module Api::V1::Users
  class SessionsController < ApiController
    def destroy
      authorize_refresh_request! # authorize by X-Refresh-Token in headers
      endpoint Api::V1::Users::Sessions::Operation::Destroy,
               options: { found_token: found_token } # passes refresh token to operation
    end
  end
end

Operation

module Api::V1::Users::Sessions::Operation
  class Destroy < ApplicationOperation
    step Rescue(JWTSessions::Errors::Unauthorized) {
      step :destroy_user_session # destroy current user session
    }
    step Macro::Semantic(success: :destroyed)
  end
end

Used nested & macroses

POST /api/v1/users/session/refresh

The point of this endpoint is refresh user session by X-Refresh-Token.

RefreshesController#create

class RefreshesController < ApiController
    def create
      authorize_refresh_request!  # authorize by X-Refresh-Token in headers
      endpoint Api::V1::Users::Sessions::Refreshes::Operation::Create,
               options: { found_token: found_token, payload: payload }  # passes refresh token and payload to operation
    end
  end
end

Operation

module Api::V1::Users::Sessions::Refreshes::Operation
  class Create < ApplicationOperation
    step Rescue(JWTSessions::Errors::Unauthorized) {
      step :refresh_user_tokens # also user session will be destroyed if detected attempt to refresh unexpired access
    }
    fail Macro::Semantic(failure: :forbidden)
    step Macro::Semantic(success: :created)
    step Macro::Renderer(meta: :tokens)
  end
end

Used nested & macroses

Clone this wiki locally