Skip to content

Commit

Permalink
fix: Admision trials
Browse files Browse the repository at this point in the history
  • Loading branch information
theodorklauritzen committed Nov 7, 2024
1 parent aa1822c commit 39012de
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 36 deletions.
5 changes: 3 additions & 2 deletions src/actions/admission/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import { createAdmissionTrial } from '@/services/admission/create'
import { createAdmissionTrialValidation } from '@/services/admission/validation'
import { Session } from '@/auth/Session'
import type { ActionReturn } from '@/actions/Types'
import type { Admission, AdmissionTrial } from '@prisma/client'
import type { Admission } from '@prisma/client'
import type { ExpandedAdmissionTrail } from '@/services/admission/Types'


export async function createAdmissionTrialAction(
admission: Admission,
userId: FormData | number
): Promise<ActionReturn<AdmissionTrial>> {
): Promise<ActionReturn<ExpandedAdmissionTrail>> {
const session = await Session.fromNextAuth()
const authRes = CreateAdmissionTrialAuther.dynamicFields({}).auth(session)

Expand Down
6 changes: 3 additions & 3 deletions src/app/_components/OmegaId/reader/OmegaIdReader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function OmegaIdReader({
debounceThreshold,
singleRead,
}: {
successCallback: (user: OmegaId, token: string) => Promise<{
successCallback: (user: number, token: string) => Promise<{
success: boolean,
text: string,
}>,
Expand Down Expand Up @@ -72,7 +72,7 @@ export default function OmegaIdReader({
return
}

const userId = parse.data.id
const userId = parse.data

if (userId === lastReadUserId && Date.now() - lastReadTime < (debounceThreshold ?? 5000)) {
lastReadTime = Date.now()
Expand All @@ -84,7 +84,7 @@ export default function OmegaIdReader({
text: '...',
})

const results = await successCallback(parse.data, token)
const results = await successCallback(userId, token.data)

if (results.success && (singleRead ?? false)) {
html5QrcodeScanner.clear()
Expand Down
14 changes: 6 additions & 8 deletions src/app/admin/admission/[admission]/registration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,17 @@ export default function RegisterAdmissiontrial({
<h4>Registrer med QR kode</h4>
<OmegaIdReader
publicKey={omegaIdPublicKey}
successCallback={async (user) => {
const results = await createAdmissionTrialAction(admission, user.id)
successCallback={async (userId) => {
const results = await createAdmissionTrialAction(admission, userId)

let msg = results.success ?
`${user.firstname} er registrert` :
`${results.data.user.firstname} ${results.data.user.lastname} er registrert` :
'Kunne ikke regisrere bruker grunnet en ukjent feil.'

if (!results.success && results.error) {
msg = `${user.firstname}: ${
results.error
.map(e => e.message)
.reduce((acc, val) => `${acc}\n${val}`, '')
}`
msg = results.error
.map(e => e.message)
.reduce((acc, val) => `${acc}\n${val}`, '')
}

return {
Expand Down
2 changes: 1 addition & 1 deletion src/app/admin/admission/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default async function AdmissionTrials() {
<ul>
{AdmissionsArray.map(trial =>
<li key={uuid()}>
<Link href={`admissiontrials/${trial}`}>{AdmissionDisplayNames[trial]}</Link>
<Link href={`admission/${trial}`}>{AdmissionDisplayNames[trial]}</Link>
</li>
)}
</ul>
Expand Down
34 changes: 14 additions & 20 deletions src/jwt/parseJWTClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { JWT_ISSUER } from '@/auth/ConfigVars'
import { createActionError } from '@/actions/error'
import type { OmegaJWTAudience } from '@/auth/Types'
import type { ActionReturn } from '@/actions/Types'
import type { OmegaId } from '@/services/omegaid/Types'

/**
* Parses a JSON Web Token (JWT) and verifies its signature using the provided public key.
Expand All @@ -16,11 +15,16 @@ import type { OmegaId } from '@/services/omegaid/Types'
* @returns A promise that resolves to an `ActionReturn` object containing the parsed JWT payload if the JWT is valid,
* or an error object if the JWT is invalid.
*/
export async function parseJWT(token: string, publicKey: string, timeOffset: number): Promise<ActionReturn<OmegaId>> {
export async function parseJWT(
token: string,
publicKey: string,
timeOffset: number,
audience: OmegaJWTAudience
): Promise<ActionReturn<number>> {
// TODO: This only works in safari and firefox :///

function invalidJWT(message?: string): ActionReturn<OmegaId> {
return createActionError('JWT INVALID', message || 'Ugyldig QR kode')
function invalidJWT(message?: string): ActionReturn<number> {
return createActionError('JWT INVALID', message || 'Invalid JWT')
}

if (timeOffset < 0) {
Expand All @@ -30,7 +34,7 @@ export async function parseJWT(token: string, publicKey: string, timeOffset: num

const tokenS = token.split('.')
if (tokenS.length !== 3) {
return invalidJWT('Ugyldig QR kode type')
return invalidJWT('Malformatted JWT')
}

const keyStripped = publicKey
Expand Down Expand Up @@ -68,35 +72,25 @@ export async function parseJWT(token: string, publicKey: string, timeOffset: num
try {
const payload = readJWTPayload(token)

if (!(
typeof payload.usrnm === 'string' &&
typeof payload.gn === 'string' &&
typeof payload.sn === 'string' &&
typeof payload.sub === 'number'
)) {
return invalidJWT('Invalid fields')
if (typeof payload.sub !== 'number') {
return invalidJWT('JWT is missing sub field')
}

if (new Date(payload.exp * 1000 + timeOffset) < new Date()) {
return invalidJWT('QR koden er utløpt')
return invalidJWT('JWT has expired')
}

if (payload.iss !== JWT_ISSUER) {
return invalidJWT('Invalid issuer')
}

if (payload.aud !== 'omegaid' satisfies OmegaJWTAudience) {
if (payload.aud !== audience) {
return invalidJWT('Invalid audience')
}

return {
success: true,
data: {
id: payload.sub,
username: payload.usrnm,
firstname: payload.gn,
lastname: payload.sn,
}
data: payload.sub
}
} catch {
return invalidJWT('An unexpected error occured')
Expand Down
7 changes: 7 additions & 0 deletions src/services/admission/Types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { AdmissionTrial } from '@prisma/client'
import type { UserFiltered } from '@/services/users/Types'


export type ExpandedAdmissionTrail = AdmissionTrial & {
user: UserFiltered
}
11 changes: 9 additions & 2 deletions src/services/admission/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import { readUserAdmissionTrials } from './read'
import { prismaCall } from '@/services/prismaCall'
import { updateUserOmegaMembershipGroup } from '@/services/groups/omegaMembershipGroups/update'
import prisma from '@/prisma'
import { Admission, type AdmissionTrial } from '@prisma/client'
import { userFilterSelection } from '@/services/users/ConfigVars'
import { Admission } from '@prisma/client'
import type { CreateAdmissionTrialType } from './validation'
import type { ExpandedAdmissionTrail } from './Types'

export async function createAdmissionTrial(
data: CreateAdmissionTrialType['Detailed']
): Promise<AdmissionTrial> {
): Promise<ExpandedAdmissionTrail> {
const parse = createAdmissionTrialValidation.detailedValidate(data)

const results = await prismaCall(() => prisma.admissionTrial.create({
Expand All @@ -25,6 +27,11 @@ export async function createAdmissionTrial(
},
},
admission: parse.admission,
},
include: {
user: {
select: userFilterSelection
}
}
}))

Expand Down

0 comments on commit 39012de

Please sign in to comment.