Refactor & unit tests
This commit is contained in:
32
src/endpoints/auth.ts
Normal file
32
src/endpoints/auth.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import {BunRequest as Request} from "bun";
|
||||
import {orm} from "../orm/orm.ts";
|
||||
import jwt from "jsonwebtoken";
|
||||
import {UnwrappedRequest} from "../utilities/guard";
|
||||
import {ErrorResponse} from "../utilities/responseHelper";
|
||||
import {Claims} from "../orm/claims";
|
||||
import {UnauthorizedError} from "../utilities/errors";
|
||||
|
||||
async function login(request: UnwrappedRequest): Promise<Response> {
|
||||
try {
|
||||
const requestBody = request.json;
|
||||
console.log(`/api/auth/login: username=${requestBody.username}`);
|
||||
const claims: Claims | null = await orm.users.verify(requestBody.username, requestBody.password);
|
||||
console.log(claims);
|
||||
if (claims) {
|
||||
const token = jwt.sign({...claims}, process.env.JWT_SECRET_KEY as string, {expiresIn: "24h"});
|
||||
return Response.json({token: token, claims: claims}, {status: 200});
|
||||
}
|
||||
|
||||
throw new UnauthorizedError('Invalid credentials');
|
||||
} catch (error: any) {
|
||||
return new ErrorResponse(error as Error);
|
||||
}
|
||||
}
|
||||
async function test(request: UnwrappedRequest) {
|
||||
return Response.json(request.claims, {status: 200});
|
||||
}
|
||||
|
||||
export default {
|
||||
login,
|
||||
test
|
||||
};
|
||||
Reference in New Issue
Block a user