1. jsonwebtoken
-- Cài đặt:
npm install jsonwebtoken
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const jwt = require('jsonwebtoken'); let data = {_id : 'duycode'}; //encode object data --> tạo ra chuỗi token: let token = jwt.sign(data,'kjKJK#XC&*ZCDS#', { expiresIn: 60 * 60 }); console.log(token) //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJkdXljb2RlIiwiaWF0IjoxNjExNzI5NjE3fQ.GSiTLZIqgUDyj-JdGZjo1lR72WBdajbNj96BxZAA3ms //decode chuỗi token --> tạo ra object data let decode = jwt.verify(token,'kjKJK#XC&*ZCDS#'); console.log(decode) //{ _id: 'duycode', iat: 1611730075, exp: 1611730105 } |
2. cookie-parser
-- Cài đặt:
npm install cookie-parser
2.1. Tại ./src/server.js
1 2 |
const cookieParser = require('cookie-parser'); app.use(cookieParser(@$123%@#XYZ)); |
2.2. Sử dụng
1 2 3 4 5 6 7 8 9 10 |
// Set cookie cho response, -> key: 'userID'; value: token res.cookie('userID', token, { signed: true, }); // Get cookie let token = req.signedCookies.userID; // Delete cookie res.clearCookie('userID'); |
3. Khai báo thêm biến của .env hoặc trên Heroku
SECRET_JWT=kjKJK#XC&*ZCDS#
SECRET_SIGNEDCOOKIES=@$123%@#XYZ
4. AccountController
-- Tại file: ./src/app/controllers/AccountController.js
-- Tạo chuỗi token với object là: {_id: account._id};
-- Lưu chuỗi token vào cookie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
const mongoDB = require('../../config/database/mongoDB'); const jwt = require('jsonwebtoken'); class AccountController { register = async (req, res, next) => { try { let newAccount = { Gmail: req.body.Gmail, Phone: req.body.Phone, Password: req.body.Password, Role: 'Manager', createdAt: Date.now(), updatedAt: Date.now(), removedAt: 0, }; let response = await mongoDB.getDB().collection('accounts').insertOne(newAccount); console.log('Tạo tài khoản mới thành công: ', response.ops); //Tạo token và lưu token vào cookie let token = jwt.sign({ _id: newAccount._id }, process.env.SECRET_JWT); res.cookie('accountID', token, { signed: true, }); res.json({ data: response.ops[0] }); } catch (error) { console.log(error); res.json({ error: error }); } }; login = async (req, res, next) => { try { let query = { Gmail: req.body.Gmail, Password: req.body.Password, }; let account = await mongoDB.getDB().collection('accounts').findOne(query); console.log('Đăng nhập thành công', account); //Tạo token và lưu token vào cookie let token = jwt.sign({ _id: account._id }, process.env.SECRET_JWT); res.cookie('accountID', token, { signed: true, }); res.json({ data: account }); } catch (error) { console.log(error); res.json({ error: error }); } }; logout = (req, res, next) => { //Xóa cookie res.clearCookie('accountID'); res.redirect('/'); }; } module.exports = new AccountController(); |