Angularjs : server side templating - angularjs

I am very new to MEAN. And I have made an application using node.js, express and mongodb. I want to send username to dashboard after user is logged in. How can I do it using Angularjs. I don't want to use ejs templating engine. If any Middle ware is required....plzz tell me.
thank you...
this is my usercrud.js
var User = require("../../schema/user/userschema");
var bcrypt = require('bcrypt');
const userOperation={
login(userObject,response){
var username=userObject.userid;
var psw = userObject.password;
User.find({ userid:username}, function (err, user) {
if (err) {
return done(err); }
if (!user) {
return done(null, false, { message: 'no user found' });
}
if(user){
console.log("user's true password is: "+user[0].password);
console.log("password"+psw);
bcrypt.compare(psw, user[0].password, function(err, res) {
if (err){
throw err;}
if(!res) {
console.log('Ooops!. Wrong Pass!');
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
}
if(res){
response.redirect('dashboard');
}
});
}
});
},
}
how can I send username to the dashboard.html
this is userroute.js
router.get('/dashboard',(req,response)=>{
});

As you are using MEAN stack for your application, what you can do is check login via async call and return user object in response. Then you can store that user into localstorage.
Once user is successful in logIn and you get this "user" object in response, redirect user from login to dashboard using angular redirection not from back-end server.
After redirection use localstorge for getting user information.

Related

How can I check if user is already Logged in using aws cognito user pool anywhere in project?

I am doing SSO(Single Sign On) in my application. I am making use of AWS cognito for it and user pool and Identity pool for users.
I have setup user pool, identity pool and using hosted UI.
When I am using Custom UI for login and calling below cognito function:
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
AWS.config.region = config.region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : config.IdentityPoolId, // your identity pool id here
Logins : {
'cognito-idp.<region>.amazonaws.com/<pool-id>': result.getIdToken().getJwtToken()
}
});
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh((error) => {
console.log("in refresh");
if (error) {
console.error(error);
} else {
console.log('Successfully logged!');
}
});
},
onFailure: function(err) {
console.log("in failure");
alert(err.message || JSON.stringify(err));
},
mfaRequired: function(codeDeliveryDetails) {
// MFA is required to complete user authentication.
// Get the code from user and call
console.log("in mfa required");
cognitoUser.sendMFACode(mfaCode, this)
}
});
This works fine but I am not able to redirect user to routes on successful and failure.
I want to use hosted UI.
Now I am able to successfully authenticate user from hosted UI and redirect to URL provided in app client settings callback URL. And getting id_token, access_token in url. I am able to decode it and get username from that.
But when I do:
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var userPool = new AmazonCognitoIdentity.CognitoUserPool(config.poolData);
console.log("cog user: ", userPool.getCurrentUser());
I get null.
Is there any way to get current logged in user So that I can identify if user is logged in or not and do next operations accordingly.

howto prevent www-authenticate header when using passport-http Basic + passport-local combination

