Files
egbim_homepage/auth/callback.php
T

178 lines
6.8 KiB
PHP

<?php
require_once __DIR__ . '/common.php';
auth_session_start_if_needed();
$error = trim((string) ($_GET['error'] ?? ''));
$state = trim((string) ($_GET['state'] ?? ''));
$code = trim((string) ($_GET['code'] ?? ''));
$fallbackSite = 'egbim';
if ($error !== '') {
auth_script_redirect('BARON-SSO 로그인에 실패했습니다: ' . $error, auth_site_base_url($fallbackSite) . '/index.php');
}
if ($state === '' || $code === '') {
auth_script_redirect('BARON-SSO 응답값이 올바르지 않습니다.', auth_site_base_url($fallbackSite) . '/index.php');
}
$statePayload = auth_consume_baron_state($state);
if ($statePayload === null) {
auth_script_redirect('BARON-SSO state 검증에 실패했습니다.', auth_site_base_url($fallbackSite) . '/index.php');
}
$site = ($statePayload['site'] ?? 'egbim') === 'eng' ? 'eng' : 'egbim';
$redirectUrl = $statePayload['return_url'] ?? auth_site_qna_url($site);
$config = auth_baron_config();
if (!auth_baron_is_configured()) {
auth_script_redirect('BARON-SSO 설정이 아직 완료되지 않았습니다.', auth_site_base_url($site) . '/index.php');
}
$tokenRequestData = [
'grant_type' => 'authorization_code',
'redirect_uri' => auth_baron_redirect_uri(),
'code' => $code,
];
$basicAuthUser = null;
$basicAuthPassword = null;
if ($config['client_auth_method'] === 'post') {
$tokenRequestData['client_id'] = $config['client_id'];
$tokenRequestData['client_secret'] = $config['client_secret'];
} else {
$tokenRequestData['client_id'] = $config['client_id'];
$basicAuthUser = $config['client_id'];
$basicAuthPassword = $config['client_secret'];
}
$tokenResponse = auth_http_post_form(
$config['token_endpoint'],
$tokenRequestData,
[],
$basicAuthUser,
$basicAuthPassword
);
if ($tokenResponse['error'] !== '') {
auth_script_redirect('BARON-SSO 토큰 요청에 실패했습니다.', auth_site_base_url($site) . '/index.php');
}
$tokenData = json_decode($tokenResponse['body'], true);
if ($tokenResponse['http_code'] < 200 || $tokenResponse['http_code'] >= 300 || !is_array($tokenData)) {
if (auth_is_local_debug()) {
$debugMessage = sprintf(
'BARON token error HTTP %d | body=%s',
$tokenResponse['http_code'],
auth_compact_debug_value((string) $tokenResponse['body'])
);
auth_script_redirect($debugMessage, auth_site_base_url($site) . '/index.php');
}
auth_script_redirect('BARON-SSO 토큰 응답을 처리할 수 없습니다.', auth_site_base_url($site) . '/index.php');
}
$claims = [];
$idToken = trim((string) ($tokenData['id_token'] ?? ''));
if ($idToken !== '') {
$claims = auth_jwt_payload($idToken);
}
if ($config['userinfo_endpoint'] !== '' && !empty($tokenData['access_token'])) {
$userInfoResponse = auth_http_get_json($config['userinfo_endpoint'], (string) $tokenData['access_token']);
$userInfoData = json_decode($userInfoResponse['body'], true);
if ($userInfoResponse['http_code'] >= 200 && $userInfoResponse['http_code'] < 300 && is_array($userInfoData)) {
$claims = array_merge($claims, $userInfoData);
}
}
$user = auth_baron_user_from_claims($claims);
if (empty($user['userId']) || empty($user['loginIds'])) {
auth_script_redirect('BARON-SSO 사용자 정보를 확인할 수 없습니다.', auth_site_base_url($site) . '/index.php');
}
$normalizedUser = auth_apply_user_session($user, 'baron', [
'baron_access_token' => (string) ($tokenData['access_token'] ?? ''),
'baron_id_token' => $idToken,
]);
setcookie('descope_login_id', '', auth_cookie_options(time() - 42000));
setcookie('descope_user_id', '', auth_cookie_options(time() - 42000));
setcookie('descope_user_name', '', auth_cookie_options(time() - 42000));
setcookie('descope_user_email', '', auth_cookie_options(time() - 42000));
setcookie('descope_user_phone', '', auth_cookie_options(time() - 42000));
setcookie('descope_custom_attributes', '', auth_cookie_options(time() - 42000));
setcookie('descope_role_names', '', auth_cookie_options(time() - 42000));
setcookie('baron_user', '', auth_cookie_options(time() - 42000));
setcookie('baron_claims', '', auth_cookie_options(time() - 42000));
setcookie('baron_provider', '', auth_cookie_options(time() - 42000));
// BARON users are kept in the server-side PHP session above. Do not mirror
// the normalized user and the complete OIDC claims into cookies: the claims
// may contain a large tenants/roles payload and make the next Cookie header
// exceed Apache's request-header limit for only some accounts.
$clientSessionPayload = [
'loginId' => (string) ($normalizedUser['loginIds'][0] ?? ''),
'descopeUserId' => (string) ($normalizedUser['userId'] ?? ''),
'userName' => (string) ($normalizedUser['name'] ?? ''),
'phone' => (string) ($normalizedUser['phone'] ?? ''),
'company' => (string) ($normalizedUser['customAttributes']['company'] ?? ''),
'familyCompany' => (string) ($normalizedUser['customAttributes']['familyCompany'] ?? ''),
'team' => (string) ($normalizedUser['customAttributes']['team'] ?? ''),
'position' => (string) ($normalizedUser['customAttributes']['position'] ?? ''),
'familyUniqueKey' => (string) ($normalizedUser['customAttributes']['familyUniqueKey'] ?? ''),
'userRole' => (string) (($normalizedUser['roleNames'][0] ?? '')),
'authProvider' => 'baron',
'sessionJwt' => $idToken !== '' ? $idToken : (string) ($tokenData['access_token'] ?? ''),
];
$jsonPayload = json_encode($clientSessionPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$jsonRedirectUrl = json_encode($redirectUrl, JSON_UNESCAPED_SLASHES);
header('Content-Type: text/html; charset=UTF-8');
echo <<<HTML
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<title>Signing in...</title>
</head>
<body>
<script>
(function () {
var payload = {$jsonPayload} || {};
var redirectUrl = {$jsonRedirectUrl};
Object.keys(payload).forEach(function (key) {
var value = payload[key];
if (typeof value === 'string' && value !== '') {
sessionStorage.setItem(key, value);
localStorage.setItem(key, value);
} else {
sessionStorage.removeItem(key);
}
});
sessionStorage.removeItem('baronClaims');
localStorage.removeItem('baronClaims');
try {
window.dispatchEvent(new CustomEvent('descope-auth-changed', {
detail: { loginId: payload.loginId || '' }
}));
} catch (e) {}
window.location.replace(redirectUrl);
})();
</script>
</body>
</html>
HTML;
exit;
?>