Merged in feat/LOY-230-Microsoft-Entra-ID-Auth (pull request #2113)

Feat(LOY-230): DTMC Routes with Entra ID Auth & Error Page Handling

* feat(LOY-230): Link Scandic Friends and Azure accounts

* fix(LOY-230): remove employee id param setting

* fix(LOY-230): return token in jwt callback for auth.dtmc.ts


Approved-by: Michael Zetterberg
Approved-by: Christian Andolf
This commit is contained in:
Chuma Mcphoy (We Ahead)
2025-06-18 10:22:04 +00:00
parent 9df19fda7c
commit 2101b79db1
23 changed files with 568 additions and 165 deletions

View File

@@ -0,0 +1,45 @@
import { NextResponse } from "next/server"
import { AuthError } from "next-auth"
import { dtmcApiCallback } from "@/constants/routes/dtmc"
import { env } from "@/env/server"
import { internalServerError, serviceUnavailable } from "@/server/errors/next"
import { signIn } from "@/auth.dtmc"
export async function GET() {
try {
const redirectUrl = await signIn(
"microsoft-entra-id",
{
redirectTo: `${env.PUBLIC_URL}${dtmcApiCallback}`,
redirect: false,
},
{
prompt: "login",
}
)
if (redirectUrl) {
console.log(`[dtmc] redirecting to: ${redirectUrl}`)
return NextResponse.redirect(redirectUrl)
} else {
console.error(`[dtmc] missing redirectUrl response from signIn()`)
return internalServerError(
"[dtmc] Missing redirect URL from authentication service"
)
}
} catch (error) {
if (error instanceof AuthError) {
console.error({ signInAuthError: error })
return serviceUnavailable(
"[dtmc] Microsoft authentication service unavailable"
)
} else {
console.error({ signInError: error })
return internalServerError(
"[dtmc] Unexpected error during authentication"
)
}
}
}

View File

@@ -20,7 +20,7 @@
}
.nav {
padding: var(--Spacing-x2);
padding: var(--Space-x2);
display: flex;
align-items: center;
justify-content: space-between;
@@ -50,8 +50,8 @@
display: flex;
align-items: center;
justify-content: center;
padding-left: var(--Spacing-x3);
padding-right: var(--Spacing-x3);
padding-left: var(--Space-x3);
padding-right: var(--Space-x3);
}
.card {
@@ -62,25 +62,25 @@
padding: var(--Spacing-x5);
border-radius: var(--Corner-radius-lg);
display: grid;
gap: var(--Spacing-x3);
gap: var(--Space-x3);
}
.formElements {
display: flex;
flex-direction: column;
gap: var(--Spacing-x3);
gap: var(--Space-x3);
}
.checkboxContainer {
display: flex;
flex-direction: column;
gap: var(--Spacing-x1);
gap: var(--Space-x1);
}
.checkboxWrapper {
display: flex;
align-items: center;
gap: var(--Spacing-x-one-and-half);
gap: var(--Space-x15);
cursor: pointer;
}
@@ -110,7 +110,7 @@
}
.termsTextFull {
padding-left: var(--Spacing-x5);
padding-left: var(--Space-x5);
}
.link {
@@ -118,3 +118,11 @@
text-decoration: underline;
font-weight: var(--Font-weight-Bold);
}
.contactSection {
padding-top: var(--Space-x3);
gap: var(--Space-x15);
display: flex;
flex-direction: column;
place-items: center;
}

View File

