JWT
1. Giới thiệu
2. Cài đặt app
2.1 Các công cụ sử dụng
Express
Dotenv
Mongoose
Bcrypt
JWT
2.1 Cài đặt API
Register : api/user/register
Register phải trải qua các bước sau: - Check Valid (Email, password, name, sdt) - Sử dụng @Happi/Joi - Check Exist Account - Mongoose DB - Hash password - Bcrypt - Create new Account - Mongoose DB
Login
Login cũng phải trải qua các bước sau: - Check Valid (Email, password) - Sử dụng @Happi/Joi - Check Exist Account - Mongoose DB (FindOne) - Check Hash password - Bcrypt - Save Information in header - JWT
Authentication (Xác thực)
Để xác thực một account cần: - Verify account - JWT - Take information from ID - Mongoose DB - Send back - Express
3. Code ví dụ
Cấu trúc thư mục
// Index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const apiRouter = require("./controller/api");
require("dotenv").config();
const bodyParser = require("body-parser");
//Connect to database
mongoose
.connect(process.env.URL_DATABASE)
.then(() => console.log("Database connected."))
.catch(() => console.log("Database error"));
//Req body handle
app.use(bodyParser.json());
//API handle
app.use("/api", apiRouter);
app.listen(3000, () => console.log("Server is listening on port 3000"));
// Use schema
const mongoose = require("mongoose");
const useSchema = new mongoose.Schema({
name: {
type: String,
require: true,
min: 6,
max: 255,
},
email: {
type: String,
require: true,
},
password: {
type: String,
require: true,
min: 6,
max: 255,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("User", useSchema);
// Api.js
const express = require("express");
const router = express.Router();
const User = require("../model/userSchema");
const { validateRegister, validateLogin } = require("../BLL/validate");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const jwt = require("jsonwebtoken");
const { auth } = require("../BLL/auth");
router.post("/register", async (req, res) => {
//Check valid
let validated = validateRegister(req.body);
if (validated.error != null)
return res.status(400).send(validated.error.details[0].message);
//Check Exist Account
const checkEmail = await User.findOne({ email: req.body.email });
if (checkEmail) return res.status(400).send("Email is already exist.");
//Hass Password
const salt = await bcrypt.genSalt(saltRounds);
const hashPassword = await bcrypt.hash(req.body.password, salt);
//Create Account
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashPassword,
});
try {
const saveUser = await user.save();
res.send(saveUser);
} catch (error) {
res.status(400).send(error);
}
});
router.post("/login", async (req, res) => {
//Check Valid
let validated = validateLogin(req.body);
if (validated.error != null)
return res.status(400).send(validated.error.details[0].message);
//Check Exist Account
const user = await User.findOne({ email: req.body.email });
if (!user) return res.status(400).send("Email wasn't resgistered.");
//Compare password
const validPass = await bcrypt.compare(req.body.password, user.password);
if (!validPass) return res.status(400).send("Invalid password.");
//Use JWT
const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
res.header("auth-token", token).send(token);
});
router.get("/post", auth, async (req, res) => {
const user = await User.findOne({ email: req.body.email });
res.send(user);
});
module.exports = router;
// Auth.js
const jwt = require("jsonwebtoken");
function auth(req, res, next) {
const token = req.header("auth-token");
if (!token) return res.status(401).send("Authentication fail");
try {
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified;
next();
} catch (error) {
return res.status(401).send("Invalid token");
}
}
module.exports.auth = auth;
// Validate.js
const Joi = require("@hapi/joi");
const validateRegister = (data) => {
const user = {
name: Joi.string().min(6).max(255).required(),
password: Joi.string().min(6).required(),
email: Joi.string().email().required(),
};
return Joi.validate(data, user);
};
const validateLogin = (data) => {
const user = {
password: Joi.string().min(6).required(),
email: Joi.string().email().required(),
};
return Joi.validate(data, user);
};
module.exports.validateLogin = validateLogin;
module.exports.validateRegister = validateRegister;
Last updated
Was this helpful?