Can't access req.user in Node.js server with Auth0/Angular - javascript

I'm using auth0 to act as my admin panel's login, and it's running great. A problem that I'm having is that in node, I cannot for some reason access 'req.user' as it returns unidentified. This is a pretty basic setup here. I have console logged req.headers and an authentication header is set.
Here is the node app.js file
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var Parse = require('node-parse-api').Parse;
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your 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')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.Parse = new Parse(options.app_id, options.api_key);
app.use('/api', routes(app), expressJwt({secret: 'Mode'}));
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '/public') });
});
module.exports = app;
Here is the AngularJS code.
var app = angular.module('EnragedGamers', ['angularMoment', 'ngRoute', 'auth0', 'angular-storage', 'angular-jwt'])
.config(function(authProvider, $routeProvider, $locationProvider, $httpProvider, jwtInterceptorProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'Home'
})
.when('/article/:article_id', {
templateUrl: 'article.html',
controller: 'Article'
})
.when('/admin-panel/login', {
templateUrl: 'admin-login.html',
controller: 'Admin-Login'
})
.when('/admin-panel', {
templateUrl: 'admin.html',
controller: 'Admin',
requiresLogin: true
});
authProvider.init({
domain: 'enragedgamers.auth0.com',
clientID: 'MpTkAl4eosjl3SB682ZGSSrJYi03QiZp',
loginUrl: '/admin-panel/login'
});
jwtInterceptorProvider.tokenGetter = ['store', function(store) {
// Return the saved token
return store.get('token');
}];
$httpProvider.interceptors.push('jwtInterceptor');
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
})
.run(function($rootScope, auth, store, jwtHelper, $location) {
// This hooks al auth events to check everything as soon as the app starts
$rootScope.$on('$locationChangeStart', function() {
var token = store.get('token');
if (token) {
if (!jwtHelper.isTokenExpired(token)) {
if (!auth.isAuthenticated) {
auth.authenticate(store.get('profile'), token);
}
} else {
// Either show the login page or use the refresh token to get a new idToken
$location.path('/');
}
}
});
});
Here is the routes file code
var express = require('express');
var router = express.Router();
module.exports = function(app){
router.get('/admin/hello', function(req, res){
console.log(req.user)
res.status(201).json({'human': 'Hello'})
console.log(req.body);
});
return router;
}

It seems that you're missing your secret on the node side and the middle man for actually authenticating.
See https://github.com/auth0/express-jwt
var jwt = require('express-jwt');
app.use(jwt({ secret: 'your secret key here'}));

Related

Cannot post data from Angular.js to Node.js

I am creating a MEAN stack application using AngularJS and Node.js.
Here is my AngularJS code:
app.js:
var app = angular.module('crudApp', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider
.when('/employees/create', {
templateUrl : 'create.html',
controller : 'EmployeeController'
}).when('/nothing', {
templateUrl : 'main.html',
controller : 'mainController'
});
$locationProvider.html5Mode(true);
}]);
app.controller('EmployeeController',function($scope,$http) {
$scope.save = function(data) {
$scope.data = JSON.stringify(data);
console.log(data);
$http.post("http://localhost:8080/employees/create-employee",$scope.data).then(function(response) {
console.log("posted successfully");
});
};
});
Here is my Node.js code:
server.js:
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(__dirname + '/angularjs/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('*',function(req, res) {
res.sendFile(__dirname + '/angularjs/public/index.html');
});
require('./node/routes')(app);
app.listen(8080);
routes.js:
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.body);
});
Angular part is working fine, displays data in console, posting the data and getting "posted successfully" message.
But in node, I am unable to get the posted data in req.body.
I am getting the "create.html" content when I checked in browser "network".
Need someone's help.
Use this
module.exports = function(app) {
app.post('/employees/create-employee',function(req,res) {
console.log(req.body);
});
And for get you should use req.params
module.exports = function(app) {
app.get('/employees/create-employee',function(req,res) {
console.log(req.params);
});

NodeJS and ExpressJS Router.use() error

I get this error:
TypeError: Router.use() requires middleware function but got a Object at Function. (C:/Users/peter/Desktop/mean/express-server/node_modules/express/lib/router/index.js:458:13)
I was testing my Api in post man and I got this error.
I got it when i in my app.js when I did app.use('/api',api);
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 session = require("express-session");
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/jokesApi');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public/images', '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')));
app.use(session({secret:'secret_3162735',saveUninitialized:true, resave: true}));
// The error comes from here
app.use('/api',api);
app.use(function (req, res, next) {
var session = req.session;
var input = req.body;
if(session.userName){
return next();
}else if(input.userName){
session.userName = input.userName;
return res.redirect('/');
}else{
req.url='/login';
return next();
}
});
app.use('/', routes);
app.use('/users', users);
module.exports = app;
JokesApi.js:
var express = require('express');
var jokes = require('../model/jokes');
var session = require("express-session")
var router = express.Router();
router.get('/joke/random',function(req,res,next){
res.end({joke: jokes.getRandomJoke()});
});
router.get('/jokes',function(req,res,next){
res.end({joke: jokes.allJokes});
});
router.post('/joke', function(req,res){
var funJoke = req.body;
var jsonJoke = funJoke.Joke;
jokes.addJoke(jsonJoke);
res.end({funnyNewJoke: jsonJoke});
})
You're not exporting your router in jokesApi.js. Add this to the end of that file:
module.exports = router;
The module jokesApi needs to be exported:
module.exports = router;
Try to follow this example: http://expressjs.com/en/guide/routing.html

Error: passport.initialize() middleware not in use what order to make calls?

