Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ S3_REGION="eu-north-1"
S3_BUCKET="device-images"
S3_ACCESS_KEY="rustfsadmin"
S3_SECRET_KEY="rustfsadmin123"

DISCOURSE_CONNECT_SECRET="iamverysecure"
8 changes: 4 additions & 4 deletions app/components/map/filter-visualization.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { X } from 'lucide-react'
import { Fragment, useEffect } from 'react'

Check warning on line 2 in app/components/map/filter-visualization.tsx

View workflow job for this annotation

GitHub Actions / ⬣ Lint

'useEffect' is defined but never used. Allowed unused vars must match /^ignored/u
import { useLoaderData, useNavigate } from 'react-router'
import { type loader } from '~/routes/explore'
import { DeviceExposureZodEnum, DeviceStatusZodEnum } from '~/schema/enum'
Expand All @@ -24,7 +24,7 @@
}

// Update the search params to remove invalid filters
const cleanSearchParams = () => {

Check warning on line 27 in app/components/map/filter-visualization.tsx

View workflow job for this annotation

GitHub Actions / ⬣ Lint

'cleanSearchParams' is assigned a value but never used. Allowed unused vars must match /^ignored/u
let modified = false
const newParams = new URLSearchParams(params)

Expand All @@ -50,10 +50,10 @@
}

// Clean search params when the component mounts
useEffect(() => {
cleanSearchParams()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// useEffect(() => {
// cleanSearchParams()
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [])
Comment on lines +53 to +56
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this might break existing functionality right?


// Group valid filters by key
const groupedFilters: { [key: string]: string[] } = {}
Expand Down
5 changes: 5 additions & 0 deletions app/lib/api-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ export const apiRoutes: { noauth: RouteInfo[]; auth: RouteInfo[] } = {
method: 'POST',
tosExempt: true
},
{
path: `discourse/sso`,
method: 'GET',
tosExempt: true,
}
],
auth: [
{
Expand Down
2 changes: 1 addition & 1 deletion app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import { type Route } from './+types/root'
import ErrorMessage from './components/error-message'
import { Toaster } from './components/ui/toaster'
import { getLocale, i18nCookie, i18nextMiddleware } from './middleware/i18next'
import { updateUserlocale } from './models/user.server'
import { tosUiMiddleware } from './middleware/tos-ui.server'
import { updateUserlocale } from './models/user.server'
import { getEnv } from './utils/env.server'
import { getUser } from './utils/session.server'

Expand Down
105 changes: 105 additions & 0 deletions app/routes/api.discourse.sso.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { createHmac, timingSafeEqual } from 'node:crypto'
import { redirect, type LoaderFunctionArgs } from 'react-router'
import invariant from 'tiny-invariant'
import { getUser } from '~/utils/session.server'

invariant(
process.env.DISCOURSE_CONNECT_SECRET,
'DISCOURSE_CONNECT_SECRET must be set',
)

const DISCOURSE_CONNECT_SECRET = process.env.DISCOURSE_CONNECT_SECRET

function signPayload(payload: string) {
return createHmac('sha256', DISCOURSE_CONNECT_SECRET).update(payload).digest('hex')
}

function safeEqualHex(a: string, b: string) {
try {
const ab = Buffer.from(a, 'hex')
const bb = Buffer.from(b, 'hex')
return ab.length === bb.length && timingSafeEqual(ab, bb)
} catch {
return false
}
}

function decodeDiscoursePayload(sso: string) {
const decoded = Buffer.from(sso, 'base64').toString('utf8')
return new URLSearchParams(decoded)
}

function encodeDiscoursePayload(params: URLSearchParams) {
return Buffer.from(params.toString(), 'utf8').toString('base64')
}

function buildAbsoluteLoginRedirect(request: Request) {
const url = new URL(request.url)
const redirectTo = `${url.pathname}${url.search}`

return `/explore/login?${new URLSearchParams({ redirectTo }).toString()}`
}


export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url)
const sso = url.searchParams.get('sso')
const sig = url.searchParams.get('sig')

if (!sso || !sig) {
throw new Response('Missing sso or sig', { status: 400 })
}

const expectedSig = signPayload(sso)
if (!safeEqualHex(sig, expectedSig)) {
throw new Response('Invalid DiscourseConnect signature', { status: 403 })
}

const incoming = decodeDiscoursePayload(sso)
const nonce = incoming.get('nonce')
const returnSsoUrl = incoming.get('return_sso_url')

if (!nonce || !returnSsoUrl) {
throw new Response('Missing nonce or return_sso_url', { status: 400 })
}

const user = await getUser(request)

if (!user) {
const loginRedirect = buildAbsoluteLoginRedirect(request)
throw redirect(loginRedirect)
}

if (!user.email) {
throw new Response('User has no email', { status: 400 })
}

const username =
user.name ??
`user_${user.id}`

const outgoing = new URLSearchParams()
outgoing.set('nonce', nonce)
outgoing.set('external_id', String(user.id))
outgoing.set('email', user.email)
outgoing.set('username', username)

if (user.name) {
outgoing.set('name', user.name)
}

if (!user.emailIsConfirmed) {
outgoing.set('require_activation', 'true')
}


const responsePayload = encodeDiscoursePayload(outgoing)
const responseSig = signPayload(responsePayload)

const redirectUrl = new URL(returnSsoUrl)
redirectUrl.searchParams.set('sso', responsePayload)
redirectUrl.searchParams.set('sig', responseSig)


throw redirect(redirectUrl.toString())
}
18 changes: 16 additions & 2 deletions app/routes/explore.login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
useActionData,
useNavigation,
useSearchParams,
useLoaderData,
} from 'react-router'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
Expand All @@ -31,9 +32,16 @@ import { safeRedirect } from '~/utils'
import { createUserSession, getUserId } from '~/utils/session.server'

export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url)
const userId = await getUserId(request)
if (userId) return redirect('/explore')
return {}
if (userId) {
const redirectTo = safeRedirect(url.searchParams.get('redirectTo'), '/explore')
return redirect(redirectTo)
}

return data({
redirectTo: safeRedirect(url.searchParams.get('redirectTo'), '/explore'),
})
}

export async function action({ request }: ActionFunctionArgs) {
Expand Down Expand Up @@ -106,6 +114,7 @@ export const meta: MetaFunction = () => {

export default function LoginPage() {
const [searchParams] = useSearchParams()
const loaderData = useLoaderData<typeof loader>()
const actionData = useActionData<typeof action>()
const identifierRef = React.useRef<HTMLInputElement>(null)
const passwordRef = React.useRef<HTMLInputElement>(null)
Expand Down Expand Up @@ -148,6 +157,11 @@ export default function LoginPage() {
</div>
)}
<Form method="post" className="space-y-6" noValidate>
<input
type="hidden"
name="redirectTo"
value={loaderData.redirectTo}
/>
<CardHeader className="space-y-1 text-center">
<CardTitle className="text-2xl font-bold">
{t('welcome_back')}
Expand Down
Loading