Skip to content

Commit

Permalink
feat: add mobile login handler
Browse files Browse the repository at this point in the history
  • Loading branch information
vnugent committed Nov 9, 2024
1 parent 51375e5 commit e46f1cc
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 508 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@turf/line-to-polygon": "^6.5.0",
"@udecode/zustood": "^1.1.3",
"@vercel/edge": "^1.1.1",
"auth0": "^2.42.0",
"auth0": "^4.12.0",
"awesome-debounce-promise": "^2.1.0",
"axios": "^0.24.0",
"classnames": "^2.3.1",
Expand Down
63 changes: 63 additions & 0 deletions src/app/api/mobile/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server'
import * as Auth0 from 'auth0'

import { AUTH_CONFIG_SERVER } from '../../../../Config'

if (AUTH_CONFIG_SERVER == null) throw new Error('AUTH_CONFIG_SERVER not defined')

const mobileAuthSecret = process.env.MOBILE_AUTH_SECRET
if (mobileAuthSecret == null) {
console.warn('Mobile auth secret not found')
}

const { clientSecret, clientId, issuer } = AUTH_CONFIG_SERVER

// Set up Auth0 client
const auth = new Auth0.AuthenticationClient({
domain: issuer.replace('https://', ''),
clientId,
clientSecret
})

/**
* Mobile login handler
*/
export async function POST (request: NextRequest): Promise<any> {
const authHeader = request.headers.get('User-Agent')
if (mobileAuthSecret != null && authHeader !== mobileAuthSecret) {
return NextResponse.json({ message: 'Unauthorized', status: 401 })
}

let username, password: string
try {
const data = await request.json()
username = data.username
password = data.password

if (isNullOrEmpty(username) || isNullOrEmpty(password)) {
console.error('Empty username/password!')
throw new Error('Invalid payload')
}
} catch (error) {
return NextResponse.json({ error: 'Unexpected error', status: 400 })
}

let response: Auth0.JSONApiResponse<Auth0.TokenSet> | undefined
try {
response = await auth.oauth.passwordGrant({
username,
password,
scope: 'openid profile email offline_access',
audience: 'https://api.openbeta.io'
})

return NextResponse.json({ data: response.data })
} catch (error) {
console.error('#### Auth0 error ####', error)
return NextResponse.json({ error: 'Unexpected auth error', status: 403 })
}
}

function isNullOrEmpty (str: string | null | undefined): boolean {
return str?.trim() === ''
}
Loading

0 comments on commit e46f1cc

Please sign in to comment.