Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require("express");
- const bodyParser = require("body-parser");
- const jsonwebtoken = require('jsonwebtoken');
- const jwt = require('express-jwt');
- const app = express();
- const secret = "topsecret"// should be in ENV
- // Middleware
- app.use(bodyParser.urlencoded({ extended: false }))
- // Public Route
- app.get('/', (req, res) => {
- res.json({ message: "Hey this route can be accessed by everyone!" })
- })
- // Check if the request ist authenticated
- app.get('/secure', jwt({ secret }), (req, res) => {
- res.json({
- message: "Only VIP can see this 😁",
- user: req.user
- });
- })
- app.post('/authenticate', (req, res, next) => {
- const { email, password } = req.body;
- if (email && password) {
- // replace with DB verification
- if (email === "florian@awesome.at" && password === "password") {
- // create JWT
- const payload = { email };
- // generate a new token which is signed with the secret and expires in 7 days
- jsonwebtoken.sign(payload, secret, { expiresIn: "7d" }, (err, token) => {
- if (err) next(err);
- res.json({
- message: "Awww yeah! Your JWT is ready!",
- token
- })
- });
- } else {
- res.status(403).json({ message: "Nope that was not right!" });
- }
- } else {
- res.status(422).json({ message: "WTF Dude??" });
- }
- })
- // Handle Unauthorized Error
- app.use((err, req, res, next) => {
- if (err.status !== 401) next(err)
- res.status(401).json(err.inner);
- });
- // Error Handler
- app.use((err, req, res, next) => {
- console.error(err);
- res.status(500).json({ message: 'Something broke!' });
- });
- app.listen(3000, () => console.log("Server running on port 3000"));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement