Sha256: 919ca5e0a3fb20758ec55c58946ad4585c1860f0edb8593f1020b11148a6a2fc

Contents?: true

Size: 1.39 KB

Versions: 5

Compression:

Stored size: 1.39 KB

Contents

require 'active_support/concern'

require 'token_authenticate_me/controllers/token_authenticateable'

module TokenAuthenticateMe
  module Controllers
    module Sessionable
      extend ActiveSupport::Concern

      include TokenAuthenticateMe::Controllers::TokenAuthenticateable

      included do
        skip_before_action :authenticate, only: [:create]
        after_action :cleanup_sessions, only: [:destroy]

        def create
          resource = User.where('username=? OR email=?', params[:username], params[:username]).first
          if resource && resource.authenticate(params[:password])
            @session = Session.create(user_id: resource.id)
            render json: @session, status: 201
          else
            render json: { message: 'Bad credentials' }, status: 401
          end
        end

        def show
          @session = authenticate_token
          render json: @session
        end

        def destroy
          authenticate_token.destroy

          render status: 204, nothing: true
        rescue
          render_unauthorized
        end

        private

        def session_params
          params.permit(:username, :email, :password)
        end

        def cleanup_sessions
          ApiSession.where('expiration < ?', DateTime.now).delete_all
        rescue
          Rails.logger.warn 'Error cleaning up old authentication sessions'
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
token_authenticate_me-0.4.3 lib/token_authenticate_me/controllers/sessionable.rb
token_authenticate_me-0.4.2 lib/token_authenticate_me/controllers/sessionable.rb
token_authenticate_me-0.4.1 lib/token_authenticate_me/controllers/sessionable.rb
token_authenticate_me-0.4.0 lib/token_authenticate_me/controllers/sessionable.rb
token_authenticate_me-0.3.0 lib/token_authenticate_me/controllers/sessionable.rb