43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import type { Route } from './+types/konviva'
|
|
|
|
import { redirect } from 'react-router'
|
|
|
|
import { userContext } from '@repo/auth/context'
|
|
import type { User } from '@repo/auth/auth'
|
|
|
|
import { cloudflareContext } from 'workers/app'
|
|
|
|
const konvivaApi = 'https://lms.saladeaula.digital'
|
|
|
|
export async function loader({ context }: Route.LoaderArgs) {
|
|
const cloudflare = context.get(cloudflareContext)
|
|
const user = context.get(userContext) as User
|
|
const secretKey = cloudflare.env.KONVIVA_SECRET_KEY
|
|
const token = await getToken(user.email, secretKey)
|
|
|
|
const url = new URL('/action/acessoExterno', konvivaApi)
|
|
url.search = new URLSearchParams(token).toString()
|
|
|
|
return redirect(url.toString())
|
|
}
|
|
|
|
async function getToken(
|
|
email: string,
|
|
secretKey: string
|
|
): Promise<Record<string, string>> {
|
|
const headers = new Headers({
|
|
Authorization: `KONVIVA ${secretKey}`,
|
|
'Content-Type': 'application/json'
|
|
})
|
|
const url = new URL(`/action/api/usuarios/token`, konvivaApi)
|
|
url.search = new URLSearchParams({ login: email }).toString()
|
|
|
|
const r = await fetch(url.toString(), { method: 'GET', headers })
|
|
|
|
if (!r.ok) {
|
|
throw new Error(await r.text())
|
|
}
|
|
|
|
return await r.json()
|
|
}
|