Complete MEAN stack application with authentication using json web tokens
1.0.0
Install the dependencies
$ npm install
Run app
$ npm start
Complete MEAN stack app with authentication
Complete MEAN stack application with authentication using json web tokens
1.0.0
Install the dependencies
$ npm install
Run app
$ npm start
When attempting to register a new User, I'm getting this error:
POST http://localhost:4200/users/register 404 (Not Found)
Shouldn't the port be 8080 to access the Node routes file? It seems like the port is being incorrectly set to 4200 somewhere in the application, but I haven't found where yet. Is this happening for anyone else?
According to the official document of angular2-jwt, the tokenNotExpired()
assume the token name is 'token'. However, in this example, the token name should be 'id-token'.
The function should be rewritten to tokenNotExpired('id_token')
'flash-messages' is not a known element:
this error occurs when I try to use
even after I installed,
npm install angular2-flash-messages
and imported it in app.module.ts,
import {FlashMessageModule} from 'angular2-flash-messages'
imported that in app.components.ts,
import { FlashMessagesService } from 'angular2-flash-messages/module/flash-messages.service';
I also installed, npm install @angular/common --save
and added FlashMessagesModule.forRoot() in the imports
but the error keeps occurring!
PS: I'm using "@angular/cli": "~10.2.0",
any help please !?
Everything works however when I click on profile I am getting this error
SyntaxError: Unexpected token < in JSON at position 0
and then nothing displays besides the Nav bar as the content that is suppose to show up on this profile section does not display.
I realize this error is caused by HTML being returned instead of JSON. But I'm unsure how to correct it as it relates to the profile section. I've looked over all of the code.
Any help would be appreciated.
I added new collection(blog) in meanauth DB and to fetch blog data using express api and to project the data in front end. but I am facing issue.
I am new to express js. Please help me in this.
I try to fetch data from local mongodb using mongoose in my ExpressJS App. But couldn't fetch data.
I have tried to use mongoose and mongojs to retrive data from mongodb.
Even tried with passing right collection name in schema.
Here is my code.
const mongoose = require('mongoose');
const config = require('../config/database');
const DataSchema = mongoose.Schema ({
"title": { type: String },
"Description": { type: String },
"Rate": { type: Number }
}, { collection : 'Datas' });
const Datas = module.exports = mongoose.model('Datas', DataSchema);
//const Datas = module.exports = mongoose.model('Datas', DataSchema,
'Datas');
module.exports.getblogs = function(){
Data.find({}, (recs)=>{
if(recs){
console.log('Records found' + recs)
}else{
console.log('Records not found');
}
});
var mongojs = require('mongojs');
var db = mongojs('mongodb://localhost:27017/mydb', ['blogs']);
// On Connection
db.on('connect', function () {
console.log('Mongo JS database connected')
});
//On Error
db.on('error', function (err) {
console.log('Mongo JS database error', err)
});
module.exports.getBlogs = function(res) {
//var data = db.blogs.find();
db.blogs.find({}, (rec, res)=>{
if(rec){
res.json(rec);
console.log('Data '+ rec)
}else{
console.log('No Data '+ rec)
}
});
}
Output from: ng --version.
@angular/cli: 1.3.1
node: 6.11.2
os: linux x64
@angular/animations: error
@angular/common: error
@angular/compiler: error
@angular/core: error
@angular/forms: error
@angular/http: error
@angular/platform-browser: error
@angular/platform-browser-dynamic: error
@angular/platform-server: error
@angular/router: error
@angular/cli: error
@angular/compiler-cli: error
ubuntu 16.04 , 64-bit
output from : npm start , ng serve
The "@angular/compiler-cli" package was not properly installed. Error: Error: Cannot find module '@angular/compiler-cli'
Error: The "@angular/compiler-cli" package was not properly installed. Error: Error: Cannot find module '@angular/compiler-cli'
at Object. (/home/jsnsree/.nvm/versions/node/v6.11.2/lib/node_modules/@angular/cli/node_modules//src/index.js:14:11)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object. (/home/jsnsree/.nvm/versions/node/v6.11.2/lib/node_modules/@angular/cli/tasks/eject.js:10:19)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
in package.json file
{
"name": "meanauthapp",
"version": "1.0.0",
"description": "MEAN stack authentication app",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},
"dependencies": {
"@angular/compiler-cli": "^4.3.6",
"bcrypt": "^1.0.2",
"bcryptjs": "*",
"body-parser": "*",
"cors": "*",
"express": "*",
"jsonwebtoken": "*",
"mongoose": "*",
"passport": "*",
"passport-jwt": "*"
},
"author": "jsnsree",
"license": "ISC",
"devDependencies": {
"@angular/cli": "^1.3.2"
}
}
I am not sure why I am getting this error.
router.post('/register', (req, res, next) => { let newUser = new User({ name: req.body.name, email: req.body.email, username: req.body.username, password: req.body.password });
deployed the app successfully...
make changes, but they will not reflect, once I run the application again
Hello, firstly you're tutorials are great and really useful, so thank you!
I wanted to add some validation on the register call to check if a user with the given email already exists. I have this which seems to work but I wanted to check if you think this is the best method or if I should use a preSave hook etc?
module.exports.addUser = function(newUser, callback) {
// first check if a user with that email already exists
User.find({email : newUser.email}).exec(function(err, docs) {
if (docs.length){
callback('User with email already exists',null);
} else {
// encrypt password with bcrypt, then save
bcrypt.genSalt(10, (err,salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) callback('Failed to register user',null);
// set password to encrypted password
newUser.password = hash;
// save new user to the database
newUser.save(callback)
});
})
}
});
}
Then I tweaked the addUser function in the routes/users register method so I can use the message from the callback:
router.post('/register', (req,res,next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
User.addUser(newUser, (err,user) => {
console.log(err);
if (err) {
res.json({success: false, msg: err});
} else {
res.json({success: true, msg: err});
}
})
});
I have validation on the front-end with my form (using angular2 material validation) to specify required fields but do I need to validate that the user has all required fields on the back-end too?
Thanks
Hi,
I'm just installing the code, I've done npm install
, and npm start
, but it does not work. I've the following error :
TypeError: ExtractJwt.fromAuthHeader is not a function
at module.exports (C:\Users\Alex\Desktop\FripToGo\meanauthapp-master\config\passport.js:8:36)
at Object.<anonymous> (C:\Users\Alex\Desktop\FripToGo\meanauthapp-master\app.js:42:29)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3
I have not changed the code.
I'm new to programming in general and I've followed the tutorial until the 9th video.
When I tried showing the users name on his profile page, the profile get request returned an empty object.
I'm sure I'm making a simple mistake, but I can't figure out what I'm doing wrong.
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database')
//register
router.post('/register', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
})
User.addUser(newUser, (err, user) => {
if (err) {
res.json({ success: false, msg: 'failed to register user' });
}
else {
res.json({ success: true, msg: 'user registerd' })
}
})
})
//authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({ succes: false, msg: 'user not found' });
}
User.comparePassword(password, user.password, (err, isMatch) => {
console.log('test');
if (err) throw err;
if (isMatch) {
const token = jwt.sign({data: user}, config.secret, {
expiresIn: 604800
});
res.json({
succes: true,
token: 'JWT ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
})
}
else {
return res.json({ succes: false, msg: 'wrong password' });
}
})
})
})
//profile
router.get('/profile', (req, res, next) => {
res.send({user: req.user})
})
//validate
router.get('/validate', (req, res, next) => {
res.send('VALIDATE')
})
module.exports = router;
Thanks,
Jules
When trying to server my angular application i get the following error.
ERROR in multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
Module not found: Error: Can't resolve 'webpack-dev-server/client?http://0.0.0.0:0' in 'C:\Users\Caolan\FingerprintProject\angular-src'
ERROR in Error: No NgModule metadata found for 'AppModule'.
at NgModuleResolver.resolve (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler\bundles\compiler.umd.js:20285:23)
at CompileMetadataResolver.getNgModuleMetadata (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler\bundles\compiler.umd.js:15238:60)
at visitLazyRoute (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler\bundles\compiler.umd.js:31176:104)
at AotCompiler.listLazyRoutes (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler\bundles\compiler.umd.js:31144:20)
at AngularCompilerProgram.listLazyRoutes (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler-cli\src\transformers\program.js:156:30)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\compiler-cli\src\ngtools_api.js:44:36)
at AngularCompilerPlugin._getLazyRoutesFromNgtools (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\cli\node_modules@ngtools\webpack\src\angular_compiler_plugin.js:263:66)
at Promise.resolve.then.then (C:\Users\Caolan\FingerprintProject\angular-src\node_modules@angular\cli\node_modules@ngtools\webpack\src\angular_compiler_plugin.js:586:50)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
-->
### Repro steps
<!--
CD into my angular-src path
-->
The node.js server is running on port 3000 and is connected to MongoDB in port 27017
when i try to server my application the error as shown above appears
Even when i use the "ng new "name"" command it will not create a new angular project folder
![angular error](https://user-images.githubusercontent.com/33484891/36530753-d41ebd04-17b3-11e8-8afe-35cf1831b3f1.PNG)
I copied all code, but I can't navigate to dashboard after authentification. App redirect to /login again with message "You are logged in".
Sorry my english.
I've been noticing that on extra small screens, the bootstrap navbar doesn't toggle display when it becomes hidden. It's been a problem for some of your angular applications and wondering if there is a solution.
Hello,
I followed the tutorial to the T and went through and checked every character of my code / POST request. I am getting the below error in my nodemon console when I try to use postman to POST a new user. I'm at a loss as I'm VERY new to backend, and am assuming that there is something different about the password validation today vs. when the tutorial was created, however I'd like to understand and complete this project nevertheless.
Postman looks like:
"http://localhost:3000/users/register"
"{
"name": "John Doe",
"email": "[email protected]",
"username": "John",
"password": "123456"
};"
Error messages:
"""
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'bcrypt'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object. (/Users/zac/Documents/MEAN/models/user.js:2:16)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object. (/Users/zac/Documents/MEAN/routes/users.js:5:14)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
[nodemon] app crashed - waiting for file changes before starting...
"""
**** I was getting this (below) error at first, but I went into mongo console and created the db "meanauth" and then the error changed to above. clearly I'm missing something integral. Any pointers would be appreciated.**
"""
/Users/zac/Documents/MEAN/models/user.js:38
if(err) throw err;
^
Error: Illegal arguments: undefined, string
at _async (/Users/zac/Documents/MEAN/node_modules/bcryptjs/dist/bcrypt.js:214:46)
at Object.bcrypt.hash (/Users/zac/Documents/MEAN/node_modules/bcryptjs/dist/bcrypt.js:220:13)
at bcrypt.genSalt (/Users/zac/Documents/MEAN/models/user.js:37:12)
at Immediate. (/Users/zac/Documents/MEAN/node_modules/bcryptjs/dist/bcrypt.js:153:21)
at runCallback (timers.js:694:18)
at tryOnImmediate (timers.js:665:5)
at processImmediate (timers.js:647:5)
"""
Pls help!
So I 've trying to follow along and I've been stuck with this error when entering the username and password to localhost:3000/users/authenticate in Postman. I get the following error:
Server Started on http://localhost:3000
Press CTRL + C to stop server
Connected to database mongodb://localhost:27017/mean-app
TypeError: Cannot read property 'username' of undefined
at router.post (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\routes\users.js:28:29)
at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5)
at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5)
at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12)
at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10)
at Function.handle (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:174:3)
at router (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:317:13)
at c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:284:7
at Function.process_params (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:335:12)
at next (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\express\lib\router\index.js:275:10)
at cors (c:\Users\micha\Documents\GitHub\Personal Projects\ml-mean-app\node_modules\cors\lib\index.js:188:7)
Here is my code for users.js
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
const User = require('../models/user');
// Register
router.post('/register', (req, res, next) => {
let newUser = new User ({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err) {
res.json({success: false, msg: 'Failed to register user'});
} else {
res.json({success: true, msg: 'User registered'});
}
});
});
//authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({ success: false, msg: 'user not found' });
}
User.comparePassword(password, user.password, (err, isMatch) => {
console.log('test');
if (err) throw err;
if (isMatch) {
const token = jwt.sign({data: user}, config.secret, {
expiresIn: 604800
});
res.json({
succes: true,
token: 'JWT ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
})
}
else {
return res.json({ succes: false, msg: 'wrong password' });
}
})
})
})
// Profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
res.json({user: req.user});
});
module.exports = router;
Here is my passport.js:
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
Any ideas?
I am begginer. I had written code for front-end in angular 2 before following these tutorials.
that's why I couldn't use angular-cli, now problem is that how can I build custom files in a public folder, there is another option is available instead of ng build? and in front-end code in which file should i change "dist" with "public" folder ?
i copied all the code same to same still getting unauthorized when trying to post the jwt token via localhost/users/profile
When deployed on DigitalOcean, the app connects to the db on my local machine, not on the server. How to fix this?
thanks for the awesome series, and especially as it has had me also learn much on debugging as well, however i am not able to fix an issue with the loggedIn(){tokenNotExpired();}
the issue is once i include the *ngIf="authService.loggedIn()" into the links for dashboard, and profile, as well as logout.
the other links get hidden, but the routes for the home, login and register are no longer clickable, and onclick the following error shows up in the developer tools console
ERROR TypeError: Cannot read property 'loggedIn' of undefined at Object.eval [as updateDirectives] (NavbarComponent.html:18) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806) at checkAndUpdateView (core.es5.js:12144) at callViewAction (core.es5.js:12507) at execComponentViewsAction (core.es5.js:12439) at checkAndUpdateView (core.es5.js:12150) at callViewAction (core.es5.js:12507) at execComponentViewsAction (core.es5.js:12439) at checkAndUpdateView (core.es5.js:12150) at callWithDebugContext (core.es5.js:13206) View_NavbarComponent_0 @ NavbarComponent.html:14 proxyClass @ compiler.es5.js:14091 DebugContext_.logError @ core.es5.js:13146 ErrorHandler.handleError @ core.es5.js:1144 ApplicationRef_.tick @ core.es5.js:5082 (anonymous) @ core.es5.js:4955 ZoneDelegate.invoke @ zone.js:391 onInvoke @ core.es5.js:4149 ZoneDelegate.invoke @ zone.js:390 Zone.run @ zone.js:141 NgZone.run @ core.es5.js:4017 next @ core.es5.js:4955 schedulerFn @ core.es5.js:3851 SafeSubscriber.__tryOrUnsub @ Subscriber.js:238 SafeSubscriber.next @ Subscriber.js:185 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ core.es5.js:3837 NgZone.checkStable @ core.es5.js:4114 NgZone.setHasMicrotask @ core.es5.js:4198 onHasTask @ core.es5.js:4161 ZoneDelegate.hasTask @ zone.js:444 ZoneDelegate._updateTaskCount @ zone.js:464 Zone._updateTaskCount @ zone.js:288 Zone.runTask @ zone.js:208 drainMicroTaskQueue @ zone.js:584 ZoneTask.invoke @ zone.js:490 NavbarComponent.html:14 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 30, nodeDef: Object, elDef: Object, elView: Object} View_NavbarComponent_0 @ NavbarComponent.html:14 proxyClass @ compiler.es5.js:14091 DebugContext_.logError @ core.es5.js:13146 ErrorHandler.handleError @ core.es5.js:1149 ApplicationRef_.tick @ core.es5.js:5082 (anonymous) @ core.es5.js:4955 ZoneDelegate.invoke @ zone.js:391 onInvoke @ core.es5.js:4149 ZoneDelegate.invoke @ zone.js:390 Zone.run @ zone.js:141 NgZone.run @ core.es5.js:4017 next @ core.es5.js:4955 schedulerFn @ core.es5.js:3851 SafeSubscriber.__tryOrUnsub @ Subscriber.js:238 SafeSubscriber.next @ Subscriber.js:185 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ core.es5.js:3837 NgZone.checkStable @ core.es5.js:4114 NgZone.setHasMicrotask @ core.es5.js:4198 onHasTask @ core.es5.js:4161 ZoneDelegate.hasTask @ zone.js:444 ZoneDelegate._updateTaskCount @ zone.js:464 Zone._updateTaskCount @ zone.js:288 Zone.runTask @ zone.js:208 drainMicroTaskQueue @ zone.js:584 ZoneTask.invoke @ zone.js:490
and this also
ERROR TypeError: Cannot read property 'loggedIn' of undefined at Object.eval [as updateDirectives] (NavbarComponent.html:18) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:12806) at checkAndUpdateView (core.es5.js:12144) at callViewAction (core.es5.js:12507) at execComponentViewsAction (core.es5.js:12439) at checkAndUpdateView (core.es5.js:12150) at callViewAction (core.es5.js:12507) at execComponentViewsAction (core.es5.js:12439) at checkAndUpdateView (core.es5.js:12150) at callWithDebugContext (core.es5.js:13206) View_NavbarComponent_0 @ NavbarComponent.html:14 proxyClass @ compiler.es5.js:14091 DebugContext_.logError @ core.es5.js:13146 ErrorHandler.handleError @ core.es5.js:1144 ApplicationRef_.tick @ core.es5.js:5082 (anonymous) @ core.es5.js:4955 ZoneDelegate.invoke @ zone.js:391 onInvoke @ core.es5.js:4149 ZoneDelegate.invoke @ zone.js:390 Zone.run @ zone.js:141 NgZone.run @ core.es5.js:4017 next @ core.es5.js:4955 schedulerFn @ core.es5.js:3851 SafeSubscriber.__tryOrUnsub @ Subscriber.js:238 SafeSubscriber.next @ Subscriber.js:185 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ core.es5.js:3837 NgZone.checkStable @ core.es5.js:4114 NgZone.setHasMicrotask @ core.es5.js:4198 onHasTask @ core.es5.js:4161 ZoneDelegate.hasTask @ zone.js:444 ZoneDelegate._updateTaskCount @ zone.js:464 Zone._updateTaskCount @ zone.js:288 Zone.runTask @ zone.js:208 drainMicroTaskQueue @ zone.js:584 ZoneTask.invoke @ zone.js:490 NavbarComponent.html:14 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 30, nodeDef: Object, elDef: Object, elView: Object} View_NavbarComponent_0 @ NavbarComponent.html:14 proxyClass @ compiler.es5.js:14091 DebugContext_.logError @ core.es5.js:13146 ErrorHandler.handleError @ core.es5.js:1149 ApplicationRef_.tick @ core.es5.js:5082 (anonymous) @ core.es5.js:4955 ZoneDelegate.invoke @ zone.js:391 onInvoke @ core.es5.js:4149 ZoneDelegate.invoke @ zone.js:390 Zone.run @ zone.js:141 NgZone.run @ core.es5.js:4017 next @ core.es5.js:4955 schedulerFn @ core.es5.js:3851 SafeSubscriber.__tryOrUnsub @ Subscriber.js:238 SafeSubscriber.next @ Subscriber.js:185 Subscriber._next @ Subscriber.js:125 Subscriber.next @ Subscriber.js:89 Subject.next @ Subject.js:55 EventEmitter.emit @ core.es5.js:3837 NgZone.checkStable @ core.es5.js:4114 NgZone.setHasMicrotask @ core.es5.js:4198 onHasTask @ core.es5.js:4161 ZoneDelegate.hasTask @ zone.js:444 ZoneDelegate._updateTaskCount @ zone.js:464 Zone._updateTaskCount @ zone.js:288 Zone.runTask @ zone.js:208 drainMicroTaskQueue @ zone.js:584 ZoneTask.invoke @ zone.js:490
I'm trying to generate my angular front end app, by running ng new angular-src
, but I'm getting this error You cannot use the new command inside an Angular CLI project.
cmd is run as administrator, and I'm using the same directory as all previous parts of the project.
Line 40 in user.js needs to be changed from:
newUser.save(callback);
to:
newUser.save(callback());
otherwise posting will sit loading forever in postman.
In routes/users.js, the call to jwt.sign() now expects the user object to be a plain object instead of the one returned by User.getUserByUsername(). I'm getting:
Error: Expected "payload" to be a plain object.
at validate (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:34:11)
at validatePayload (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:56:10)
at Object.module.exports [as sign] (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:108:7)
at User.comparePassword (/Users/tmaple/.../routes/users.js:23:23)
...
So I added:
const plainUserObject = {
name: user.name,
email: user.email,
username: user.username,
password: user.password
}
and pass that into jwt.sign()
`const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log('payload received', jwt_payload);
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err) {
return done(err, false);
}
if(user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}`
The payload is not getting displayed on the console as well as POSTMAN is showing Unauthorized , please help
yeah right
So, I've been following your tutorial series on Youtube, Problem I'm facing is this, even after taking care of unwanted routes in app.js. If I try to access a route such as /abc
(provided this route is not present), it redirects to /
but no content of HomeComponent
is displayed and console give me the error shown in title. So, may be Angular is going crazy. Please guide me with this.
Here's the traceback
error_handler.js:54EXCEPTION: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'abc' Error: Cannot match any routes. URL Segment: 'abc' at ApplyRedirects.noMatchError (http://localhost:3000/vendor.bundle.js:79426:16) [angular] at CatchSubscriber.selector (http://localhost:3000/vendor.bundle.js:79395:29) [angular] at CatchSubscriber.error (http://localhost:3000/vendor.bundle.js:64082:31) [angular] at MapSubscriber.Subscriber._error (http://localhost:3000/vendor.bundle.js:5793:26) [angular] at MapSubscriber.Subscriber.error (http://localhost:3000/vendor.bundle.js:5767:18) [angular] at MapSubscriber.Subscriber._error (http://localhost:3000/vendor.bundle.js:5793:26) [angular] at MapSubscriber.Subscriber.error (http://localhost:3000/vendor.bundle.js:5767:18) [angular] at MapSubscriber.Subscriber._error (http://localhost:3000/vendor.bundle.js:5793:26) [angular] at MapSubscriber.Subscriber.error (http://localhost:3000/vendor.bundle.js:5767:18) [angular] at LastSubscriber.Subscriber._error (http://localhost:3000/vendor.bundle.js:5793:26) [angular] at LastSubscriber.Subscriber.error (http://localhost:3000/vendor.bundle.js:5767:18) [angular] at MergeAllSubscriber.OuterSubscriber.notifyError (http://localhost:3000/vendor.bundle.js:45218:26) [angular] at InnerSubscriber._error (http://localhost:3000/vendor.bundle.js:81826:21) [angular] at InnerSubscriber.Subscriber.error (http://localhost:3000/vendor.bundle.js:5767:18) [angular]ErrorHandler.handleError @ error_handler.js:54next @ application_ref.js:348schedulerFn @ async.js:93SafeSubscriber.__tryOrUnsub @ Subscriber.js:234SafeSubscriber.next @ Subscriber.js:183Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:79NgZone.triggerError @ ng_zone.js:333onHandleError @ ng_zone.js:294ZoneDelegate.handleError @ zone.js:338Zone.runGuarded @ zone.js:142_loop_1 @ zone.js:557drainMicroTaskQueue @ zone.js:566
Any corrections?
Passport authorization works for any user on any other user route.
I am getting "Property 'user' does not exist on type 'Object' " error.
profile.component.ts code
`import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {Router} from '@angular/router';
@component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user:Object;
constructor(private AuthService:AuthService, private router: Router) { }
ngOnInit() {
this.AuthService.getProfile().subscribe(profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
});
}
}
`
auth.service.ts code
`import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule,HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken:any;
user: any;
constructor(private http:HttpClient) { }
registerUser(user){
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/register',user, {headers: headers});
}
authenticateUser(user){
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/authenticate',user, {headers: headers});
}
getProfile(){
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.get('http://localhost:3000/users/profile', {headers: headers});
}
storeUserData(token, user){
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken=token;
this.user=user;
}
loadToken(){
const token = localStorage.getItem('id_token');
this.authToken = token;
}
logout(){
this.authToken=null;
this.user=null;
localStorage.clear();
}
}
`
Anybody can help me.
tried everything suggested earlier regarding this issue that's y thought of name adding it as a new issue...
i tried everything even console.log(jwt_payload) but in postman i m getting unauthorized and terminal is not showing any error
following is my passport.js file
`const JwtStrategy=require('passport-jwt').Strategy;
const ExtractJwt=require('passport-jwt').ExtractJwt;
const User=require('../model/RegisterSchema');
const config=require('../config/database');
module.exports=function(passport){
let opts={};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts,(jwt_payload, done)=> {
console.log(jwt_payload);
User.getUserById({id:jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
} and my user.js code
router.post('/authenticate',(req,res,next)=>{
const username=req.body.username;
const password=req.body.password;
User.getUserByUsername(username,(err,user)=>{
if(err) throw err;
if(!user){
return res.json({sucess:false,msg:'User not found'});
}
User.comparePassword(password,user.password,(err,isMatch)=>{
if(err) throw err;
if(isMatch){
const token=jwt.sign(user.toJSON(),config.secret,{
expiresIn:604800 //1week
});
res.json({
sucess:true,
token:'JWT'+token,
user:{
id:user._id,
name:user.name,
username:user.username,
email:user.email
}
});
}else{
return res.json({sucess:false,msg:'Wrong password'});
}
});
});
});
router.get('/profile',passport.authenticate('jwt',{session:false}), (req, res, next) =>{
res.json({user:req.user});
});
module.exports=router;`
I am getting a 404 error for the users/authenticate endpoint when trying to login. Help please!
I get an error when I try creating a new component in the components folder. The component gets created outside the component folder- in the app folder and I see this error "ERROR in Cannot read property 'length' of undefined". Please how can I fix this?
Passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/User');
const config = require('../config/mongoose');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log(jwt_payload);
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
};
User.js
const mongoose = require('mongoose');
const bcryptjs = require('bcryptjs');
const config = require('../config/mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
};
module.exports.getUserByUsername = function (username, callback) {
const query = {username: username};
User.findOne(query, callback);
};
module.exports.addUser = function (newUser, callback) {
bcryptjs.genSalt(10, function (err, salt) {
bcryptjs.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback)
})
})
};
module.exports.comparePassword = function (candidatePassword, hash, callback) {
bcryptjs.compare(candidatePassword, hash, (err, isMatch) => {
if(err) throw err;
callback(null, isMatch);
})
};
Users.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const User = require('../models/User');
const config = require('../config/mongoose');
const JWT = require('jsonwebtoken');
// register
router.post('/register', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg: 'Failed to register user.'});
} else {
res.json({success: true, msg: 'User registered'});
}
});
});
// authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
const token = JWT.sign({data: user}, config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({success: false, msg: 'User not authenicated'});
}
});
});
});
// profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
res.json({user: req.user});
});
module.exports = router;
Nothing is comming out and I have been looking at the code for hours!
hi....
i am trying to learn MEAN stack web app development
getting unauthorized in passport.js
here code is:
module.exports= function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log('payload received', jwt_payload);
User.getUserById(jwt_payload.sub, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
in above code,....i have changed code as per the version ,even i can't able see payload and its not accessing from below this code.
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log('payload received', jwt_payload);
User.getUserById(jwt_payload.sub, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
if anyone gets answer pls.....help me
FYI, the current Bootswatch URL in index.html
is outdated, since they changed things after adopting Bootstrap 4. The new version 3 URL is https://bootswatch.com/3/sandstone/bootstrap.min.css
- note the '3'.
When the page loads is appears blank and in the console log the following appears.
"Failed to load resource: the server responded with a status of 404 (Not Found)"
I have my heroku app created and have successfully pushed to heroku. I also have my mLab db setup fine. Unfortunately, I cannot register/login successfully from heroku.
https://lmb-meanauthapp.herokuapp.com/
Note, after registering, it says that I have registered but there is no collection made in my db.
When I try to log in, I get an error:
Refused to load the font '' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
I've also seen an Internal Server Error when trying to log in.
One thing I'm confused about is how when were working in dev mode on localhost, we run two servers (one for backend and one for frontend). This logic seems to go away when we deploy to heroku.
Has anyone had this problem or know how to work around it? Thanks.
Steps to reproduce:
Visit https://lmb-meanauthapp.herokuapp.com/
Works, no errors.
Click '[Register]'(https://lmb-meanauthapp.herokuapp.com/register)
Seems to work, no errors. Note: User message about callProdMode() to enable production mode.
Fill in registration form and submit.
Seems to work. See screen shot:
However, there is no collection created in the db on mLab:
Try to login with new account. This does nothing and produces the following error:
error_handler.js:54 EXCEPTION: Response with status: 503 Service Unavailable for URL: https://limitless-tor-36102.herokuapp.com/users/authenticate
Refreshing either the register or login page will produce an "Internal Server Error" on the page.
this.authService.authenticateUser(user).subscribe(data => {
if (data.success){
this.authService.storeUserData(data['token'], data['user']);
this.flashMessages.show('You are now logged in',{ cssClass: 'alert-success', timeout:5000});
this.router.navigate(['/dashboard']);
} else{
this.flashMessages.show(data['msg'], { cssClass: 'alert-danger', timeout:5000});
this.router.navigate(['/login']);
}
when i compile this code it is giving me an error like success,token,user and msg do not exist in property response
nodejs version 10.5.0
Hey I am getting the same issue while registering. I use same function in login so there's no spelling error. Please help me.
Originally posted by @anjali22 in #7 (comment)
change your code like this
getProfile(){
let headers = new Headers();
this.loadToken();
headers = headers.append('Autherization', this.authToken);
headers = headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/users/profile',{headers: headers})
.map(res => res.json());
Originally posted by @DilshanDilipudara in #7 (comment)
First of all thank you for your work and help.
I was trying to get profile details, am using your code only but am getting 401 unauthorized error.
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
authToken: any;
user: any;
constructor(private http:Http) { }
registerUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/register', user,{headers: headers})
.map(res => res.json());
}
authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/users/authenticate', user,{headers: headers})
.map(res => res.json());
}
getProfile(){
let headers = new Headers();
this.loadToken();
headers.append('Autherization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/users/profile',{headers: headers})
.map(res => res.json());
}
storeUserData(token, user){
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
loadToken(){
const token = localStorage.getItem('id_token');
this.authToken = token;
}
logout(){
this.authToken = null;
this.user = null;
localStorage.clear();
}
}
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: Object;
constructor(
private authService : AuthService,
private router: Router
) { }
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
});
}
}
I followed meanauthapp video tutorial part 4 and I'm struggling with a bug.
The error occurred when I post username and password by postman to url "http://localhost:3000/users/authenticate".
The terminal result:
`/Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/jsonwebtoken/sign.js:89
throw err;
^
Error: Expected object
at validate (/Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/jsonwebtoken/sign.js:34:11)
at Object.module.exports [as sign] (/Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/jsonwebtoken/sign.js:100:7)
at User.comparePassword (/Volumes/Work/Learning/MEAN stack/meanauthapp/routes/users.js:40:23)
at bcrypt.compare (/Volumes/Work/Learning/MEAN stack/meanauthapp/models/user.js:48:3)
at /Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/bcryptjs/dist/bcrypt.js:297:21
at /Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/bcryptjs/dist/bcrypt.js:1353:21
at Immediate.next [as _onImmediate] (/Volumes/Work/Learning/MEAN stack/meanauthapp/node_modules/bcryptjs/dist/bcrypt.js:1233:21)
at runCallback (timers.js:781:20)
at tryOnImmediate (timers.js:743:5)
at processImmediate [as _immediateCallback] (timers.js:714:5)`
I think the occurring error part is :
const token = jwt.sign(user, config.secret, { expiresInMinutes : 604800 // 1 week });
The sign function.
Is it version problem?
In the User.comparePassword function, when creating the token object, the entire user object is passed in as the payload to sign, this includes the user's encrypted password. This should be removed before signing, same as for the user object passed to the response json.
I had the surprise today to see that the client application is corrupted as styling. Seems that the url in index.html link - https://bootswatch.com/sandstone/bootstrap.min.css - has undergone an update.
Does anyone have the former bootstrap.min.css file?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.