generated from nhcarrigan/template
feat: initial prototype works
I can log in and create a book! Woo!
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { FastifyPluginAsync } from "fastify";
|
||||
import { AuthService } from "../../services/auth.service";
|
||||
import { AuthResponse } from "@library/shared-types";
|
||||
|
||||
const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
const authService = new AuthService(app);
|
||||
|
||||
/**
|
||||
* Discord OAuth callback.
|
||||
*/
|
||||
app.get("/callback", async (request, reply) => {
|
||||
try {
|
||||
const tokenResult = await app.oauth2Discord.getAccessTokenFromAuthorizationCodeFlow(
|
||||
request
|
||||
);
|
||||
|
||||
// Get user data from Discord API
|
||||
const discordResponse = await fetch("https://discord.com/api/users/@me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenResult.token.access_token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!discordResponse.ok) {
|
||||
throw new Error("Failed to fetch Discord user data");
|
||||
}
|
||||
|
||||
const userData = await discordResponse.json();
|
||||
|
||||
// Create or update user in database
|
||||
const user = await authService.createOrUpdateUserFromDiscord(userData);
|
||||
|
||||
// Generate JWT
|
||||
const jwt = await authService.generateToken(user);
|
||||
|
||||
// Set cookie and redirect to frontend
|
||||
reply
|
||||
.setCookie("auth-token", jwt, {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 7 * 24 * 60 * 60, // 7 days
|
||||
})
|
||||
.redirect("/"); // Redirect to root since API serves frontend
|
||||
} catch (error) {
|
||||
app.log.error({ err: error }, "Auth callback error");
|
||||
reply
|
||||
.code(401)
|
||||
.send({ error: "Authentication failed", details: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Get current user.
|
||||
*/
|
||||
app.get<{ Reply: AuthResponse | { error: string } }>(
|
||||
"/me",
|
||||
{
|
||||
preValidation: [app.authenticate],
|
||||
},
|
||||
async (request) => {
|
||||
const user = request.user as any;
|
||||
const token = await authService.generateToken(user);
|
||||
|
||||
return {
|
||||
user,
|
||||
accessToken: token,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Logout.
|
||||
*/
|
||||
app.post("/logout", async (request, reply) => {
|
||||
reply
|
||||
.clearCookie("auth-token", {
|
||||
path: "/",
|
||||
})
|
||||
.send({ message: "Logged out successfully" });
|
||||
});
|
||||
};
|
||||
|
||||
export default authRoutes;
|
||||
Reference in New Issue
Block a user