I have the follow - Generated initially by the Visual Studio Node Tools, uses Express and Jade as the client
/**
* Module dependencies.
*/
var express = require('express');
var fs = require('fs');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var https = require('https');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var loginHandler = require('./routes/Login.js');
var auth = require('./config/auth.js');
var googleSupport = require('./googleSupport.js');
var googleAuthority = auth.googleAuth;
var googleScopes = '';
// retrieve google scopes
googleScopes = googleSupport.discoverServiceScopes(auth.googleAuth);
// set up passport
passport.serializeUser(function (user,done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: googleAuthority.clientId,
clientSecret: googleAuthority.clientSecret,
callbackURL: googleAuthority.callbackUrl
},
function (accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
var request = require('request');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
console.log('extracting service scopes');
app.get(passport.initialize());
app.get(passport.session());
app.get('/', routes.index);
app.get('/index', routes.index);
// google login support
// go to login page.
app.get('/googleLogin', passport.authenticate('google', { scope: [googleScopes] }),
function (req, res) {
res.redirect('/');
}
);
app.get('/AuthorizeGoogle', passport.authenticate('google', { failureRedirect: '/'}),
function (req, res) {
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The thing is when it validates the user I get the following
500 Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\http\request.js:44:34)
at Strategy.module.exports.strategy.success (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\middleware\authenticate.js:228:13)
at verified (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:179:18)
at Strategy._verify (C:\Node\YourLivesN\YourLivesN\app.js:41:12)
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:195:22
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-google-oauth\lib\passport-google-oauth\oauth2.js:115:7
at passBackControl (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:125:9)
at IncomingMessage. (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:143:7)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
Now I am assuming this is the same cause as this question passport.js passport.initialize() middleware not in use but cannot see what order the calls should be in my code.
So can anyone tell me what order to place the various parts of the code.
Thanks
Try changing this part
app.get(passport.initialize());
app.get(passport.session());
to
app.use(passport.initialize());
app.use(passport.session());
further reading on subject : Difference between app.use and app.get in express.js
, and I would suggest you separate passport configuration in a stand alone file and require it on paths that need authentication. Example tutorial : https://www.youtube.com/watch?v=zbfet_-Z5UQ&index=12&list=PLZm85UZQLd2Q946FgnllFFMa0mfQLrYDL

Angular ng-view not working with express

I'm trying work open page home of directory partials/home using ng-view and ng-view not working with express. A new page opens with render when acess http://localhost:3000/home. All routes defined for angular has no effect. I would like to know how to render my page partials/home.html in index.html using ng-view with express.
app.js
//módulos
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//uncomment after placing your favicon in /public
app.use(favicon(__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')));
load('routes').then('controllers').into(app);
server.listen(3000);
console.log('Site no ar ...');
module.exports = app;
Routes Express - index.js
module.exports = function (app) {
app.get('/', function(req, res){
res.render('index');
});
app.get('/:name', function(req, res){
var name = req.params.name;
res.render('partials/' + name);
});
app.get('*', function(req, res){
res.render('index');
});
};
Routes Angular - Location: public/app/app.js
var app = angular.module('appSiteFio',['ngRoute']);
app.config(function($routeProvider, $locationProvider){
// remove o # da url
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'mainController',
})
.when('/home', {
templateUrl : 'partials/home.html',
controller : 'homeController',
})
.otherwise ({ redirectTo: '/' });
});
I would suggest changing the index.js file to something like:
module.exports = function (app) {
app.use(express.static('/partials')); //here you can write your partials directory.
app.get('*', function(req, res){
res.render('index');
});
};
(Also change your templateUrl inside angular file with the partials prefix.);
that way angular will allways will be loaded and angular router will deal with all the views fetching from the static partials folder

Angular with Node

So Im trying to work AngularJS and Node. I am trying to set up client side routing but Im having some problems.
EDIT
So I changed up some code following https://github.com/scotch-io/starter-node-angular that #PareshGami suggested. I get the URLS to be hit but now the actual content doesnt load.
Here is my updated Code:
server.js:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
app.use(bodyParser.json());
require('./server/routes')(app);
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
my angular app.js:
(function (angular) {
'use strict';
var app = angular.module('eos', [
'ngRoute',
'ngResource',
'eos.opsCtrl',
'eos.dashboardCtrl'
]);
app.config(function ($routeProvider, $locationProvider){
$routeProvider.when(
'/',
{
templateUrl: 'views/dashboard.html',
pageName: 'Dashboard',
controller: 'dashboardCtrl'
}
);
$routeProvider.when(
'/ops',
{
templateUrl: 'views/ops.html',
pageName: 'Operations',
controller: 'opsCtrl'
}
);
$routeProvider.otherwise({redirectTo: '/'});
$locationProvider.html5Mode(true);
});
}(window.angular));
My routes.js (new):
var opsController = require('./controllers/opsController');
module.exports = function(app) {
//path.join(__dirname, 'client');
// server routes ===========================================================
// handle things like api calls
// authentication routes
app.get('/api/ops', opsController.list);
app.post('/api/ops', opsController.create);
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendFile('index.html', { root: './client' });
});
};
Then rest is identical. And suggestions on why it is not loading the content in the ng-view?
FINALLY GOT IT TO WORK! My server.js was set up wrong.
Here is the correct server.js. Notice position of:
require('./server/routes')(app);
it needed to be father down for what I assume is the compile sequence
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
methodOverride = require('method-override');
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use('/js', express.static(__dirname + '/client/js'));
app.use('/views', express.static(__dirname + '/client/views'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname +'/node_modules'));
require('./server/routes')(app);
app.listen(3000);
console.log('Im Listening...');
exports = module.exports = app;
I was directed by PareshGami to look over this site 'setting-up-a-mean-stack-single-page-application'. After following that I was able to get the routing to work. The key to my problem was the ordering of my server.js file and the require('./server/routes')(app); part.

Categories

Resources