feat: Implement the /user/me endpoint

This commit is contained in:
Alexander Polynomdivision
2018-09-29 14:23:09 +02:00
parent 2e93fc954d
commit 65070b1f5b
14 changed files with 410 additions and 139 deletions

View File

@@ -1,30 +1,45 @@
import { pbkdf2Sync } from "crypto";
import { pbkdf2Sync, randomBytes } from "crypto";
import { Db } from "mongodb";
import { IUser } from "shared/user";
export function isAuthenticated(token: string): Promise<boolean> {
return new Promise((res, rej) => {
// TODO
res(true);
});
export async function isAuthenticated(token: string, db: Db): Promise<boolean> {
// See if we can find a session with that token
const session = await db.collection("sessions").findOne({ token, });
return session !== null;
}
export function performLogin(username: string, password: string): Promise<IUser | {}> {
return new Promise((res, rej) => {
// Hash the password
// TODO: Fetch the salt
const salt = "";
const hash = pbkdf2Sync(password, salt, 50000, 512, "sha512").toString("hex");
// TODO: Look up the user, compare hashes and send the returned user
res({
username: "Polynom",
uid: "1",
showWelcome: true,
classId: "test",
score: 4,
sessionToken: "abc123",
});
export async function performLogin(username: string, password: string, db: Db): Promise<IUser> {
const user = await db.collection("users").findOne({
username,
});
// Hash the password
const hash = pbkdf2Sync(password, user.salt, 50000, 512, "sha512").toString("hex");
if (hash === user.hash) {
// Create a session
const sessionToken = randomBytes(20).toString("hex");
// Store the token
await db.collection("sessions").insertOne({
username: user.username,
token: sessionToken,
});
return {
username: user.username,
uid: user.uid,
showWelcome: user.showWelcome,
//@ts-ignore
classId: user.classId,
// TODO: Implement
score: 4,
sessionToken,
};
} else {
// It does not matter what we throw
throw new Error("LOL");
}
};

View File

@@ -6,18 +6,26 @@ export async function authRoute(req: Request, res: Response, next: () => void) {
const token = req.get("Token");
if (token) {
// Check if were authenticated
const auth = await isAuthenticated(token);
if (auth)
//@ts-ignore
const auth = await isAuthenticated(token, req.db);
if (auth) {
//@ts-ignore
req.token = token;
next();
else
} else {
res.send({
error: "401",
data: {},
error: "403",
data: {
msg: "Session Token not found!",
},
});
}
} else {
res.send({
error: "401",
data: {},
error: "403",
data: {
msg: "No Session Token specified",
},
});
}
};