Angularjs login authentication issues - javascript

I am new using Angularjs and I'm building a login-page using AngularJS through REST API. I'm facing an issue when I am trying to submit my form. I browsed through so many web-site and links, but I din't got proper answer. Please don't tell me to google it, because I already have so many blue links. If you know anything , please correct me and if you have any working example share it .
AngularJS :
var app = angular.module('logapp',['toastr','ngRoute']);
app.factory('Auth', function($http){
var service = {};
service.login = function(username,password) {
$http.post('http://localhost:3000/loginfo',
{
username : username,
password : password
})
.then(
function successCallback(response){
console.log(response.data);
});
};
service.isAuthenticated = function() {
return {
isAuthenticated : false,
}
};
return service;
});
app.controller('credientials', function($scope,$http,Auth) {
$scope.isAuthenticated = false;
$scope.userCred = {
username: '',
password: ''
}
/*-----Form Submition-----*/
$scope.log = function(userCred){
Auth.login(userCred, function(result) {
console.log(Auth);
if (result === true) {
console.log('success');
} else {
$scope.Error = response.message;
}
});
};

First things first, this part
Auth.login(userCred, function(result) {
is Wrong. Your service.login takes 2 parameters. And they are username and password. It does not take any callback.
Right way to do it is like this
Auth.login(userCred.username, userCred.password)
.then(function(result){
console.log(result);
})
.catch(function(err){
console.error(err);
});
Which goes without saying, you refactor your service.login as follows
service.login = function(username,password) {
return $http.post('http://localhost:3000/loginfo',{
username : username,
password : password
})
}

Related

Asynchronous execution error on AWS Cognito registering method

I'm making an user management with the Amazon Web Service names Cognito.
It runs smoothly on local but it is not when I use it on a Wamp server.
I can not figure out why... maybe cause to asynchronous execution ?
I'm using $q and .then(function() { ... }); to wait for it's execution.
This is how I do in my controller :
$scope.validateForm = function() {
if (AuthService.getActifUser() == false) {
//clear local storage
$storage.remove('userData');
}
//getting the form attributes
var datafirstName = {
Name: 'custom:first_name',
Value: $scope.firstName
};
var dataLastName = {
Name: 'custom:last_name',
Value: $scope.lastName
};
var dataEmail = {
Name: 'email',
Value: $scope.email
};
var attributeFirstName = AuthService.setAttributes(datafirstName);
var attributeLastName = AuthService.setAttributes(dataLastName);
var attributeEmail = AuthService.setAttributes(dataEmail);
var attributeList = [];
attributeList.push(attributeFirstName);
attributeList.push(attributeLastName);
attributeList.push(attributeEmail);
// signing try
AuthService.signin($scope.username, $scope.password, attributeList)
.then(function(res) {
// save username in local storage
$storage.set('userData', $scope.username);
// go to the verification page
routeService.goToView('/users-confirmation');
}, function(res) {
console.log(res);
);
}
And in the AuthService Factory :
AuthService.signin = function(username, password, attributeList) {
var deferred = $q.defer();
userPool.signUp(username, password, attributeList, null, function(err, result) {
if (err) {
alert(err);
deferred.reject('registering failled.');
}
console.log('successfully registered.');
deferred.resolve('successfully registered.');
});
return deferred.promise;
};
Unfortunatelly the routeService.goToView() method is never called.
Hope someone know why ?
Could you please add a handler for the promise rejection to ensure that the promise is not being rejected?
It could be that your promise is being rejected and the error hidden. Also, where is invalidPassword being defined?

How to call angular service method from controller?

I'm bit new in angular. I've built 'Employee Search' Service module. Here is the code...
// Service for employee search
app.service('employeeSearchService', function($http, resourceServerAddress){
this.empList = [];
// Method for clearing search employee list
this.clearEmpList = function(){
this.empList = [];
}
// Method for fetching employee search list
this.fetchEmpList = function(){
return this.empList;
}
// Method for making employee search
this.searchEmpList = function(empName){
var postData = {
empName:empName,
};
$http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function successCallback(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
this.empList = response;
}
else
{
console.log('no matches found for employee search');
this.empList = [];
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function errorCallback(response) {
console.log('Error occur at time of processing request');
});
}
});
Then, I'm using following code in my Controller to fetch data from this Service module.
employeeSearchService.searchEmpList(empName);
empSearchResponseList = employeeSearchService.fetchEmpList();
console.log('Search response from server module : '+empSearchResponseList);
I can see from my chrome console that, I'm getting data from my AJAX call with all console message from Service module. But, can't able to catch those data in Controller variable.
I think the way, I'm using 'searchEmpList()' & 'fetchEmpList()' in my controller it's not the right way. But, can't able to find out how to modify that one.
Need Some Guidance -.-
--- Controller Code updated ----
// Controller for application Home route
app.controller("HomeController", function($scope, $state, $location, $ionicHistory, $ionicSideMenuDelegate, $http, resourceServerAddress, employeeSearchService) {
console.log('At home controller');
// Check application session. If it's found not exist redirect user to login page
if(window.localStorage.getItem("access_token") === "undefined" || window.localStorage.getItem("access_token") === null) {
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
console.log('Redirecting user to login page-222');
$state.go("login");
}
$scope.empName = '';
$scope.alertMsgBox = false;
$scope.alertMsgText = '';
$scope.employees = [];
$scope.resourceServerAddress = resourceServerAddress;
var empSearchResponseList=null;
// Method for employee search
$scope.searchEmployee = function(form){
console.log('Employee name entered : '+$scope.empName);
console.log('Employee name character length : '+$scope.empName.length);
if($scope.empName.length >= 3 ){
var postData = {
Emp_Name:$scope.empName,
access_token:window.localStorage.getItem('access_token'),
session_id:window.localStorage.getItem('session_id')
};
$http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function successCallback(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
$scope.employees = response['data']['data'];
$scope.alertMsgBox = false;
}
else
{
console.log('no matches found for employee search');
$scope.alertMsgBox = true;
$scope.employees = [];
$scope.alertMsgText = 'No matches found.';
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function errorCallback(response) {
console.log('Error occur at time of processing request');
});
}
}
// Method for showing employee profile
$scope.showEmpProfile = function(empId){
console.log('HomeCtrl - click on profile image of emp id : '+empId);
// Redirecting to home page
$state.go('app.emp-profile', {empId:empId});
}
});
this also seems confusing for me.
the $http call s done asynchronously so when you call fetch it fetches an empty array.
I would do something like this
this.searchEmpList = function(empName){
var postData = {
empName:empName,
};
return $http({
method: 'POST',
url: resourceServerAddress,
data : postData
}).then(function(response) {
console.log('Response Data : '+response);
if(response['data']['status'] === 'success'){
console.log('Response received successfully with status=success');
if(response['data']['data'].length)
{
console.log('matches found for employee search');
return response['data']['data'];
}
else
{
console.log('no matches found for employee search');
return [];
}
}
if(response['data']['status'] === 'error'){
console.log('Response received successfully with status=error');
}
}, function(response) {
console.log('Error occur at time of processing request');
});
}
and in the controller
employeeSearchService.searchEmpList(empName).then(function(data){
console.log('data is ready', data);
});
Also notice that you have to return the $http in order to use .then() in the controller ( returns a promise).
Fot a great styleguide for angular check
Are you sure that you service works?
I prefer this syntax:
.service('Service', function () {
var Service = {
//methods here
}
return Service;
});
And you don't need hard work with 'this'.

How can i get data from service in angular

I have LoginController and securityService.
This is LoginCtrl
// place the message if something goes wrong
$scope.authMsg = '';
$scope.login = function () {
$scope.authMsg = '';
var loginData = {email: $scope.account.email, password: $scope.account.password};
securityService.login(loginData);
};
This is securityService
login: function (logData) {
var _vm = this;
$http
.post('/api-token-auth/', logData)
.then(function (response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if (!response.data.token) {
_vm.authMsg = 'Incorrect credentials.';
} else {
$cookieStore.put('djangotoken', response.data.token);
$http.defaults.headers.common.Authorization = 'JWT ' + response.data.token;
$http.get('/api/account/restricted/').then(function (response) {
authService.loginConfirmed();
_vm.currentUser = response.data;
$rootScope.currentUser = response.data;
});
}
}, function (x) {
_vm.authMsg = 'Server Request Error';
});
},
This login is working fine but my problem is i don't know how can get the authMesg from service to controller because that is async. Everytime i get blank message in case of invalid login
you need to use promise service of angular to make you controller and service syn
login: function (logData) {
var _vm = this,d= $$q.defer();
$http
.post('/api-token-auth/', logData)
.then(function (response) {
// assumes if ok, response is an object with some data, if not, a string with error
// customize according to your api
if (!response.data.token) {
_vm.authMsg = 'Incorrect credentials.';
} else {
$cookieStore.put('djangotoken', response.data.token);
$http.defaults.headers.common.Authorization = 'JWT ' + response.data.token;
$http.get('/api/account/restricted/').then(function (response) {
authService.loginConfirmed();
_vm.currentUser = response.data;
$rootScope.currentUser = response.data;
});
}
d.resolve(vm.authMsg);
}, function (x) {
_vm.authMsg = 'Server Request Error';
d.reject(vm.authMsg);
});
},
In controller you need to resolve this promise
securityService.login(loginData).then(function(data){
consol.log(data); // get success data
},function(error){
consol.log(data); // get error message data
})
and inject $q in your service.
This will give you authMsg
securityService.login(loginData).authMsg
But follow #Vigneswaran Marimuthu comments, that is best practice.

Parse.com: getting UserCannotBeAlteredWithoutSessionError

I have an Angular service that takes in a roleId and userId and assigns the user to that role and make a pointer in User to that role.
app.service('CRUD', function () {
this.addUserToRole = function (roleId, userId) {
// first we have to find the role we're adding to
var query = new Parse.Query(Parse.Role);
return query.get(roleId, {
success: function (role) {
// then add the user to it
var Database = Parse.Object.extend("User");
var query = new Parse.Query(Database);
console.log(role);
return query.get(userId, {
success: function (user) {
console.log(user);
role.getUsers().add(user);
role.save();
// now we need to tell the user that he has this role
console.log(user);
user.attributes.role.add(role);
user.save();
return user;
},
error: function (err) {
return err;
}
});
},
error: function (err) {
console.log(err);
}
});
}
});
I'm getting {"code":206,"error":"Parse::UserCannotBeAlteredWithoutSessionError"} on user.save();
After some research, I arrived at this website. He uses this code snippet as a JS SDK example:
Parse.Cloud.run('modifyUser', { username: 'userA' }, {
success: function(status) {
// the user was updated successfully
},
error: function(error) {
// error
}
});
and mentions something about a useMasterKey() function.
I'm still unsure how to fix this error.
Add
Parse.Cloud.useMasterKey();
at the beginning of your function.
Set it up as a background job. That is the code snip you found I think and a simpler far more secure means of fondling users and roles
https://parse.com/docs/cloud_code_guide#jobs

Angular UI Router and server side redirecting

I'm building a small Meteor app and I've stumbled upon a minor setback.
I was using Iron:Router and Angular UI Router which led to some difficulties. I had to remove the Iron:Router to resolve them and by doing that I lost the benefit of redirecting to an URL on the server side. How I used to redirect and process using the Iron:Router:
Router.route('/payment/:invoice_no/:amount/:userId', {
where: 'server',
action: function() {
var amount = parseInt(this.params.amount);
var url = generate_URL_for_payment_authorization(this.params.invoice_no,this.params.amount,this.params.userId);
if (url == null) {
this.response.end("error");
}
this.response.writeHead(301, { 'Location': url});
this.response.end();
}
});
How I rewrote the previous code using the Angular UI Router:
.state('premiumPayment', {
url: '/payment/:invoice_no/:amount/:userId',
controller: function($scope, $stateParams, $http) {
var invoice_no = $stateParams.invoice_no;
var amount = $stateParams.amount;
var userId = $stateParams.userId;
Meteor.call('testingFunction', invoice_no, amount, userId, (error) => {
if (error) {
alert(error);
}
else {
console.log('Going to PayPal screen!');
}
});
}
})
And the testingFunction. I would like to know how do I redirect once I got the URL?
testingFunction: function (invoice_no, amount, userId) {
console.log(invoice_no);
console.log(amount);
console.log(userId);
var url = "";
if (Meteor.isServer) {
url = generate_URL_for_payment_authorization(invoice_no,amount,userId);
console.log("Going to this URL now: " + url);
//HOW DO I REDIRECT TO THE URL HERE???
}
}
So basically what I'm asking, how do I navigate to that URL which I get in the testingFunction function? I can't use Iron:Router because I'll get some unwanted behaviour back into my app.

Categories