ExpressJS JWT authentication

npm install dotenv jsonwebtoken bcrypt

 

register

const express = require('express');
const user = express.Router();
const primsaClient = require('@prisma/client');
const prisma = new primsaClient.PrismaClient();
const bcrypt = require('bcrypt');

user.post('/register', async (req, res, next) => {
    const { email, password } = req.body;

    if (!(email && password)) {
        res.sendStatus(400);
        return next();
    }

    const findUser = await prisma.user.findFirst({
        where: {
            email: email
        }
    });

    if (findUser != null) {
        res.sendStatus(409);
        return next();
    }

    let user = {};

    bcrypt.hash(password, 10, async (err, hash) => {
        console.log(hash);
        user = await primsa.user.create({
            data: {
                email: email,
                passwordHash: hash,
                lastLogin: null
            }
        });

    });
    // console.log(user);
    res.json(user);
});



module.exports = user;

 

auth

require('dotenv').config();
const express = require('express');
const auth = express.Router();
const jwt = require('jsonwebtoken');
const primsaClient = require('@prisma/client');
const prisma = new primsaClient.PrismaClient();
const bcrypt = require('bcrypt');



auth.post('/login', async (req, res, next) => {
    const { email, password } = req.body;

    if (!(email && password)) {
        res.sendStatus(400);
        return next();
    }

    const findUser = await prisma.user.findFirst({
        where: {
            email: email
        }
    });

    if (findUser == null) {
        res.sendStatus(404);
        return next();
    }

    bcrypt.compare(password, findUser.passwordHash, (err, result) => {
        if (result) {
            let token = jwt.sign({ email: email }, process.env.TOKEN_SECRET, {
                expiresIn: '1h'
            });

            res.json({
                token: token
            });
        } else {
            res.sendStatus(401);
            return next();
        }
    });

});

module.exports = auth;
创建时间:8/10/2022 3:55:06 PM 修改时间:8/10/2022 3:57:27 PM