Hi I want to support both formbased authentication and http basic authentication in my app. Everything works as expected except when I use form based auth via angularjs with wrong credentials.
Instead of having my angular code handle the 401, the browser shows the BASIC auth dialog, caused by the WWW-Authenticate header.
How can I prevent that header from being added when the local strategy is used?
Or how can I support both mechanisms in a different way?
I use the following route in my express based app.
api.post('/authenticate', passport.authenticate(['local', 'basic'], { session: false }), function (req, res) {
This enables both authentication methods on that url. I repeat, when I use wrong credentials using formbased it shows me the basic auth dialog (I don't want that).
Following is how I registered the strategies.
passport.use(new BasicStrategy({ realm: 'Authentication failed. Wrong username or password.'}, verifyLocalUser));
passport.use(new LocalStrategy(verifyLocalUser));
This is how my verifyUser method looks like...
var verifyLocalUser = function (username, password, next) {
User.findOne({
username: username
}).select('fullname admin username password').exec(function (err, user) {
if (err) {
return next(err);
}
if (user && user.comparePasswords(password)) {
return next(null, user);
} else {
next(null, false, { message: 'Authentication failed. Wrong username or password.' });
}
});
}
Does anyone know how to support multiple authentication methods using passport.js?
For completeness, this is the angular code which authenticates me...
authFactory.signIn = function (username, password) {
return $http.post('/api/authenticate', {
username: username,
password: password
}).then(function (res) {
AuthToken.setToken(res.data.token);
return res.data;
}, function (res) {
console.warn(res);
});
};
instead of this:
next(null, false, { message: 'Authentication failed. Wrong username or password.' });
You can use this:
cb(new YourCustomError())
And "YourCustomError" can have a message, for me mine "YourCustomError" looks like:
class HttpError extends Error {
constructor (msg = 'Invalid Request', status = 400) {
super(msg)
this.status = status
}
}
class Forbidden extends HttpError {
constructor (msg = 'Forbidden') {
super(msg, 403)
}
}
Or probably new Error(<message>) will work properly for you, too

How can i authenticate the nodejs application using ionic framework?

I am trying to create a web service for my phone gap application.
Backend is written in nodejs. They have used Passport ,
local_login method for the same. which is giving me access_token as well.
I am able to login and able to fetch access token using phone gap application.
How can i fetch other data, which is required session authentication using Phone gap
any idea ?
You can use passport-http-bearer
passport.use(new BearerStrategy(
function(token, done) {
User.findOne({ token: token }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user, { scope: 'all' });
});
}
));
Authenticate Requests
app.get('/profile',
passport.authenticate('bearer', { session: false }),
function(req, res) {
res.json(req.user);
});
for more details visit this link https://github.com/jaredhanson/passport-http-bearer

How to secure feature for authenticated users only in Meanjs when using angularjs

I am working on my first app, and have started with the front-end and angularjs. In general I have found it very intuitive, but the relationship between backend and frontend is where things start to blur for me.
I have now gotten to the point where I want to provide slightly different functionality on some pages depending on whether the user is authenticated or not (in this case the ability to edit some form fields in a form).
From the public angularjs side it seems easy enough to write a basic if statement to provide different functionality to authenticated users (see basic attempt below) but as this is a client side function, how do I prevent a user spoofing authentication to edit things I don't want them to (save to database).
angular.module('core').controller('myCtrl', ['$scope', 'Authentication', 'Menus',
function($scope, Authentication, Menus) {
$scope.authentication = Authentication;
if(typeof $scope.authentication.user == "object"){
// behaviour for authenticated
}else{
// for unauthenticated
}
}
I am new to mean, meanjs and node.js in general, being primarily a php guy, so please be gentle if my question is way off base.
I suggest using passport a npm module for user authentication. Here's some code to get you started. Also take a look at this scotch.io tutorial
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../app/models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if the user is found but the password is wrong
if (!user || !user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong username or password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
};

passportjs and backbone: authenticating users

Currently I been using a chrome app called Postman to test my services from nodejs/express/passportjs.
Currently I'm having trouble wrapping my head around how I should grab the user info and authenticate it with backbone.
I would try to authenticate the user like so:
$.post("http://localhost:3000/login", { username: "joe", password: "pass" })
.done(function(data) {
console.log(data)
//try to pull a service that's protected by passport
})
.fail(function(data) {
console.log(data)
})
Which is not working at all when it's successful. Its giving the 500 error I set for when someone isn't logged in.
Any particular direction I should be going in to manage authentication with passportjs in backbone?
The 500 error means some part of the code in the server is not working properly.
You can send the logged in user from express using passport. You can follow the following example.
var app = express();
var login = require('./routes/login');
app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login',
failureFlash: true }),
login.login);
where your login.js file may look like this
exports.login = function (req, res) {
res.json(req.user);
}
the authenticate process of passport populates user variable in request (req) with the logged in user.
Please note, you have to use cookie parser and session of express to make the passport session working. e.g.,
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat' }));
your local authentication may look like the following (say you have a function that finds user by username (findByUsername)).
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
});
}
));

Resources