sessionStorage is not replacing - angularjs

$scope.admin_email;
$scope.admin_password;
$scope.onSelect = function(admin_email,admin_password){
console.log( admin_email,admin_password)
console.log("User Name: ", $scope.admin_email,
"Password : ", $scope.admin_password);
var mydata = {
admin_email : $scope.admin_email,
admin_password : $scope.admin_password
}
$http({
async: true,
method: 'POST',
url: 'http://localhost:3000/api/v1/users/login',
data : mydata
}).then(function successCallback(response){
if(response.status==200){
console.log({response});
$rootScope.isLogged=true;
setTimeout(function(){
window.sessionStorage.accessToken = response.data.token;
}, 1000)
$("#loginModal").modal("hide");
// console.log($("#loginModal"));
setTimeout(function(){
window.location='#/dashboard'
}, 1000)
}
else{
alert('login password or username incorrect')
}
},
function errorCallback (response) {
alert("some error occurred. Check the console.");
console.log(response);
});
}
This code window.sessionStorage.accessToken = response.data.token; is not working,it is a login api here window.sessionStorage.accessToken is not replacing
List item
it is showing such errors
Object ata: null error: true message: code: "invalid_token" inner: expiredAt: "2019-03-19T09:22:27.000Z" message: "jwt expired" name: "TokenExpiredError" proto: Object message: "jwt expired" name: "UnauthorizedError" status: 401 proto: Object status: 500 proto: Object

Related

Passing $scope through AJAX, but only few variables inserted

I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed

similar post req giving response in postman but not on angular $http.post

There is post request to get token for user . I have used angular $http.post method In my browser network window its not giving me response but when i try this in postman it gives me response here is screen shot attached
please help
this.login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
//if (loginData.rememberMe) {
data = data + "&client_id=" + constants.AUTHSETTINGS.CLIENT_ID;
//}
debugger;
console.log(data)
var deferred = $q.defer();
$http.post(api_url + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then
(function (response) {
if (loginData.rememberMe) {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: response.data.refresh_token, useRefreshTokens: true });
}
else {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: "", useRefreshTokens: false });
}
console.log('---auth servcie')
console.log(response)
authentication.isAuth = true;
authentication.userName = loginData.userName;
authentication.useRefreshTokens = loginData.rememberMe;
deferred.resolve(response);
}
,function (err, status) {
console.log('auth error -- here ')
console.log(err)
console.log(status)
deferred.reject(err);
//deferred.resolve(err);
});
return deferred.promise;
};
raw data
var data = "grant_type=password&username=asad#gmail.com&password=1234&client_id=angularjs

Retrieve data to put as a parameter when logging in

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);
});
}

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;
};
}])

Angular JS Node JS Bad request error post

I am using angularjs with node js as server.
I am passing data this way from UI.
schatApp.controller('registerController', function($scope,$location,$http) {
$scope.RegisterCredentials=function(){
var data={
"firstName":"simhachalamrsdafrds",
"lastName":"ajay",
"username":"asfsd",
"email":"ajayfds14#m.com",
"provider":"local",
"displayName":"amruth"
}
// var json = "{\"firstName\": \"firstName\",\"lastName\": \"lastName\",\"username\": \"username\",\"email\": \"email\"}";
var config = {
headers : {
contentType:'application/json; charset=utf-8',
dataType: 'json'
}
}
$http.post("/register",JSON.stringify(data),config).then(function sucess(result){
// alert(JSON.stringify(result));
},function failure(result){
// alert(JSON.stringify(result));
});
}
});
This is my backend code
app.post('/register',function(req,res){
var data={
firstName:'simhachalam',
lastName:'ajay',
username:'asfsdq',
email:'ajayfds14#mq.com',
provider:'local',
displayName:'amruth'
}
console.log("111...............");
//console.log(req.body);
//res.setHeader('Content-Type', 'application/json');
core.account.create('local',data,function(err){
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
res.status(201).json({
status: 'success',
message: 'You\'ve been registered, ' +
'please try logging in now!'
});
});
});
I am getting 400 bad request.
Its very difficult to say what could be the issue, you need to do a console.log(err) object. can you give that information for us here.
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
The above code clearly states that you are returning res.status(400), can you change your $http.post to below and check.
$http({
method: 'POST',
url: "/register",
data: JSON.stringify(data),
headers: {'Content-Type': 'application/json; charset=utf-8'}
});
hopefully your /register endpoint is hosted on the same server where you are serving the client from.

Resources