Class: V1::Users::SessionsController

Inherits:
Devise::SessionsController
  • Object
show all
Defined in:
app/controllers/v1/users/sessions_controller.rb

Overview

Sesssions Controller Allows the user to create sessions, authenticating Uses Devise + Tiddle Authentication is done via tokens, using GitHub

Instance Method Summary collapse

Instance Method Details

#createObject

before_action :configure_sign_in_params, only: [:create]


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/controllers/v1/users/sessions_controller.rb', line 12

def create
  user = User.find_by(id: request.headers["X-USER-ID"])
  token = request.headers["X-USER-CODE"]
  if user && token && Tiddle::TokenIssuer.build.find_token(user, token)
    render json: { data: { user: user, authentication_token: token } }
    return
  end

  logger.info 'Creating session, verifying code sent'

  code = params[:code] || request.headers[:code] # Get code from headers or params
  if code.nil?
    logger.warn 'Null code, impossible to authenticate'
    render json: ErrorExchange.new(:auth_code_error, :not_acceptable, {}), status: :not_acceptable
    return
  end

  provider = params[:provider] || request.headers[:provider]
  if provider.nil?
    logger.warn 'Null provider, impossible to authenticate'
    render json: ErrorExchange.new(:auth_provider_error, :not_acceptable, {}), status: :not_acceptable
    return
  end
  begin
    verify = verify_user!(code, provider, request)
    if verify.kind_of? ErrorExchange
      render json: verify, status: verify.status
      return
    end
    user,token = verify
  rescue Octokit::NotFound
    logger.info 'User not found'
    render json: ErrorExchange.new(:auth_github_code_error, :unauthorized, {}), status: :unauthorized
    return
  rescue Octokit::Unauthorized
    logger.info 'User is not authorized'
    render json: ErrorExchange.new(:auth_github_unauthorized_error, :unauthorized, {}), status: :unauthorized
    return
  end
  # Return token
  if token
    logger.info 'Returning user info and token'
    render json: { data: { user: user, authentication_token: token } }
  else
    logger.info 'Authentication token error'
    render json: ErrorExchange.new(:auth_token_error, :unauthorized, {}), status: :unauthorized
  end
end

#destroyObject


61
62
63
64
65
# File 'app/controllers/v1/users/sessions_controller.rb', line 61

def destroy
  logger.info 'Destroying session'
  Tiddle.expire_token(current_user, request) if current_user
  return_response json: {}
end