Javascript
This commit is contained in:
71
server/auth.js
Normal file
71
server/auth.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import dotenv from 'dotenv';
|
||||
import chalk from 'chalk';
|
||||
import jwt from 'jsonwebtoken'
|
||||
import argon2 from 'argon2'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
dotenv.config();
|
||||
|
||||
export default class AuthHandler {
|
||||
ips = new Map()
|
||||
#secret
|
||||
|
||||
constructor() {
|
||||
this.#secret = process.env.JWT_SECRET;
|
||||
}
|
||||
|
||||
isLoggedInUser(req, res) {
|
||||
const token = req.cookies.auth_token; // read cookie
|
||||
|
||||
if (!token) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
return true
|
||||
} catch (err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async login(req, res) {
|
||||
const { email, password } = req.body;
|
||||
let foundUser = global.db.get.userByEmail(email)
|
||||
if(!foundUser) {
|
||||
res.status(400).json({ error: 'Incorrect email.' });
|
||||
return;
|
||||
}
|
||||
const storedHash = foundUser.password
|
||||
const valid = await argon2.verify(storedHash, password);
|
||||
if (!valid) {
|
||||
res.status(400).json({ error: 'Incorrect password.' });
|
||||
} else {
|
||||
const payload = { id: foundUser.id };
|
||||
const secret = process.env.JWT_SECRET;
|
||||
const options = { expiresIn: "2h" };
|
||||
const token = jwt.sign(payload, secret, options);
|
||||
|
||||
res.cookie("auth_token", token, {
|
||||
httpOnly: true, // cannot be accessed by JS
|
||||
secure: process.env.ENV === "production", // only over HTTPS
|
||||
sameSite: "lax", // like SameSiteLaxMode
|
||||
maxAge: 2 * 60 * 60 * 1000, // 2 hours in milliseconds
|
||||
path: "/", // available on entire site
|
||||
domain: process.env.ENV === "production" ? "." + process.env.BASE_URL : undefined
|
||||
});
|
||||
|
||||
res.redirect("/")
|
||||
}
|
||||
}
|
||||
|
||||
logout(req, res) {
|
||||
res.cookie('auth_token', '', {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 0, // expire immediately
|
||||
path: '/',
|
||||
});
|
||||
|
||||
res.redirect("/")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user