feat(lst): added in basic authentication
This commit is contained in:
45
packages/lst-auth/routes/login.ts
Normal file
45
packages/lst-auth/routes/login.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import {Hono} from "hono";
|
||||
import {setCookie, getCookie, deleteCookie} from "hono/cookie";
|
||||
import {sign, verify} from "jsonwebtoken";
|
||||
|
||||
const JWT_SECRET = "your-secret-key";
|
||||
|
||||
const fakeUsers = [
|
||||
{id: 1, username: "admin", password: "password123"},
|
||||
{id: 2, username: "user", password: "password123"},
|
||||
{id: 3, username: "user2", password: "password123"},
|
||||
];
|
||||
export const authLogin = new Hono().get("/", async (c) => {
|
||||
// lets get the username and password to check everything
|
||||
const {username, password} = await c.req.json();
|
||||
let user = null;
|
||||
// make sure we go a username and password
|
||||
if (!username || !password) {
|
||||
return c.json({error: "Username and password required"}, 400);
|
||||
}
|
||||
|
||||
// check the user exist in our db
|
||||
if (!fakeUsers.includes(username && password)) {
|
||||
return c.json({error: "Invalid username or password"}, 400);
|
||||
}
|
||||
|
||||
user = fakeUsers.find((u) => u.username === username && u.password === password);
|
||||
|
||||
// create the token
|
||||
|
||||
const token = sign({userId: user?.id}, JWT_SECRET, {expiresIn: "1h"});
|
||||
|
||||
setCookie(c, "auth_token", token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
maxAge: 3600, //parseInt(process.env.JWT_EXPIRES_IN) * 60 * 1000 || 3600, // expires in 1 hour is not set in env
|
||||
path: "/",
|
||||
sameSite: "strict",
|
||||
});
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
message: "Login successful",
|
||||
user: {id: user?.id, username: user?.username, token: token},
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user