Retrieve data to put as a parameter when logging in - angularjs

EDIT:
Including more code because I'm having a hard time implementing your solution.
[...]
$scope.loginForm.loading = false;
$scope.submitLoginForm = function() {
$scope.loginForm.loading = true;
$http
.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: `here goes the token`
})
.then(function onSuccess() {
window.location = '/myPage';
toastr.success('You are in!', 'Success', { closeButton: true });
})
.catch(function onError(sailsResponse) {
// if (sailsResponse.status === 403) {
// // toastr.error('Removed', 'Error', {
// // closeButton: true
// // });
// window.location = '/restore';
// return;
// }
// Handle known error type(s).
// Invalid username / password combination.
if (sailsResponse.status === 400 || 404) {
// $scope.loginForm.topLevelErrorMessage = 'Invalid email/password combination.';
//
toastr.error(
'Invalid email or username/password combination.',
'Error',
{
closeButton: true
}
);
return;
}
toastr.error(
'An unexpected error occurred, please try again.',
'Error',
{
closeButton: true
}
);
return;
})
.finally(function eitherWay() {
$scope.loginForm.loading = false;
});
};
[...]
[...]
$scope.submitLoginForm = function() {
$http
.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: `I need the data here`
})
[...]
How do I retrieve the _csrf paramether, reachable through a GET in /csrfToken, at the exact time the request is being send?

Not at the exact time but you can get the csrf_token just before you call '/login'.
$scope.submitLoginForm = function() {
$http.get('/csrfToken')
.then(function successCallback(response) {
var csrf = response.data._csrf;
$http.put('/login', {
email: $scope.loginForm.login,
username: $scope.loginForm.login,
password: $scope.loginForm.password,
_csrf: csrf
});
}, function errorCallback(response) {
alert(response.statusText);
});
}

Related

Unable to store values in mongoDb?

