Use middleware to authenticate users

Closes #1
This commit is contained in:
SileNce5k 2025-01-26 06:45:16 +01:00
parent 7b35e1e2b5
commit 332ffc040d
Signed by: SileNce
GPG key ID: B0A142BB4291B204

View file

@ -18,6 +18,16 @@ app.use((req, res, next) => {
}) })
app.use((req, res, next) => {
const authenticatedUser = verifyAuthToken(req.cookies.auth_token);
if(authenticatedUser){
res.locals.user = getUser(authenticatedUser.user_id)
}
next()
})
const frontendPath = { const frontendPath = {
views: path.join(__dirname, "..", "frontend", "views"), views: path.join(__dirname, "..", "frontend", "views"),
public: path.join(__dirname, "..", "frontend", "public") public: path.join(__dirname, "..", "frontend", "public")
@ -86,13 +96,12 @@ function getUser(userid){
} }
app.get('/users/:id/settings', (req, res) => { app.get('/users/:id/settings', (req, res) => {
let authenticatedUser = verifyAuthToken(req.cookies.auth_token)
let userId = Number(req.params.id); let userId = Number(req.params.id);
if(authenticatedUser){ if(res.locals.user){
if(authenticatedUser.user_id === userId){ if(res.locals.user.user_id === userId){
res.render("user_settings", {id: userId}) res.render("user_settings", {id: userId})
}else { }else {
res.redirect(`/users/${authenticatedUser.user_id}/settings`) res.redirect(`/users/${res.locals.user.user_id}/settings`)
} }
}else { }else {
res.redirect("/") res.redirect("/")
@ -100,7 +109,7 @@ app.get('/users/:id/settings', (req, res) => {
}) })
app.get('/register', (req, res) => { app.get('/register', (req, res) => {
if(verifyAuthToken(req.cookies.auth_token)){ if(res.locals.user){
res.redirect("/"); res.redirect("/");
return; return;
} }
@ -109,11 +118,9 @@ app.get('/register', (req, res) => {
}) })
app.get('/', (req, res) => { app.get('/', (req, res) => {
const authenticatedUser = verifyAuthToken(req.cookies.auth_token); if(res.locals.user){
if(authenticatedUser){
const user = getUser(authenticatedUser.user_id)
const footer = ""; const footer = "";
res.render("dashboard", {user: user, footer: footer}) res.render("dashboard", {user: res.locals.user, footer: footer})
}else{ }else{
res.render("invalid_login") res.render("invalid_login")
} }