summaryrefslogtreecommitdiff
path: root/backend/src/controllers
diff options
context:
space:
mode:
authorArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
committerArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
commit655ec610fcce8dd7748f10772d520bdff4f7c78e (patch)
tree35b79f30d2cb5aea88cf76ce27f480da93cefd32 /backend/src/controllers
Basic setup & login
Diffstat (limited to 'backend/src/controllers')
-rw-r--r--backend/src/controllers/generateAdmin.ts48
-rw-r--r--backend/src/controllers/loginUser.ts65
2 files changed, 113 insertions, 0 deletions
diff --git a/backend/src/controllers/generateAdmin.ts b/backend/src/controllers/generateAdmin.ts
new file mode 100644
index 0000000..045fd2d
--- /dev/null
+++ b/backend/src/controllers/generateAdmin.ts
@@ -0,0 +1,48 @@
+import bcrypt from "bcrypt";
+import { Request, Response } from "express";
+import { QueryResult } from "pg";
+import db from "../database/postgres.js";
+import type { AdminCreationResult } from "../types/user.js";
+import { isPostgresError, PostgresErrorCodes } from "../utils/dbErrorCheck.js";
+
+/*
+ One-time function to generate an admin user with specific email & password in the DB
+ Reason: hash the password with bcrypt for future authentication
+*/
+async function generateAdmin(_req: Request, res: Response) {
+ const adminMail = "admin@test.com";
+ const adminPass = "test123";
+
+ try {
+ const hashedPassword = await bcrypt.hash(adminPass, 10);
+
+ const adminCreation: QueryResult<AdminCreationResult> = await db.query(
+ "INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id, email, created_at;",
+ [adminMail, hashedPassword]
+ );
+
+ return res.status(201).json({
+ message: "The admin was created successfully.",
+ admin: adminCreation.rows[0],
+ });
+ } catch (error) {
+ if (
+ isPostgresError(error) &&
+ error.code === PostgresErrorCodes.UNIQUE_VIOLATION
+ ) {
+ console.error("Error creating the admin: ", error);
+ return res.status(409).json({
+ message: "Admin already exists.",
+ error: error.message,
+ });
+ }
+
+ console.error("Error creating admin: ", error);
+ return res.status(500).json({
+ message: "Internal server error for admin creation.",
+ error,
+ });
+ }
+}
+
+export default generateAdmin;
diff --git a/backend/src/controllers/loginUser.ts b/backend/src/controllers/loginUser.ts
new file mode 100644
index 0000000..860bce2
--- /dev/null
+++ b/backend/src/controllers/loginUser.ts
@@ -0,0 +1,65 @@
+import bcrypt from "bcrypt";
+import { Request, Response } from "express";
+import jwt from "jsonwebtoken";
+import { QueryResult } from "pg";
+import db from "../database/postgres.js";
+import type { LoginRequest } from "../types/request.js";
+import type { AuthorizedUser, DatabaseUser } from "../types/user.js";
+
+async function loginUser(req: Request, res: Response) {
+ const { email, password } = req.body as LoginRequest;
+
+ if (!email || !password) {
+ return res.status(400).json({
+ message: "E-Mail und Passwort sind erforderlich.",
+ });
+ }
+
+ try {
+ // Get data for user with login email address
+ const queryResult: QueryResult<DatabaseUser> = await db.query(
+ "SELECT id, email, password_hash, created_at FROM users WHERE email = $1;",
+ [email]
+ );
+
+ const user = queryResult.rows[0];
+
+ if (!user) {
+ return res.status(401).json({ message: "Login Daten ungültig." });
+ }
+
+ // Check if password is correct
+ const isValidPassword = await bcrypt.compare(
+ password,
+ user.password_hash
+ );
+
+ if (!isValidPassword) {
+ return res.status(401).json({
+ message: "Das Passwort ist nicht korrekt.",
+ });
+ }
+
+ const userData: AuthorizedUser = {
+ id: user.id,
+ email: user.email,
+ createdAt: user.created_at,
+ };
+
+ // Create token for authentication
+ const token = jwt.sign(userData, process.env.JWT_SECRET!);
+
+ return res.status(200).json({
+ message: "Erfolgreiche Anmeldung.",
+ user: userData,
+ token,
+ });
+ } catch (error) {
+ console.error("Fehler beim Login: ", error);
+ return res
+ .status(500)
+ .json({ message: "Interner Serverfehler beim Login.", error });
+ }
+}
+
+export default loginUser;