Commit 594a3bc4 authored by KANTAPONG SONG-NGAM's avatar KANTAPONG SONG-NGAM

add work

parent b5b120bb
passport = require('passport');
localStrategy = require('passport-local').Strategy;
User = require('./user');
config = require('./config');
JWTstrategy = require('passport-jwt').Strategy;
//We use this to extract the JWT sent by the user
ExtractJWT = require('passport-jwt').ExtractJwt;
//Create a passport middleware to handle User login
passport.use('login', new localStrategy({
usernameField : 'username',
passwordField : 'password'
}, async (username, password, done) => {
try {
//Find the user
user = await User.findOne({ username });
if( !user ){
//If the user isn't found in the database, return a message
return done(null, false, { message : 'User not found'});
}
//Validate password and make sure it matches with the corresponding hash stored in the database
//If the passwords match, it returns a value of true.
const validate = await user.isValidPassword(password);
if( !validate ){
return done(null, false, { message : 'Wrong Password'});
}
//Send the user information to the next middleware
return done(null, user, { message : 'Logged in Successfully'});
} catch (error) {
return done(error);
}
}));
//This verifies that the token sent by the user is valid
passport.use(new JWTstrategy({
//secret we used to sign our JWT
secretOrKey : config.secret,
jwtFromRequest : ExtractJWT.fromUrlQueryParameter(config.secret)
}, async (token, done) => {
try {
//Pass the user details to the next middleware
return done(null, token.user);
} catch (error) {
done(error);
}
}));
module.exports = {
'secret': 'KolenCompation',
'database': 'mongodb://localhost/Kolen'
}
\ No newline at end of file
{
"name": "week03",
"version": "1.0.0",
"lockfileVersion": 1
}
{
"name": "week03",
"version": "1.0.0",
"description": "",
"main": "auth.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC"
}
express = require('express');
passport = require('passport');
jwt = require('jsonwebtoken');
config = require('./config');
apiRoutes = express.Router();
apiRoutes.post('/login', async (req, res, next) => {
passport.authenticate('login', async (err, user, info) => {
try {
if(err || !user){
const error = new Error('An Error occured')
return next(error);
}
req.login(user, { session : false }, async (error) => {
if( error ) return next(error)
const body = { _id : user._id, username : user.username };
token = jwt.sign({ user : body },config.secret);
//Send back the token to the user
return res.json({ token });
}); } catch (error) {
return next(error);
}
})(req, res, next);
});
module.exports = apiRoutes;
express = require('express');
apiRoutes = express.Router();
// GET(http://localhost:8000/api/)
apiRoutes.get('/', function(req, res) {
res.json({ message: 'Welcome to API routing'});
});
// GET(http://localhost:8000/api/users)
apiRoutes.get('/users', function(req, res) {
User.find({}, function(err, users) {
if (err) throw err;
res.json(users);
});
});
module.exports = apiRoutes;
express = require('express');
app = express();
bodyParser = require('body-parser');
morgan = require('morgan');
mongoose = require('mongoose');
jwt = require('jsonwebtoken');
passport = require('passport');
config = require('./config');
routes = require('./routes');
secureRoute = require('./secure-routes');
// =======================
// configuration
// =======================
// server setting
var port = process.env.PORT || 8000;
// connect databse
mongoose.connect(config.database,{useNewUrlParser:true});
//mongoose.Promise = global.Promise;
// application variables
app.set('superSecret', config.secret);
require('./auth');
// config for body-parser
app.use(bodyParser.urlencoded({ extended: false}));
app.use(bodyParser.json());
// log request
app.use(morgan('combined'));
// =======================
// routes
// =======================
app.use('/', routes);
app.use('/api', passport.authenticate('jwt', { session : false }), secureRoute );
// =======================
// start the server
// =======================
app.listen(port);
console.log('started http://localhost:' + port + '/');
// get mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
UserSchema = new Schema({
username : {
type : String ,
required : true
},
password : {
type : String,
required : true
},
admin : {
type : Boolean,
required : true
}
})
// make user model and export
module.exports = mongoose.model('User', UserSchema);
This diff is collapsed.
...@@ -14,6 +14,9 @@ ...@@ -14,6 +14,9 @@
"express": "^4.16.4", "express": "^4.16.4",
"jsonwebtoken": "^8.3.0", "jsonwebtoken": "^8.3.0",
"mongoose": "^5.3.7", "mongoose": "^5.3.7",
"morgan": "^1.9.1" "morgan": "^1.9.1",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0"
} }
} }
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