Commit 3b65c370 authored by chinguyen's avatar chinguyen

jwt

parent 7e97eab1
......@@ -32,13 +32,18 @@
]
},
"dependencies": {
"bcrypt": "^5.0.1",
"body-parser": "1.19.0",
"cors": "2.8.5",
"cross-env": "7.0.0",
"express": "4.17.1",
"express-boom": "3.0.0",
"jsonwebtoken": "^8.5.1",
"kafka-node": "^5.0.0",
"morgan": "1.9.1",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"pg": "^8.5.1",
"pg-hstore": "^2.3.3",
"sequelize": "^6.5.0",
......
import * as uuid from 'uuid'
import { AppUser } from './../sqlz/models/appuser'
import { Language } from '../sqlz/models/language'
import * as uuid from 'uuid';
import { AppUser } from './../sqlz/models/appuser';
import { Language } from '../sqlz/models/language';
import * as passport from 'passport';
import * as jwt from 'jsonwebtoken'
import { Json } from 'sequelize/types/lib/utils';
export function create(appUser: any): Promise<any> {
return Language.findOne({
where: { name: 'fr' }
})
.then(language => {
return AppUser
.create({
id: uuid.v1(),
email: appUser.email,
pwd: appUser.pwd,
languageId: language.get('id')
})
})
}
export function findAll(): Promise<any> {
......@@ -30,6 +29,16 @@ export function login(appUser: any): Promise<any> {
email: appUser.email,
pwd: appUser.pwd
},
include: [Language]
})
}
export function authenticate(appuser: any): Promise<any> {
return AppUser.findOne({
where: {
email: appuser.email,
pwd: appuser.pwd
}
})
}
// import passport from "passport";
// import passportLocal from "passport-local";
// // import passportApiKey from "passport-headerapikey";
// import passportJwt from "passport-jwt";
// import { AppUser } from './../sqlz/models/appuser';
// const LocalStrategy = passportLocal.Strategy;
// const JwtStrategy = passportJwt.Strategy;
// const ExtractJwt = passportJwt.ExtractJwt;
// passport.use(new LocalStrategy({ usernameField: "email" }, (email, password, done) => {
// // let obj = AppUser.findOne({
// // where: {email: email.toLowerCase()}
// // });
// // if (obj !== null){
// // return done(undefined, false, { message: 'email ${email} not found.' });
// // }
// AppUser.findOneOne({ username: username.toLowerCase() }, (err, user: any) => {
// if (err) { return done(err); }
// if (!user) {
// return done(undefined, false, { message: `username ${username} not found.` });
// }
// user.comparePassword(password, (err: Error, isMatch: boolean) => {
// if (err) { return done(err); }
// if (isMatch) {
// return done(undefined, user);
// }
// return done(undefined, false, { message: "Invalid username or password." });
// });
// });
// }));
\ No newline at end of file
import { Request, Response } from 'express'
import { AppUserDao } from '../../dao/_index'
import * as jwt from 'jsonwebtoken'
const secretKey = 'qwertyuiop123456';
export function create(req: Request, res: Response) {
req.checkBody('pwd', 'Password is required').notEmpty()
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'A valid email is required').isEmail()
req.getValidationResult()
.then(function(result) {
if (result.isEmpty()) {
return AppUserDao.create(req.body)
.then(appuser => res.status(201).send(appuser))
.catch(error => res.boom.badRequest(error))
} else {
res.boom.badRequest('Validation errors', result.mapped())
}
})
}
export function login(req: Request, res: Response) {
req.checkBody('pwd', 'Password is required').notEmpty()
req.checkBody('email', 'Email is required').notEmpty()
req.checkBody('email', 'A valid email is required').isEmail()
req.getValidationResult()
.then(function(result) {
if (result.isEmpty()) {
return AppUserDao.login(req.body)
} else {
res.boom.badRequest('Validation errors', result.mapped())
}
})
.then(appuser => res.status(200).send(appuser))
.catch(error => res.boom.badRequest(error))
}
export function authenticateJWT(req: Request, res: Response) {
console.log("--------------------authentication----------------")
return AppUserDao.authenticate(req.body).then(function(appuser) {
if (appuser !== null) {
let token = jwt.sign({
email: req.body.email
}, secretKey)
//res.set('Set-Cookie','Bearer ' + token);
//let temp = 'Bearer ' + token;
res.cookie(
'access-token', 'Bearer ' + token,
{
domain:'.chinguyen-test.com.vn',
path: '/hello',
expires: new Date(Date.now() + 4 * 3600000),
secure: true,
httpOnly: true
})
//console.log(res.headers);
//res.send(token);
res.send("login success")
}
res.send("Invalid username or password.")
})
}
export function verifyToken(req: Request, res: Response): Promise<any> {
console.log("babbbaaabb: ",req.headers.authorization);
let authenticateToken = String(req.headers.authorization);
console.log(authenticateToken);
if (authenticateToken === "") {
// ERROR MESSAGES SHOULD BE MORE VERBOSE IN DEV AND MORE OBSCURE ON PROD
res.send({ status: "AUTH_ERROR", data: "INVALID_DATA" });
return;
}
if (authenticateToken.startsWith("Bearer ") === false){
res.send({ status: "AUTH_ERROR", data: "INVALID_FORMAT" });
return;
}
const token = authenticateToken.replace("Bearer ", "");
let decoded = jwt.verify(token,secretKey);
return res.send(JSON.stringify(decoded));
}
......@@ -9,20 +9,21 @@ let clientOpts = {
requestTimeout: 30000
};
// Create Producer
let MessageProducer = kafka.Producer,
aaClient = new kafka.KafkaClient(clientOpts),
messageProducer = new MessageProducer(aaClient,{requireAcks: 1})
// let MessageProducer = kafka.Producer,
// aaClient = new kafka.KafkaClient(clientOpts),
// messageProducer = new MessageProducer(aaClient,{requireAcks: 1})
messageProducer.on('ready', function () {
setMessageProducer(messageProducer);
});
// messageProducer.on('ready', function () {
// setMessageProducer(messageProducer);
// });
export function getMessageProducer(): kafka.Producer {
return messageProducer;
//return messageProducer;
return
}
export function setMessageProducer(producerObj: kafka.Producer): void {
messageProducer = producerObj;
}
// export function setMessageProducer(producerObj: kafka.Producer): void {
// messageProducer = producerObj;
// }
///
......@@ -5,6 +5,6 @@ export function routes(app: Express) {
app.get('/api/appUsers', AppUserController.AppUserGet.list)
app.post('/api/appUsers', AppUserController.AppUserPost.create)
app.post('/api/appUsers/login', AppUserController.AppUserPost.login)
app.post('/api/appUsers/login' , AppUserController.AppUserPost.authenticateJWT ,AppUserController.AppUserPost.login)
}
......@@ -4,7 +4,7 @@
"password": "meu@sds12@!#gh",
"database": "chinguyen_nodejs-practice",
"host": "27.74.255.96",
"port": 5432,
"port": 5430,
"dialect": "postgres"
}
}
\ No newline at end of file
......@@ -23,17 +23,17 @@ module.exports = {
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
languageId: {
type: Sequelize.UUID,
allowNull: false,
onDelete: 'CASCADE',
references: {
model: 'Languages',
key: 'id',
as: 'languageId',
}
}
// languageId: {
// type: Sequelize.UUID,
// allowNull: false,
// onDelete: 'CASCADE',
// references: {
// model: 'Languages',
// key: 'id',
// as: 'languageId',
// }
// }
})
,
down: (queryInterface, Sequelize) => queryInterface.dropTable('AppUsers')
......
......@@ -8,7 +8,7 @@ export class AppUser extends Model {
export class AppUserModel {
id: string
name: string
email: string
pwd: string
createdAt: Date
updatedAt: Date
......@@ -22,6 +22,6 @@ AppUser.init(
{ sequelize, modelName: 'AppUser' }
)
AppUser.belongsTo(Language, {
foreignKey: 'languageId'
})
// AppUser.belongsTo(Language, {
// foreignKey: 'languageId'
// })
......@@ -5,6 +5,7 @@
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"skipLibCheck": true,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment