-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (76 loc) · 2.23 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import express from 'express'
import jwt from 'jsonwebtoken'
import cookieParser from 'cookie-parser'
import { PORT, SECRET_JWT_KEY } from './config.js'
import { UserRepository } from './user-respository.js'
import { UserSchema } from './schema/userSchema.js'
const app = express()
app.set('view engine', 'ejs')
app.use(express.json())
app.use(cookieParser())
app.use((req, res, next) => {
const token = req.cookies.access_token
req.session = { user: null }
try {
const data = jwt.verify(token, SECRET_JWT_KEY)
req.session.user = data
} catch (error) {
req.session.user = null
}
next()
})
app.post('/register', async (req, res) => {
const { username, password } = req.body
try {
UserSchema.parse({ username, password })
const id = await UserRepository.create({ username, password })
res.send({ id })
} catch (error) {
// Errores de zod
if (error.errors) {
return res.status(400).send({ error: error.errors })
}
// Errores generales
res.status(400).send({ error: error.message })
}
})
app.post('/login', async (req, res) => {
const { username, password } = req.body
try {
UserSchema.parse({ username, password })
const user = await UserRepository.login({ username, password })
const token = jwt.sign({ _id: user._id, username: user.username }, SECRET_JWT_KEY, { expiresIn: '1h' })
res
.cookie('access_token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 1000 * 60 * 60
})
.send(user)
} catch (error) {
// Errores de zod
if (error.errors) {
return res.status(400).send({ error: error.errors })
}
// Errores generales
res.status(400).send({ error: error.message })
}
})
app.post('/logout', (req, res) => {
res.clearCookie('access_token').json({ message: 'Sesión cerrada' })
})
app.get('/protected', (req, res) => {
const { user } = req.session
if (!user) {
return res.status(403).send({ error: 'Acceso denegado' })
}
res.render('protected', user)
})
app.get('/', (req, res) => {
const { user } = req.session
res.render('index', user)
})
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`)
})