Fixed Login and Register user not returning, Fixed error upon logging/registering

This commit is contained in:
Lynixenn
2025-03-25 18:41:39 +01:00
parent 9e7039c72c
commit cfcfd4ba5e
2 changed files with 57 additions and 24 deletions

View File

@@ -55,10 +55,10 @@ type ApiResponse = {
// Docs Routes // Docs Routes
router router
.get("/", (ctx) => { .get("/", (ctx: any) => {
ctx.response.body = "For endpoints, use /api/{name}"; ctx.response.body = "For endpoints, use /api/{name}";
}) })
.get("/api", (ctx) => { .get("/api", (ctx: any) => {
ctx.response.body = "For API Documentation, visit /docs"; ctx.response.body = "For API Documentation, visit /docs";
}); });
@@ -82,8 +82,7 @@ router
.get("/api/auth/refresh", () => {}); // TODO .get("/api/auth/refresh", () => {}); // TODO
// -- User routes -- // // -- User routes -- //
router router.get("/api/users", api_getAllUsers);
.get("/api/users", api_getAllUsers);
// .get("/api/user/:id/info", api_user_getInfo); // .get("/api/user/:id/info", api_user_getInfo);
// -- Chat routes -- // // -- Chat routes -- //
@@ -176,12 +175,20 @@ async function api_register(ctx: Context): Promise<void> {
} = result; } = result;
// Claude 3-5 Sonnet was used for the first Date formatting // Claude 3-5 Sonnet was used for the first Date formatting
const account_created = `${Math.floor(Date.now() / 1000)}-${ const account_created = `${Math.floor(Date.now() / 1000)}-${
new Date().toLocaleDateString("en-GB").split("/").join("-") new Date()
.toLocaleDateString("en-GB")
.split("/")
.join("-")
}`; }`;
if ( if (
!username || !password || !userGroup || !displayname || !user_email || !username ||
!firstname || !surname !password ||
!userGroup ||
!displayname ||
!user_email ||
!firstname ||
!surname
) { ) {
helper_utils.errorResponse(ctx, 400, "Missing required fields"); helper_utils.errorResponse(ctx, 400, "Missing required fields");
return; return;
@@ -204,9 +211,20 @@ async function api_register(ctx: Context): Promise<void> {
account_created, account_created,
); );
const user = await db_utils.getUserByUsername(username);
const responseBody: any = {
success: true,
message: "Register successful",
};
if (user.user_id !== undefined) {
responseBody.userId = user.user_id;
}
helper_utils.sendResponse(ctx, { helper_utils.sendResponse(ctx, {
status: 200, status: 200,
body: `Registered under name: ${userId}`, body: responseBody,
}); });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@@ -232,20 +250,32 @@ async function api_login(ctx: Context): Promise<string> {
return "Error"; return "Error";
} }
// Get the stored salt for this user
const storedSalt = user.password_salt; const storedSalt = user.password_salt;
// Salt the provided password with the stored salt
const saltedPassword = `${password}${storedSalt}`; const saltedPassword = `${password}${storedSalt}`;
// Hash the salted password
const hash = await helper_utils.hashPassword(saltedPassword); const hash = await helper_utils.hashPassword(saltedPassword);
// Compare the phashed password with the stored hash // Compare the hashed password with the stored hash
if (user.password !== hash) { if (user.password !== hash) {
helper_utils.errorResponse(ctx, 401, "Invalid password"); helper_utils.errorResponse(ctx, 401, "Invalid password");
return "Error"; return "Error";
} }
helper_utils.sendResponse(ctx, { status: 200, body: "Success" }); // Return success with the user ID if it exists
const responseBody: any = {
success: true,
message: "Login successful",
};
// Only add userId if it exists
if (user.user_id !== undefined) {
responseBody.userId = user.user_id;
}
helper_utils.sendResponse(ctx, {
status: 200,
body: responseBody,
});
return "Success"; return "Success";
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@@ -255,10 +285,12 @@ async function api_login(ctx: Context): Promise<string> {
} }
// +++ APP ---------------------------------------------------------- // // +++ APP ---------------------------------------------------------- //
app.use(oakCors({ app.use(
oakCors({
origin: "*", origin: "*",
credentials: true, credentials: true,
})); }),
);
app.use(router.routes()); app.use(router.routes());
app.use(router.allowedMethods()); app.use(router.allowedMethods());

View File

@@ -7,8 +7,8 @@
*/ */
// +++ IMPORTS ------------------------------------------------------ // // +++ IMPORTS ------------------------------------------------------ //
import { DB } from "https://deno.land/x/sqlite@v3.9.1/mod.ts"; import { DB, Row } from "https://deno.land/x/sqlite@v3.9.1/mod.ts";
import { queryDatabase, mapAccountRow } from "./mod.ts"; import { mapAccountRow, queryDatabase } from "./mod.ts";
import { Accounts } from "../interfaces.ts"; import { Accounts } from "../interfaces.ts";
/** /**
@@ -28,8 +28,9 @@ function registerUser(
firstname: string, firstname: string,
surname: string, surname: string,
account_created: string, account_created: string,
): string { ): any {
const query_user_exists = `SELECT * FROM accounts WHERE user_username = '${user}'`; const query_user_exists =
`SELECT * FROM accounts WHERE displayname = '${user}'`;
if (!query_user_exists) { if (!query_user_exists) {
return "noUser"; return "noUser";
} }
@@ -67,8 +68,8 @@ function registerUser(
'[]' '[]'
)`; )`;
db.query(query_add_user); db.query(query_add_user);
let userId = db.query( const userId = db.query(
`SELECT user_id FROM accounts WHERE user_username = '${user}'`, `SELECT user_id FROM accounts WHERE displayname = '${user}'`,
); );
console.log(`New user: ${user}`); console.log(`New user: ${user}`);
@@ -99,4 +100,4 @@ async function getUserByUsername(db: DB, username: string): Promise<Accounts> {
return result[0]; return result[0];
} }
export { registerUser, getAllUsersFromDB, getUserByUsername }; export { getAllUsersFromDB, getUserByUsername, registerUser };