Created
February 14, 2022 13:25
-
-
Save SnowyPainter/778aac6331a4887f54c9719b0ef066f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cookieParser = require('cookie-parser'); | |
const bodyParser = require('body-parser'); | |
const express = require('express'); | |
const jwt = require('jsonwebtoken'); | |
const app = express(); | |
app.use(cookieParser()); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
const config = { | |
secretKey : 'QIFHAONFOEPN' | |
} | |
app.post('/login', (req, res) => { | |
console.log(req.body) | |
const user = { | |
id: 1, | |
} | |
let token = jwt.sign({ user: user }); | |
res.send(token); | |
}) | |
app.post('/logout', (req, res) => { | |
res.cookie("auth-token", ""); | |
}) | |
app.get('/api', verifyToken, (req, res) => { | |
try { | |
jwt.verify(req.token, config.secretKey, (error, authData) => { | |
if (error) { | |
res.send("not logged in") | |
} | |
res.json({ | |
message: "post Created", | |
authData | |
}) | |
}) | |
} catch (error) { | |
res.send(error) | |
} | |
}) | |
function verifyToken(req, res, next) { | |
try { | |
req.token = req.cookies["auth-token"] | |
next() | |
else { | |
res.send("Not logged-in") | |
} | |
} | |
catch { | |
res.send("something went wrong") | |
} | |
} | |
app.listen(3000, () => { | |
console.log("server is runing") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment