This commit is contained in:
2024-05-25 01:17:39 +02:00
parent a7f24f6229
commit 8c56a9421e
27 changed files with 467 additions and 165 deletions
+28
View File
@@ -0,0 +1,28 @@
type APIErrorMessage = {
status: number,
responseText: string
}
class APIError extends Error{
declare info:APIErrorMessage
constructor(message:APIErrorMessage) {
super(JSON.stringify(message))
this.info = message;
this.name = "AuthError"; // (different names for different built-in error classes)
}
}
const attemptAPIAction = async (action:Function,request:Request) => {
try {
return await action(request);
}
catch (e) {
if (e instanceof APIError) {
return new Response(e.info.responseText, { status: e.info.status });
}
else {
throw e;
}
}
}
export { APIError, attemptAPIAction }
+34
View File
@@ -0,0 +1,34 @@
// import { MUser } from "@/model/sequelize/User";
// import { MAuth } from "@/model/sequelize/Auth";
import { validatePassword } from "@/util/Auth";
import { APIError } from "@/util/api/error";
import { User } from "@/model/User";
export function parseBasicAuth(authb64:string):UserAuth
{
const authString:string = Buffer.from(authb64.split(" ")[1] as any, "base64").toString("utf8");
var userAuth:UserAuth = {
username:authString.split(":")[0] as any,
password:authString.split(":")[1] as any
};
return userAuth
}
export type UserAuth = {
username: string,
password: string
}
export async function getAssociatedUser(auth:UserAuth)
{
let foundUser = await User.findOne({ attributes: {include: ['password']}, where: {username: auth.username} });
if (!foundUser)
throw new APIError({status: 401, responseText:"Unauthorized: Invalid Username"});
if (!(await validatePassword(auth.password, foundUser.password)))
throw new APIError({status: 401, responseText:"Unauthorized: Invalid Password"});
return foundUser;
}