feat: auth

This commit is contained in:
2026-02-04 08:04:46 -08:00
parent 8f3aeb9391
commit e167a17bd9
12 changed files with 673 additions and 9 deletions
+86
View File
@@ -0,0 +1,86 @@
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);
/**
* Initiate Discord OAuth login.
*/
app.get("/login", async (request, reply) => {
const authUrl = app.oauth2Discord.generateAuthorizationUri({
scope: ["identify", "email"],
});
return reply.redirect(authUrl);
});
/**
* Discord OAuth callback.
*/
app.get("/callback", async (request, reply) => {
try {
const token = await app.oauth2Discord.getAccessTokenFromAuthorizationCodeFlow(
request
);
// Get user data from Discord
const userData = await app.oauth2Discord.userinfo(token.access_token);
// 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(process.env.FRONTEND_URL || "http://localhost:4200");
} catch (error) {
app.log.error(error);
reply
.code(401)
.send({ error: "Authentication failed" });
}
});
/**
* 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;
+109
View File
@@ -0,0 +1,109 @@
/**
* @copyright 2026 NHCarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { FastifyPluginAsync } from "fastify";
import { PrismaClient } from "../../../generated/prisma";
import { Game, GameStatus } from "@library/shared-types";
import { adminGuard } from "../../middleware/admin-guard";
const gamesRoutes: FastifyPluginAsync = async (app) => {
const prisma = new PrismaClient();
// Get all games (public route)
app.get<{ Reply: Game[] }>("/", async () => {
const games = await prisma.game.findMany({
orderBy: { updatedAt: "desc" },
});
return games.map((game) => ({
...game,
status: game.status.toLowerCase() as GameStatus,
}));
});
// Get single game (public route)
app.get<{ Params: { id: string }; Reply: Game | null }>(
"/:id",
async (request) => {
const { id } = request.params;
const game = await prisma.game.findUnique({
where: { id },
});
if (!game) return null;
return {
...game,
status: game.status.toLowerCase() as GameStatus,
};
}
);
// Create game (protected admin route)
app.post<{ Body: Omit<Game, "id" | "createdAt" | "updatedAt">; Reply: Game }>(
"/",
{
preValidation: [app.authenticate, adminGuard],
},
async (request, reply) => {
const game = await prisma.game.create({
data: {
...request.body,
status: request.body.status.toUpperCase() as any,
},
});
return {
...game,
status: game.status.toLowerCase() as GameStatus,
};
}
);
// Update game (protected admin route)
app.put<{
Params: { id: string };
Body: Partial<Omit<Game, "id" | "createdAt" | "updatedAt">>;
Reply: Game | null;
}>(
"/:id",
{
preValidation: [app.authenticate, adminGuard],
},
async (request, reply) => {
const { id } = request.params;
const updateData = { ...request.body };
if (updateData.status) {
updateData.status = updateData.status.toUpperCase() as any;
}
const game = await prisma.game.update({
where: { id },
data: updateData,
});
return {
...game,
status: game.status.toLowerCase() as GameStatus,
};
}
);
// Delete game (protected admin route)
app.delete<{ Params: { id: string }; Reply: { success: boolean } }>(
"/:id",
{
preValidation: [app.authenticate, adminGuard],
},
async (request, reply) => {
const { id } = request.params;
await prisma.game.delete({
where: { id },
});
return { success: true };
}
);
};
export default gamesRoutes;