My API log:
OPTIONS /api/signup 204 14.010 ms - -
req.body { '{"name":"rahul jain","mobile":"343453","email":"inayath#cantern.in","password":"123","cpassword":"123"}': '' }
POST /api/signup 200 9.296 ms - 56
I'm making a post request from angular.js to node.js server and here is my angular.js code:
.controller('RegisterCtrl', function($scope, AuthService, $state, $http) {
$scope.user = {
name: '',
mobile:'',
email:'',
password:'',
cpassword:''
};
$scope.signup = function() {
console.log("user",$scope.user);
$http.post("http://localhost:8080/api/signup", $scope.user )
.then(function (response) {
return response;
});
};
})
Here is my node.js code:
apiRoutes.post('/signup', function(req, res) {
console.log("req",req.body);
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
mobile: req.body.mobile,
email: req.body.email,
password: req.body.password,
cpassword: req.body.cpassword
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
I think that req.body object having key-value and key is my whole data. Is that correct? Please help me out, thanks in advance.

res.json sending old data

Hi I have an issue that I can't really explain with res.json from express.
Here is my /login route:
router.post('/login', function (req, res) {
if (req.body.user) {
var newUser = (typeof req.body.user === 'string') ? JSON.parse(req.body.user) : req.body.user;
User.findOne({ email: newUser.email })
.exec(function (err, user) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (user !== undefined && user !== null) {
// Check password and generate a token if it exist
encrypt.checkHash(newUser.pwd, user.pwd, function (err, isCorrect) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (isCorrect != false) {
// Generate token and send it
Token.generateToken({
_id: user._id, email: user.email,
iat: moment().valueOf(),
exp: moment().add(30, 'minutes').valueOf(),
},
conf.secret,
{},
function (err, token) {
if (err) {
return res.json({ error: true, authenticate: false, data: err });
} else {
console.log('Logged');
return res.json({
error: false,
token: token,
authenticate: true,
msg: 'user_connected',
});
}
});
} else {
console.log('Not logged');
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_empty' });
}
});
And here the function where I made my request to that route:
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
And here my onClick function which start the process
var promise = userRequest.auth($scope.user);
promise.then(function (response) {
var data = response.data;
$log.info('Login RESPONSE ', response);
if (data.error == false && data.authenticate == true) {
$log.info('You are logged');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-success', 'Vous ĂȘtes maintenant connectĂ©');
} else {
$log.info('Wrong informations');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-danger', 'Utilisateur inconnue');
}
}, function (reason) {
$log.error(reason);
});
My function's encrypt.checkHash callback work and the value isCorrect is the good one when checking my password hash. It log 'Logged' if the password is correct and 'Not logged' if it's not.
The first time I made a request on this route it send me back an response by res.json and I get the expected data.
But after the first request, the data I receive is always the one I received on the first query.
e.g: The first time I send correct identification info and it return me
{error: false, token: token, authenticate: true, msg: 'user_connected'}
but after that, every time I try to make another query on that route I keep receiving this JSON object event if my identification info are false.
I'm not an expert in Nodejs and I tried to replace all my
res.json({...})
by
return res.json({...})
to stop the execution but the result still the same.
Can you share your wisdom with me and help me solve this case please ?
I found out why it was happening, in my angularJS factory I initialize only once the $q service and where using it inside a method of the factory. like this:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
// Initialized wrongly
var deferred = $q.defer();
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])
instead of:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
userRequest.auth = function (user) {
// Where to initialize it
var deferred = $q.defer();
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])

Check if email is taken and code is correct in signup

Trying to check if either email is taken, code is wrong, or both are wrong in node. this is my code thus far:
app.post('/auth/signup', function (req, res) {
var code = Access.findOne({ accesscode: 'secretpassword' }, { _id: 0, accesscode: 1 }, function (err, data) {
console.log(data);
});
User.findOne({ email: req.body.email }, function (err, existingUser) {
if (existingUser) {
return res.status(409).send({ message: 'Email is already taken' });
}
else if (code != req.body.access) {
return res.status(400).send({ message: 'Access code is wrong' });
}else {
var user = new User({
displayName: req.body.displayName,
email: req.body.email,
password: req.body.password,
isAdmin: false,
});
}
user.save(function(err, result) {
if (err) {
res.status(500).send({ message: err.message });
}
res.send({ token: createJWT(result) });
});
});
});
I'm trying to check if req.body.access from the signup form is equal to the accesscode field in the Access mongoose schema.
How do I only get the 'secretpassword' when querying with mongoose? Currently I get { accesscode: 'secretpassword'};
And are the if/else-if's correct?
EDIT:
I managed to fix it.
instead of setting it to var code = Access.findOne I did it like this:
var code;
Access.findOne({ accesscode: 'secretpassword' }, { _id: 0, accesscode: 1 }, function (err, data) {
code = data.accesscode;
});
This way it stores the accesscode value into code and we can continue using it in the other functions.
I will use the 'jsonwebtoken' module to do the code part.
https://www.npmjs.com/package/json-web-token
So for generation/verification of code (token) it should look like:
var jwt = require('jsonwebtoken')
// Generate code
jwt.sign({sub:email,purpose:"signup"},signkey,{algorithm:"HS256"});
// Verify the code
var decoded = jwt.verify(code,signkey,{algorithms:"HS256"});
if (decoded.purpose !== "signup") {
throw new Error("invalid purpose");
}
if (decoded.sub !== getObjectProperty(res, emailProperty)) {
throw new Error("invalidactivationcode");
}
As for user email checking there are plenty of example out there in the net using mongodb.

Ldap Login in angular js + Express+ passport-ldapauth + sails application

We have a website which has to be authenticated with windows active directory. I am using passport-ldapauth as middleware.
Authentication does not proceed ahead and whenever I click the submit button the following message gets printed to the console.
{Message : 'Missing credentials'}
this is the code:
login.jade
.login-form(ng-controller="LoginCtrl")
form
input(type="text" ng-model="username" placeholder="Enter employee number")
input(type="password" ng-model="password" placeholder="Enter Password")
button.show-bu-btn.btn.btn-primary(ng-click="submit()") Submit
logincontroller.js
'use strict';
angular.module('someapp').controller('LoginCtrl', function ($scope, $http, $rootScope, Service) {
$scope.submit = function () {
$http.post('/Login', {uname: $scope.username}).success(function (res) {
console.log('login OK ', res);
sessionStorage.userAccessInfo = JSON.stringify(res.userAccessInfo);
sessionStorage.dataQuery = JSON.stringify(res.userAccessInfo);
location.hash = '#/main';
}).error(function (res) {
});
};
});
routes.js
module.exports.routes = {
'post /Login' : 'AuthController.process',
};
AuthController.js
module.exports = {
process: function(req, res) {
var emp = req.body.uname;
Acl.findOne({empid: emp}).exec(function(err, user) {
//console.log(user);
if(user) {
passport.authenticate('ldapauth', function(err, user, info) {
console.log(info);
if(err || !user) {
return res.redirect('/login');
}
req.logIn(user, function(err)
{
if (err)
{
res.redirect('/login');
return;
}
});
})(req, res);
}
else {
res.json({userAccessInfo: undefined});
//console.log('Something is wrong');
}
});
}
};
Acl.js
Data resides in a flat file
module.exports = {
attributes: {
empid: {
type: 'string',
columnName: 'empid'
},
designation: {
type: 'string',
columnName: 'designation'
},
email: {
type: 'string',
columnName: 'email'
}
}
};
Passport.js
var passport = require('passport');
var express = require('express');
var LdapStrategy = require('passport-ldapauth').Strategy;
var app = express();
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
Acl.findOne({id:id}).exec(function(err, user) {
done(err, user);
});
});
passport.use(
new LdapStrategy({
server: {
url: 'ldap://xxxx.xx.xx:389',
adminDn: 'serviceadmin',
adminPassword: 'servicepassword',
searchFilter: '(sAMAccountName={{username}})',
searchBase: 'DC=xxxx,DC=xx,DC=xx'
},
passReqToCallback: true
},
function(user, done) {
if(!user) {
return done(null, false, {message: 'Unknown user'});
}
Acl.findOne({username:user.uid}).exec(function(err,user) {
if(err) {
return done(err);
}
return done(null, user);
});
}
)
);
Any ideas on why I am getting the message are highly appreciated. Please correct if there is some mistake.

Angularjs $cookieProvider unknown provider error

I use a custom authentication service to store my authentication token, authToken. This stores the received user profile into a client side cache with $cookieStorage.put() method. When i run, i get the unrecognized provider error:
authToken:
appModule.factory('authToken',['$cookieStorage',
function($cookieStorage) {
var cachedStorage;
return {
setToken: function(token) {
cachedStorage = token;
$cookieStorage.put('userToken', token);
},
getToken: function() {
if (!cachedStorage) {
cachedStorage = $cookieStorage.get('userToken');
}
},
isAuthenticated: function() {
return !!this.getToken();
}
};
}]);
where i use it:
appModule.controller('AuthenticationController',
function ($scope, accountRepository,authToken) {
$scope.login = function(credentials) {
var profile = accountRepository.login(credentials);
profile.success(function(data) {
if (data) {
var userData = {
username: data.username,
firstName: data.firstName,
lastName: data.lastName,
isLogged: true
}
alert('success', 'OK', 'You are now registered' + userData.firstName);
authToken.setToken(userData);
}
});
}
});
the ngCookie module is inserted into appModule, this works fine because i have used it before.
It is $cookieStore not $cookieStorage
https://docs.angularjs.org/api/ngCookies/service/$cookieStore

Resources