LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 1
MC TIÊU:
Kết thúc bài thực hành này bạn có khả năng
Hiểu và cài đặt Authentication
Đăng ký, đăng nhập và mã hoá password
Authentication
Validation
PHN I
Bài 1 (3 điểm)
Viết RESTFUL API thực hiện đăng ký thành viên
Bước 1: Tạo model user
const Sequelize =
require
require
require
requirerequire('sequelize' ;)
const sequelize =
require
require
require
requirerequire('../util/database' ;)
const User = sequelize.
de
de
de
dede
fine
fine
fine
finefine('tblUsers', {
id: {
type
type
type
typetype: Sequelize.
INTEGER
INTEGER
INTEGER
INTEGERINTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
email: {
type
type
type
typetype: Sequelize.
STRIN
STRIN
STRIN
STRINSTRIN
G
G
G
GG,
required: true
},
password: {
type
type
type
typetype: Sequelize.
STRIN
STRIN
STRIN
STRINSTRIN
G
G
G
GG,
required: true
},
typeUser: {
type
type
type
typetype: Sequelize.
INTEGER
INTEGER
INTEGER
INTEGERINTEGER,
required: true
}
},
{ timestamps: false }
LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 2
);
module exports User. = ;
Bước Xây dựng controller thực hiện thêm user
onst User =
require
require
require
requirerequire('../models/user');
const bcrypt =
require
require
require
requirerequire('bcryptjs');
const jwt =
require
require
require
requirerequire("jsonwebtoken");
exports. =
createUser
createUser
createUser
createUsercreateUser (req, res, next) => {
const email req = .body.email;
const password req = . .body password;
const confirmPassword = req. .body confirmPassword;
const typeUser req body typeUser = . . ;
console.
l
l
l
ll
og
og
og
ogog(email);
User.
find
find
find
findfind
One
One
One
OneOne({where: { email: email }})
.
then
then
then
thenthen(user => {
( if user) {
console.
log
log
log
loglog(user email. );
return res.
statu
statu
statu
statustatu
s
s
s
ss
json
json
json
jsonjson(400). ({message:"Email da ton tai"});
}
return bcrypt password.
hash
hash
hash
hashhash( , ; 12)
) }
.
then
then
then
thenthen(hashedPassword=>{
const user = new
User
User
User
UserUser({ email email password: , : hashedPassword typeUser typeUser, : } ;)
return user.
save
save
save
savesave();
})
.
then
then
then
thenthen(user => {
res.
status
status
status
statusstatus(201).
json
json
json
jsonjson({
message: 'Thêm thành công thành viên!',
user: user
});
) }
.
catch
catch
catch
catchcatch(err res => .
status
status
status
statusstatus
json
json
json
jsonjson(400). (err))
};
Bước 3: Thực hiện route
const express =
require
require
require
requirerequire(' ' ;express )
const userController =
re
re
re
rere
quire
quire
quire
quirequire('../controllers/auth' ;)
const router express = .
Rou
Rou
Rou
RouRou
ter
ter
ter
terter();
// POST /blog/post
router.
post
post
post
postpost('/register', userController createUser. );
router.
post
post
post
postpost('/login/', userController login. );
LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 3
module exports router. = ;
Bước 4: Test API với Postman
Bài 2 (2 điểm)
Viết REST API xử lý đăng nhập và trả về token
Bước 1: Viết API
exports.
login
login
login
loginlogin = (req, res, next) => {
const email req = .body.email;
const password req = . .body password;
User.
find
find
find
findfind
One
One
One
OneOne({where: { email: email }})
.
then
then
then
thenthen(user => {
(if !user) {
return res.
statu
statu
statu
statustatu
s
s
s
ss
json
json
json
jsonjson(400). ({message:"Email khong ton tai"});
}
return
Promise
Promise
Promise
PromisePromise.
all
all
all
allall
compare
compare
compare
comparecompare([bcrypt. (password user password user, . ), ]);
) }
.
then
then
then
thenthen(result=>{
const isMatch result= [0];
const user=result[1];
if(!isMatch) return res.
status
status
status
statusstatus
json
json
json
jsonjson( )400 . ({message:"Password khong khop"})
const payload={
email user: . ,email
typeUser user typeUser: .
}
console.
log
log
log
loglog(payload);
return jwt.
sign
sign
sign
signsign(payload,"FptPolyTechnic",{expiresIn:3600})
})
.
then
then
then
thenthen(token=>{
console.
log
log
log
loglog( )token ;
res. .
status
status
status
statusstatus( )200
j
j
j
jj
son
son
son
sonson({message:"Login thanh cong",token})
})
.
catch
catch
catch
catchcatch(err res => .
status
status
status
statusstatus
json
json
json
jsonjson(400). (err))
};
Bước 2: Test với phương thức với postman
LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 4
PHN II
Bài 3 (2 điểm)
Xây RESTFUL API Authenticate dựng
Bước 1: Tạo middleWare authen
Bước 2: sử dụng middleware trên cho
router userController testAuth. '
get
get
get
getget( /private/',
authenticate
authenticate
authenticate
authenticateauthenticate, . );
Bước 3: Test với postman
LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 5
Bài 4 (2 điểm)
Xây dựng middleware kiểm tra tính hợp lệ dữ liệu nhập vào khi thực hiện đăng ký
user.
S dng validate trong route
// POST /blog/post
router.
post
post
post
postpost('/register',
checkInput
checkInput
checkInput
checkInputcheckInput, userController createUser. );
router.
post
post
post
postpost('/login/', userController login. );
router. ' ;
get
get
get
getget( /private/',
authenticate
authenticate
authenticate
authenticateauthenticate, userController.testAuth)
Bài 5 (1 điểm)
Test REST API: sinh viên thực hiện gọi tất cả các API đã thực hiện ở bài 3,4 với
front end.
LAB 7
WEB503 - NODEJS & RESFUL WEB SERVICE RANG T 6
*** Y u c u n p b i:
SV n n file ( ) bao g m c c y u c c hi hoc share th m c google drive á ê u đã th n
trên, n ng thp LMS đú i gian quy đnh ca ging viên. KH NG N P B I COI NH
KH NG C M. ĐI
---Hết---

Preview text:

LAB 7 MỤC TIÊU:
Kết thúc bài thực hành này bạn có khả năng
✓ Hiểu và cài đặt Authentication
✓ Đăng ký, đăng nhập và mã hoá password ✓ Authentication ✓ Validation PHẦN I Bài 1 (3 điểm)
Viết RESTFUL API thực hiện đăng ký thành viên Bước 1: Tạo model user const Sequelize = re r q e u q i u r i e r ('sequelize'); const sequelize = re r q e u q i u r i e r ('../util/database'); const User = sequelize.de d fi f n i e n ('tblUsers', { id: { ty t p y e p : Sequelize.IN I T N E T G E E G R E , autoIncrement: true, allowNull: false, primaryKey: true }, email: { ty t p y e p : Sequelize.ST S R T I R N I G, required: true }, password: { ty t p y e p : Sequelize.ST S R T I R N I G, required: true }, typeUser: { ty t p y e p : Sequelize.IN I T N E T G E E G R E , required: true } }, { timestamps: false }
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 1 LAB 7 ); module.exports = User; Bước
Xây dựng controller thực hiện thêm user onst User = re r q e u q i u r i e r ('../models/user'); const bcrypt = re r q e u q i u r i e r ('bcryptjs'); const jwt = re r q e u q i u r i e r ("jsonwebtoken"); exports.cr c e r a e t a e t U e s U e s r e = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;
const confirmPassword = req.bod . y confirmPassword;
const typeUser = req.body.typeUser; console.log o (email); User.fi f n i d n On O e n ({where: { email: email }}) .th t e h n e (user = > { i f (user) { console.lo l g o (user.email); return res.st s a t t a u t s(400).js j o s n
o ({message:"Email da ton tai"}); } return bcrypt.ha h s a h s (password, 12); }) .th t e h n e (hashedPassword=>{ const user = new Us U e s r
e ({ email: email, password: hashedPassword,typeUser:typeUser }); return user.sa s v a e v (); }) .th t e h n e (user = > { res.st s a t t a u t s u (201).js j o s n o ({
message: 'Thêm thành công thành viên!', user: user }); }) .ca c t a c t h c (err => res.st s a t t a u t s u (400).js j o s n o (err)) }; Bước 3: Thực hiện route
const express = require('express'); const userController = re r qu q i u r i e r ('../controllers/auth'); const router = express.Ro R u o te t r e (); // POST /blog/post router.po p s o t
s ('/register', userController.createUser); router.po p s o t
s ('/login/', userController.login);
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 2 LAB 7 module.exports = router;
Bước 4: Test API với Postman Bài 2 (2 điểm)
Viết REST API xử lý đăng nhập và trả về token Bước 1: Viết API exports.lo l g o i g n i = (req, res, next) = > {
const email = req.body.email;
const password = req.body.password; User.fi f n i d n On O e n ({where: { email: email }}) .th t e h n e (user = > { i f (!user) { return res.st s a t t a u t s(400).js j o s n
o ({message:"Email khong ton tai"}); } return Pr P o r m o i m s i e s .al a ll([bcrypt.co c m o p m a p r a e
r (password, user.password),user]); }) .th t e h n e (result=>{ const isMatch=result[0]; const user=result[1]; if(!isMatch) return res.st s a t t a u t s u (40 ) 0 .js j o s n
o ({message:"Password khong khop"}) const payload={ email:user.email, typeUser:user.typeUser } console.lo l g o (payload); return jwt.si s g i n
g (payload,"FptPolyTechnic",{expiresIn:3600}) }) .th t e h n e (token=>{ console.lo l g o (token); res.st s a t t a u t s u (20 ) 0 .jso s n
o ({message:"Login thanh cong",token}) }) .ca c t a c t h c (err => res.st s a t t a u t s u (400).js j o s n o (err)) };
Bước 2: Test với phương thức với postman
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 3 LAB 7 PHẦN II Bài 3 (2 điểm)
Xây dựng RESTFUL API Authenticate
Bước 1: Tạo middleWare authen
Bước 2: sử dụng middleware trên cho router.ge g t
e ('/private/',authenticate, userController.testAuth); Bước 3: Test với postman
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 4 LAB 7 Bài 4 (2 điểm)
Xây dựng middleware kiểm tra tính hợp lệ dữ liệu nhập vào khi thực hiện đăng ký user. •
Sử dụng validate trong route // POST /blog/post router.po p s o t s ('/register',ch c e h c e k c I k n I p n u p t
u , userController.createUser); router.po p s o t
s ('/login/', userController.login); router.ge g t
e ('/private/',authenticate, userController.testAuth); Bài 5 (1 điểm)
Test REST API: sinh viên thực hiện gọi tất cả các API đã thực hiện ở bài 3,4 với front end.
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 5 LAB 7
*** Yu cu np bi:
SV nn file (hoc share th mc google drive) bao gm các yêu cu đã thực hiện
trên, np LMS đúng thi gian quy đnh ca giảng viên. KHNG NP BI COI NH KHNG C ĐIM. ---Hết---
WEB503 - NODEJS & RESFUL WEB SERVICE TRANG 6