@@ -0,0 +1,146 @@
"use client"
import Image from "next/image"
import { useSearchParams } from "next/navigation"
import { type IntlShape, useIntl } from "react-intl"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import ScandicLogoIcon from "@scandic-hotels/design-system/Icons/ScandicLogoIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { supportEmail, supportPhone } from "@/constants/contactSupport"
import { employeeBenefits } from "@/constants/routes/dtmc"
import ButtonLink from "@/components/ButtonLink"
import Link from "@/components/TempDesignSystem/Link"
import useLang from "@/hooks/useLang"
import background from "@/public/_static/img/Scandic_Computer_Coffee.png"
import styles from "./linkEmploymentError.module.css"
export default function LinkEmploymentErrorPage() {
const lang = useLang()
const intl = useIntl()
const searchParams = useSearchParams()
const error = searchParams.get("error")
const errorContent = getErrorContent(error, intl)
return (
<div className={styles.pageWrapper}>
<Image
src={background}
alt=""
fill
className={styles.backgroundImage}
priority
sizes="100vw"
/>
<div className={styles.contentContainer}>
<nav className={styles.nav}>
<ButtonLink href={employeeBenefits[lang]} variant="Text">
<MaterialIcon
icon="chevron_left"
size={20}
className={styles.backArrow}
/>
<span className={styles.navBackText}>
{intl.formatMessage({
defaultMessage: "Go back",
})}
</span>
</ButtonLink>
<div className={styles.logoContainer}>
<ScandicLogoIcon
color="Icon/Interactive/Accent"
height="20px"
width="94px"
/>
</div>
</nav>
<main className={styles.mainContent}>
<div style={{ textAlign: "center" }} className={styles.card}>
<Typography variant="Title/Subtitle/lg">
<h1>{errorContent.heading}</h1>
</Typography>
<Typography variant="Body/Paragraph/mdRegular">
<p>{errorContent.message}</p>
</Typography>
<div className={styles.contactSection}>
<Typography variant="Title/Subtitle/md">
<h3>
{intl.formatMessage({
defaultMessage: "Contact our member service",
})}
</h3>
</Typography>
<Typography variant="Link/sm">
<Link
color="Text/Interactive/Secondary"
href={`tel:${supportPhone[lang].replaceAll(" ", "")}`}
textDecoration="underline"
>
{supportPhone[lang]}
</Link>
</Typography>
<Typography variant="Link/sm">
<Link
href={`mailto:${supportEmail[lang]}`}
color="Text/Interactive/Secondary"
textDecoration="underline"
>
{supportEmail[lang]}
</Link>
</Typography>
</div>
</div>
</main>
</div>
</div>
)
}
const getErrorContent = (error: string | null, intl: IntlShape) => {
const defaultErrorContent = {
heading: intl.formatMessage({
defaultMessage: "Your account could not be connected",
}),
message: intl.formatMessage({
defaultMessage:
"We could not connect your accounts to give you access. Please contact us and we'll help you resolve this issue.",
}),
}
switch (error) {
case "unable_to_verify_employee_id":
return {
heading: intl.formatMessage({
defaultMessage: "You're not eligible for employee benefits",
}),
message: intl.formatMessage({
defaultMessage:
"This may be because your employment has not yet started, has ended, or you are a consultant. If you believe this is an error, please contact us for assistance.",
}),
}
case "employee_id_already_linked":
return {
heading: intl.formatMessage({
defaultMessage:
"Employee number already linked to another Scandic Friends membership.",
}),
message: intl.formatMessage({
defaultMessage:
"If you believe this is an error, please contact us for assistance.",
}),
}
case "missing_employee_id_profile":
case "missing_employee_id":
case "no_session":
return defaultErrorContent
default:
return defaultErrorContent
}
}

View File

@@ -1,139 +0,0 @@
"use client"
import Image from "next/image"
import { useState } from "react"
import { Checkbox as AriaCheckbox } from "react-aria-components"
import { useIntl } from "react-intl"
import { Button } from "@scandic-hotels/design-system/Button"
import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"
import ScandicLogoIcon from "@scandic-hotels/design-system/Icons/ScandicLogoIcon"
import { Typography } from "@scandic-hotels/design-system/Typography"
import { employeeBenefits } from "@/constants/routes/dtmc"
import ButtonLink from "@/components/ButtonLink"
import useLang from "@/hooks/useLang"
import styles from "./linkEmploymentPage.module.css"
export default function LinkEmploymentPage() {
const lang = useLang()
const intl = useIntl()
const [isChecked, setIsChecked] = useState(false)
const linkMyEmploymentText = intl.formatMessage({
defaultMessage: "Link my employment",
})
return (
<div className={styles.pageWrapper}>
<Image
src="/_static/img/Scandic_Computer_Coffee.png"
alt=""
fill
className={styles.backgroundImage}
priority
/>
<div className={styles.contentContainer}>
<nav className={styles.nav}>
<ButtonLink href={employeeBenefits[lang]} variant="Text">
<MaterialIcon
icon="chevron_left"
size={20}
className={styles.backArrow}
/>
<span className={styles.navBackText}>
{intl.formatMessage({
defaultMessage: "Go back",
})}
</span>
</ButtonLink>
<div className={styles.logoContainer}>
<ScandicLogoIcon
color="Icon/Interactive/Accent"
height="20px"
width="94px"
/>
</div>
</nav>
<main className={styles.mainContent}>
<div className={styles.card}>
<Typography variant="Title/Subtitle/lg">
<h1 className={styles.heading}>
{intl.formatMessage({
defaultMessage: "Link your employment to access benefits",
})}
</h1>
</Typography>
<div className={styles.formElements}>
<div className={styles.checkboxContainer}>
<AriaCheckbox
isSelected={isChecked}
onChange={setIsChecked}
className={styles.checkboxWrapper}
>
{({ isSelected: isAriaSelected }) => (
<>
<span className={styles.checkbox}>
{isAriaSelected && (
<MaterialIcon icon="check" color="Icon/Inverted" />
)}
</span>
<Typography variant="Body/Paragraph/mdRegular">
<span>
{intl.formatMessage({
defaultMessage: "I accept the terms and conditions",
})}
</span>
</Typography>
</>
)}
</AriaCheckbox>
<Typography variant="Body/Paragraph/mdRegular">
<p className={styles.termsTextFull}>
{intl.formatMessage(
{
defaultMessage:
"By accepting the {termsLink}, I agree to link my employment to access benefits. The connection will remain active during my employment or until I opt out by sending an email to Scandic's customer service.",
},
{
termsLink: (
// TODO: Update with actual URL for terms and conditions.
<a href={"#"} className={styles.link}>
{intl.formatMessage({
defaultMessage:
"Scandic Family Terms and Conditions",
})}
</a>
),
}
)}
</p>
</Typography>
</div>
{isChecked ? (
<ButtonLink
href={"#"} // TODO: Udpate with actual URL for linking employment.
>
{linkMyEmploymentText}
</ButtonLink>
) : (
<Button
variant="Primary"
typography="Body/Paragraph/mdRegular"
isDisabled
>
{linkMyEmploymentText}
</Button>
)}
</div>
</div>
</main>
</div>
</div>
)
}

