import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import { getUserByEmail, updateUser } from "../user/user.service"; import { createSession, deleteSession, getSession } from "./auth.service"; export async function authRoutes(fastify: FastifyInstance) { fastify.get( "/microsoft/token", {}, async (req: FastifyRequest, res: FastifyReply) => { try { const { token } = await fastify.microsoftOauth.getAccessTokenFromAuthorizationCodeFlow( req ); const user = (await fastify.microsoftOauth.userinfo(token)) as { givenname: string; familyname: string; email: string; picture: string; }; const userInDb = await getUserByEmail(user.email); if (userInDb == null) return res.code(401).send({ error: "not_allowed" }); await updateUser(userInDb.pid, { firstName: user.givenname, lastName: user.familyname, email: user.email, avatar: user.picture, }); const session = await createSession( userInDb.id, req.ip, req.headers["user-agent"] ); return res.code(201).send({ session_token: session.sid }); } catch (err) { //@ts-ignore if (err.data) { //@ts-ignore fastify.log.warn(err.data.payload); return res.code(400).send(); } else { return err; } } } ); fastify.delete("/logout", {}, async (req, res) => { if (!req.headers.authorization) return res.code(200).send(); const auth = req.headers.authorization.split(" ")[1]; await deleteSession(auth); return res.code(200).send(); }); }