Nodejs (express) simple user registration, login and authorization

Time:2020-10-29

preface:
New node auth folder, new server.js File, initialization folder NPM init – y
(git init)
1. Install express, mongoose and rest client
2. Turn on the server
const express = require('express)
const app = express()
//Connect to database
require('./modles/db')
//jwt
const jwt = require('jsonwebtoken')
app.use(express.json())

//Key
const SECRET = 'sajkFAjscbhsafchdsvjkks';
app.get('/api', async(req, res) => {
    const user = await User.find();
    res.send(user);
    // res.send('ok');
})
//Registration
app.post('/api/register', async(req, res) => {
    const user = await User.create({
        username: req.body.username,
        password: req.body.password
    })
    res.send(user);
    // console.log(req.body);
});
//Login
app.post('/api/login', async(req, res) => {
    const user = await User.findOne({ username: req.body.username });
    if (!user) {
        return res.status(422).send({
            Message: 'user name does not exist'
        })
    }
    //Verify password comparesync
    const isPasswordValid = require('bcryptjs').compareSync(req.body.password, user.password);
    if (!isPasswordValid) {
        return res.status(422).send({
            Message: 'password error'
        });
    }
    //Generating token
    const token = jwt.sign({
        id: String(user._id)
    }, SECRET)
    res.send({
            user,
            token
        })
        // res.send(isPasswordValid);
        // res.send(user);
});
//Middleware
const auth = async(req, res, next) => {
//Get token
    const raw = String(req.headers.authorization.split(' ').pop());
    //Analysis
    const { id } = jwt.verify(raw, SECRET);
    req.user = await User.findById(id);
    next()
}
//Personal information
app.get('/api/profile', auth, async(req, res) => {
    res.send(req.user);
})

app.listen(3000, () => {`
    console.log('listening port 3000!');
})

3. Connect to the database

/*ps:
var bcrypt = require('bcryptjs');
generate
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync("....", salt);
//Comparison
bcrypt.compareSync("....", hash); 
//In one step
var hash = bcrypt.hashSync('...', 8);
*/
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/database', {
    new useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true
})
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        //Uniqueness
        unique: true
    },
    password: {
        type: String,
        //Encryption bcrypt
        set(val) {
            return require('bcryptjs').hashSync(val, 10);
        }
    }
})
const User = mongoose.model('User', userSchema)

module.exports = {User}

4. New construction test.http (similar to postman)

@url=http://localhost:3001/api
@json= Content-Type: application/json
###
get {{url}}


###Registration
post {{url}}/register
{{json}}

{
    "username": "admin4",
    "password": "1234568"
}

###Login
post {{url}}/login
{{json}}

{
    "username": "admin2",
    "password": "1234568"
}

###Personal information
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZGZiYWI1MDc3OTU4MTA0MDkyMjU4ZiIsImlhdCI6MTU5MTc1NDYxNX0.bg2JDwigQ5jYg-nOdNUENjJS80y1KmZySjZDhXpvmTM