Class: Shakha::AuthController

Inherits:
ApplicationController show all
Includes:
PKCEMixin, RateLimiter
Defined in:
app/controllers/shakha/auth_controller.rb

Constant Summary

Constants included from PKCEMixin

PKCEMixin::CODE_CHALLENGE_METHOD, PKCEMixin::CODE_VERIFIER_LENGTH, PKCEMixin::PKCE_COOKIE_EXPIRY_SECONDS, PKCEMixin::PKCE_COOKIE_NAME

Instance Method Summary collapse

Methods included from PKCEMixin

generate_code_challenge, generate_code_verifier

Instance Method Details

#authorizeObject



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/controllers/shakha/auth_controller.rb', line 18

def authorize
  provider = resolve_provider
  pkce = create_pkce_bundle

  auth_url = provider.authorize_url(
    state: pkce[:state],
    code_challenge: pkce[:challenge],
    redirect_uri: callback_redirect_uri(provider),
    nonce: pkce[:nonce]
  )

  redirect_to auth_url, allow_other_host: true
end

#callbackObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/controllers/shakha/auth_controller.rb', line 32

def callback
  provider = resolve_provider
  pkce_result = verify_pkce!(params[:state])

  token_response = provider.exchange_code(
    code: params[:code],
    code_verifier: pkce_result[:verifier],
    redirect_uri: callback_redirect_uri(provider)
  )

  identity = provider.identity_from_response(token_response, expected_nonce: pkce_result[:nonce])
  user = find_or_create_user(provider.provider_name, identity)
  session_record = create_session(user)
  set_session_cookie(session_record)
  redirect_to build_return_url(pkce_result[:return_to], session_record), allow_other_host: true

rescue PKCEError, OAuthError => e
  handle_auth_failure(e, pkce_result)
end

#destroyObject



52
53
54
55
56
57
58
59
60
61
# File 'app/controllers/shakha/auth_controller.rb', line 52

def destroy
  current_session&.destroy
  cookies.delete(:shakha_session_token)

  if request.format.json?
    render json: { status: "signed_out" }
  else
    redirect_to params[:return_to].presence || "/"
  end
end

#errorObject



63
64
65
# File 'app/controllers/shakha/auth_controller.rb', line 63

def error
  @message = params[:message] || "Authentication failed"
end

#newObject



13
14
15
16
# File 'app/controllers/shakha/auth_controller.rb', line 13

def new
  @return_to = sanitize_return_to(params[:return_to])
  @providers = Shakha.config.providers
end