View File

@@ -1 +1,20 @@
export { GET, POST } from "@/auth"
import { GET as DEFAULT_GET, POST as DEFAULT_POST } from "@/auth"
import { GET as DTMC_GET, POST as DTMC_POST } from "@/auth.dtmc"
import type { NextRequest } from "next/server"
export function GET(req: NextRequest) {
if (req.nextUrl.pathname.includes("microsoft-entra-id")) {
return DTMC_GET(req)
}
return DEFAULT_GET(req)
}
export function POST(req: NextRequest) {
if (req.nextUrl.pathname.includes("microsoft-entra-id")) {
return DTMC_POST(req)
}
return DEFAULT_POST(req)
}

View File

@@ -0,0 +1,106 @@
import { type NextRequest, NextResponse } from "next/server"
import { DTMC_SUCCESS_BANNER_KEY } from "@/constants/dtmc"
import { linkEmploymentError } from "@/constants/routes/dtmc"
import { overview } from "@/constants/routes/myPages"
import { internalServerError } from "@/server/errors/next"
import { getPublicURL } from "@/server/utils"
import { auth } from "@/auth"
import { auth as dtmcAuth } from "@/auth.dtmc"
import { getLang } from "@/i18n/serverContext"
import { isValidSession } from "@/utils/session"
async function linkEmployeeToUser(employeeId: string) {
try {
console.log(`[dtmc] Linking employee ID ${employeeId}`)
// TODO: Use the actual API once available. For now, return a mock success response.
return { success: true }
} catch (error) {
console.error("[dtmc] Error linking employee to user:", error)
throw error
}
}
/**
* This is the route that the NextAuth callback for Microsoft Entra ID provider
* will redirect too once it has created the session. Since it is its own cookie,
* here we can check both sessions, the Scandic Friends one and the Azure one.
*/
export async function GET(request: NextRequest) {
try {
const lang = await getLang()
const dtmcSession = await dtmcAuth()
const session = await auth()
const baseUrl = getPublicURL(request)
console.log("[dtmc] DTMC Callback handler - using baseUrl:", baseUrl)
if (!isValidSession(session)) {
console.error(
"[dtmc] DTMC Callback handler - No valid user session found"
)
const errorUrl = new URL(linkEmploymentError[lang], baseUrl)
errorUrl.searchParams.set("error", "no_session")
return NextResponse.redirect(errorUrl)
}
if (!isValidSession(dtmcSession)) {
console.error(
"[dtmc] DTMC Callback handler - No valid entra id session found"
)
const errorUrl = new URL(linkEmploymentError[lang], baseUrl)
errorUrl.searchParams.set("error", "no_entra_id_session")
return NextResponse.redirect(errorUrl)
}
const employeeId = dtmcSession.employeeId
console.log(
"[dtmc] DTMC Callback handler - Extracted employeeId:",
employeeId
)
if (!employeeId) {
console.error("[dtmc] DTMC Callback handler - No employeeId in session")
const errorUrl = new URL(linkEmploymentError[lang], baseUrl)
errorUrl.searchParams.set("error", "missing_employee_id")
return NextResponse.redirect(errorUrl)
}
console.log(
"[dtmc] DTMC Callback handler - Calling linkEmployeeToUser with ID:",
employeeId
)
const result = await linkEmployeeToUser(employeeId)
console.log(
"[dtmc] DTMC Callback handler - linkEmployeeToUser result:",
result
)
if (!result.success) {
console.error(
"[dtmc] DTMC Callback handler - Failed to verify employment"
)
const errorUrl = new URL(linkEmploymentError[lang], baseUrl)
errorUrl.searchParams.set("error", "unable_to_verify_employee_id")
return NextResponse.redirect(errorUrl)
}
console.log(
"[dtmc] DTMC Callback handler - Success! Employee linked with ID:",
employeeId
)
console.log("[dtmc] overview[lang]:", overview[lang])
const successUrl = new URL(overview[lang], baseUrl)
successUrl.searchParams.set(DTMC_SUCCESS_BANNER_KEY, "true")
console.log(
"[dtmc] DTMC Callback handler - Redirecting to success URL:",
successUrl.toString()
)
return NextResponse.redirect(successUrl)
} catch (error) {
console.error("[dtmc] DTMC Callback handler - Error in handler:", error)
return internalServerError()
}
}