node.js - How to generate token using passport.js while signing in locally and not with any other social media channel? -
i trying generate token while logging in locally. let's normal user , want sign in. token generated while signing in? , how? need guidance.
as using mongodb require users schema model in routes code.here routes code user.js
var express = require('express'); var router = express.router(); var passport = require('passport'); var user = require('../models/schema'); var verify = require('./verify'); /* users listing. */ router.get('/', function(req, res, next) { res.send('respond resource'); }); router.post('/register', function(req, res) { user.register(new user({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password, function(err, user) { if (err) { return res.status(500).json({err: err}); } passport.authenticate('local')(req, res, function () { return res.status(200).json({status: 'registration successful!'}); }); }); }); router.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.status(401).json({ err: info }); } req.login(user, function(err) { if (err) { return res.status(500).json({ err: 'could not log in user' }); } var token = verify.gettoken(user); res.status(200).json({ status: 'login successful!', success: true, token: token }); }); })(req,res,next); }); router.get('/logout', function(req, res) { req.logout(); res.status(200).json({ status: 'bye!' }); }); module.exports = router;
when @ code notice verify variable.it nothing verification user registered or not.if user registered user allow login.after login user successfull response along token.so here veirfy code verify.js
var user=require('../models/schema'); var jwt = require('jsonwebtoken'); // used create, sign, , verify tokens var config = require('../config.js'); exports.gettoken = function (user) { return jwt.sign(user, config.secretkey, { expiresin: 3600 }); }; exports.verifyordinaryuser = function (req, res, next) { // check header or url parameters or post parameters token var token = req.body.token || req.query.token || req.headers['x-access-token']; // decode token if (token) { // verifies secret , checks exp jwt.verify(token, config.secretkey, function (err, decoded) { if (err) { var err = new error('you not authenticated!'); err.status = 401; return next(err); } else { // if good, save request use in other routes req.decoded = decoded; next(); } }); } else { // if there no token // return error var err = new error('no token provided!'); err.status = 403; return next(err); } };
if observe code there variable config nothing connection mongodb.here code config.js
module.exports = { 'secretkey': '12345-67890-09876-54321', 'mongourl' : 'mongodb://localhost:27017/confusion' }
and user schema here schema.js
var mongoose = require('mongoose'); var schema = mongoose.schema; var passportlocalmongoose = require('passport-local-mongoose'); var user= new schema({ username:{ type:string, required:true, unique:true }, email:{ type:string, required:true, unique:true }, phone:{ type:number, required:true, unique:true }, password:{ type:string } }); user.plugin(passportlocalmongoose); module.exports = mongoose.model('user',user);
and server code app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieparser = require('cookie-parser'); var bodyparser = require('body-parser'); var mongoose = require('mongoose'); var passport = require('passport'); var localstrategy = require('passport-local').strategy; var config = require('./config'); mongoose.connect(config.mongourl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { console.log("connected correctly server"); }); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: false })); app.use(cookieparser()); app.use(express.static(path.join(__dirname, 'public'))); var user = require('./models/schema'); app.use(passport.initialize()); passport.use(new localstrategy(user.authenticate())); passport.serializeuser(user.serializeuser()); passport.deserializeuser(user.deserializeuser()); app.use('/users', users); // catch 404 , forward error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render error page res.status(err.status || 500); res.render('error'); }); app.listen(3000,function(){ console.log("server listening on 3000"); }); module.exports = app;
project structure
must per code
+app.js +config.js +routes(directory) ++user.js ++verify.js +models(directory) ++schema.js
run code node app.js
when want register use http://localhost:3000/users/register
, login use http://localhost:3000/users/login
Comments
Post a Comment