Registration using AngularJS - javascript

I want to do a very simple registration using AngularJS.
Firstly, I'm getting user with this e-mail and assign to $scope.users. If method "GetUserByEmail" returns more than one user, I try show message "User already exists". And here is problem. Method GetUserByEmail is avoided. Program "jumps" to "if" condition and $scope.users is always empty, I don't know why. Sometimes after adding user to database, the method returns array of object and assign to $scope.users
It's my code with method CreateUser:
var RegisterController = function ($scope, Api, $http) {
$scope.users = {
}
$scope.CreateUser = function () {
var user = {
Password: $scope.password,
Name: $scope.name,
Surname: $scope.surname,
Email: $scope.email,
DateOfBirth: $scope.dateofBirth
}
Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).then(function (d) {
$scope.users = d;
});
if ($scope.users.length > 0)
{
alert("User already exists!");
$scope.users = {};
}
else
{
Api.PostUser("Users", "PostUser", user).then(function (d) {
alert("Hello");
});
}
};
}
RegisterController.$inject = ['$scope', 'Api', '$http'];
And method GetUserByEmail:
this.GetUserByEmail = function (controllerName, methodName, email) {
var promise = $http({
method: 'GET',
url: 'api/' + controllerName + '/' + methodName + '?email=' + email,
config: {
params: {
"email": email
}
}
})
.then(function onSuccess(response) {
return response.data;
},
function onError(response) {
return response.statusText;
});
return promise;
}

Try this!!!
var RegisterController = function($scope, Api, $http) {
$scope.users = {}
$scope.CreateUser = function() {
var user = {
Password: $scope.password,
Name: $scope.name,
Surname: $scope.surname,
Email: $scope.email,
DateOfBirth: $scope.dateofBirth
}
Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).then(function(d) {
$scope.users = d;
if ($scope.users.length > 0) {
alert("User already exists!");
$scope.users = {};
} else {
Api.PostUser("Users", "PostUser", user).then(function(d) {
alert("Hello");
});
}
});
};
}
RegisterController.$inject = ['$scope', 'Api', '$http'];

If you used success...error block on your request, eventhough the response is null, request will return into success block and you can validate yor data. I think these are fine you.
var RegisterController = function ($scope, Api, $http) {
$scope.users = {
}
$scope.CreateUser = function () {
var user = {
Password: $scope.password,
Name: $scope.name,
Surname: $scope.surname,
Email: $scope.email,
DateOfBirth: $scope.dateofBirth
}
Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).success(function (response) {
if (response!=null && dresponse.lenght > 0)
{
alert("User already exists!");
$scope.users = {};
}
else
{
Api.PostUser("Users", "PostUser", user)
.success(function (d) {
alert("Hello");
}).error(function(e){
console.log(e.message);
});
}
}).error(function(error){
console.log(error.message);
});
};
}
RegisterController.$inject = ['$scope', 'Api', '$http'];

Related

login authentication issue in angularjs

I have created login page and for accessing data I have used JSON File. when I click on the login() btn , userdata should match with the server data. But I am getting error and I am not able to send the $http response to the client side from server. If the rows with that name and password matches it return true, if not return false. then the client should parse this response.
But I don't know how What I am doing wrong?
Any help / advice would be greatly appreciated.
AngualJS:
/* server-side */
app.factory('auth', function ($http, session) {
var authService = {};
authService.login = function (username, password) {
var response;
$http.post('http://localhost:3000/loginfo')
.then(
function successCallback(response) {
var user = response.data;
console.log(user);
if (user.username == username && user.password == password) {
var signinfo = response.data;
console.log(response.data);
} else {
console.log('Error');
}
})
};
authService.isAuthenticated = function () {
return {
isAuthenticated: false,
user: null
}
};
return authService;
});
/* client-side */
app.controller('credientials', function ($scope, $http, auth) {
$scope.userCred = {
username: '',
password: ''
};
/*-----Form Submition-----*/
$scope.log = function (userCred) {
auth.isAuthenticated = true;
auth.login(userCred.username, userCred.password, function (response) {
if (response.success) {
console.log('success');
} else {
console.log('Error');
}
})
};
});

How to get loggedin user info in angularjs

I want to get info on the currently logged in user so that i can display it for example. I have tried the following code but i get the error AuthService.getAuthMember is not a function can anyone help
var myApp = angular.module('myApp', ['ngResource', 'ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/api/meetups', {
templateUrl: 'partials/main.html',
access: {restricted: true}
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController',
access: {restricted: false}
})
.when('/prive', {
templateUrl: 'partials/prive.html',
controller: 'userController',
access: {restricted: true}
})
.when('/logout', {
controller: 'logoutController',
access: {restricted: true}
})
.when('/register', {
templateUrl: 'partials/register.html',
controller: 'registerController',
access: {restricted: false}
})
.when('/one', {
template: '<h1>This is page one!</h1>',
access: {restricted: true}
})
.when('/two', {
template: '<h1>This is page two!</h1>',
access: {restricted: false}
})
.otherwise({
redirectTo: '/'
});
});
myApp.run(function ($rootScope, $location, $route, AuthService) {
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
AuthService.getUserStatus()
.then(function(){
if (next.access.restricted && !AuthService.isLoggedIn()){
$location.path('/login');
$route.reload();
}
});
});
});
angular.module('myApp').factory('AuthService',
['$q', '$timeout', '$http',
function ($q, $timeout, $http, $cookies) {
// create user variable
var user = null;
// we must create authMemberDefer var so we can get promise anywhere in app
var authenticatedMemberDefer = $q.defer();
// return available functions for use in the controllers
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
getAuthMember: getAuthMember,
setAuthMember: setAuthMember
});
function isLoggedIn() {
if(user) {
return true;
} else {
return false;
}
}
//this is function that we will call each time when we need auth member data
function getAuthMember() {
return authenticatedMemberDefer.promise;
}
//this is setter function to set member from coockie that we create on login
function setAuthMember(member) {
authenticatedMemberDefer.resolve(member);
}
function getUserStatus() {
return $http.get('/user/status')
// handle success
.success(function (data) {
if(data.status){
user = true;
} else {
user = false;
}
})
// handle error
.error(function (data) {
user = false;
});
}
function login(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/login',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
user = true;
deferred.resolve();
//**
$cookies.putObject('loginSession', data);
// here create coockie for your logged user that you get from this response, im not sure if its just "data" or data.somethingElse, check you response you should have user object there
} else {
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/user/logout')
// handle success
.success(function (data) {
user = false;
deferred.resolve();
//on log out remove coockie
$cookies.remove('loginSession');
})
// handle error
.error(function (data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(username, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/user/register',
{username: username, password: password})
// handle success
.success(function (data, status) {
if(status === 200 && data.status){
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function (data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
}]);
myApp.controller('meetupsController', ['$scope', '$resource', 'AuthService', function ($scope, $resource, AuthService) {
var Meetup = $resource('/api/meetups');
$scope.meetups = []
Meetup.query(function (results) {
$scope.meetups = results;
});
/AuthService.getAuthMember().then(function(member){
console.log(member);
//here your member should be and you can apply any logic or use that data where u want
$scope.username1=member.username;
});
$scope.createMeetup = function () {
var meetup = new Meetup();
meetup.name = $scope.meetupName;
meetup.text = $scope.username;
meetup.$save(function (result) {
$scope.meetups.push(result);
$scope.meetupName = '';
$scope.username = '';
});
}
}]);
myApp.controller('userController', ['$scope', '$resource', function ($scope, $resource) {
/* var Meetup = $resource('/api/user');
$scope.users = []
Meetup.query(function (results) {
$scope.users = results;
});
*/
var Meetup = $resource('/api/user', {},{
query: {method: 'get', isArray: true}
});
$scope.users = []
$scope.text='mikyas';
Meetup.query({text: $scope.text}).$promise.then(function (results) {
$scope.users = results;
}, function(error) {
// console.log(error);
$scope.meetups = [];
});
}]);
Can you change your run to something like this
myApp.run(function($rootScope, $location, $route, AuthService, $cookies) {
$rootScope.$on('$routeChangeStart',
function(event, next, current) {
if ($cookies.get('loginSession')) {
var session = JSON.parse($cookies.get('loginSession'));
AuthService.setAuthMember(session);
} else {
$location.path('/login');
}
});
});
Also try console.log(AuthService) and check if you see that getAuthMember() function.
Edit:
var myApp = angular.module('myApp', ['ngResource', 'ngRoute', 'ngCookies']);
Don't forget to include angular cookies.

AngularJS - Does not test callback function from Service call in controller in unit test script using Jasmine

Error:In test.js call callback(fetch response) from servie function call in controller
Here there is three files.
In that test.js test the controller.js file using karma-jasmin for unit testing for angular js
controller.js
'use strict';
// Login Angular Module Controller
var loginModule = angular.module('loginModule.controllers'['toaster','vcRecaptcha']);
// Controller Function : loginCtrl
// Parameters : $scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller
loginModule.controller('loginCtrl', function ($scope, $rootScope, $cookieStore, $location, AuthenticationServiceLogin, FlashService, toaster, vcRecaptchaService, $http, $controller)
{
//redirect user to dashboard if already logged in
$rootScope.globals = $cookieStore.get('globals') || {};
if ($rootScope.globals.currentUser) {
$location.path('/home');
}
// Function Name : forget password
$scope.forgetPassword = function(){
$scope.dataLoading = true;
AuthenticationServiceLogin.forgetPassword($scope.email, function (response) {
if (response.success) {
toaster.pop('success', "", "Email sent Successfully. Please check your email.");
$scope.dataLoading = false;
}else{
toaster.pop('error', "", "Email is incorrect / Email not exist in Database");
$scope.dataLoading = false;
}
});
};
//AuthenticationService.ClearCredentials();
// Function Name : login
$scope.login = function (){
$scope.dataLoading = true;
// callback(response);
// Service Calls Function : userLogin
// Parameters : $scope.username,$scope.password AuthenticationServiceLogin.userLogin($scope.username,$scope.password, function (response) {
console.log(response.success);
if(response.success)
{
AuthenticationServiceLogin.SetCredentials(response);
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
if (response.status ==200) {
//AuthenticationServiceLogin.SetCredentials(response);
//START STOMP to establish connection
var stompCtrl = $rootScope.$new();
$controller('StompController', { $scope: stompCtrl });
//END STOMP to establish connection
toaster.pop('success', "", "Login Successful");
$location.path('/home');
}
else if(response.status ==401){
toaster.pop('error', response.status+" "+response.statusText," Access is denied due to invalid credentials");
$scope.dataLoading = false;
}
else {
toaster.pop('error', "Username / Password", "Username or password is incorrect");
$scope.dataLoading = false;
}
});
};
});
service.js
'use strict';
var loginModule = angular.module('loginModule.services',['vcRecaptcha']);
loginModule.service('AuthenticationServiceLogin', function ($http, $cookieStore,$rootScope,$timeout, UserService, Base64,vcRecaptchaService,ENV) {
var service = {};
var servicePath = ENV.apiEndpoint;
this.forgetPassword = function(email,callback)
{
$timeout(function () {
var response;
if(email == 'admin#belvms.com'){
response = {success: true};
}
else {
response = {success: false};
}
callback(response);
}, 900);
}
this.userLogin = function(username, password,callback) {
$timeout(function () {
var response;
if(username == 'admin' && password =='admin'){
response = {success: true};
}
else {
//response = {success: false, message: 'Username or password is incorrect'};
}
callback(response);
}, 900);
var data1 = "username=" + username + "&password="
+ password + "&grant_type=password&scope=read%20write&" +
"client_secret=belSecret&client_id=vms-bel";
};
this.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
}
};
});
test.js
'use strict';
describe('Login', function () {
var $controller1,AuthenticationServiceLogin,$window,$scope,$location;
beforeEach(module('loginModule.controllers'));
beforeEach(inject(function(_$controller_,_$q_,_$window_,_$location_) {
$controller1 = _$controller_;
$window = _$window_;
AuthenticationServiceLogin = { userLogin: function() {},
forgetPassword: function() {}
}; spyOn(AuthenticationServiceLogin,'userLogin').and.returnValue(response);
spyOn(AuthenticationServiceLogin,'forgetPassword').and.returnValue(response);
}));
describe('Login', function () {
it('To call Login function', function () {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin: AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.login();
});
it('To call services', function() {
var $scope = {};
var $rootscope = {};
var $location = {};
var $cookieStore = {};
var $http = {};
var $controller = {};
var FlashService = {};
var controller = $controller1('loginCtrl',{
$scope: $scope,
$rootscope: $rootscope,
$location: $location,
$window: $window,
$cookieStore:$cookieStore,
AuthenticationServiceLogin:AuthenticationServiceLogin,
FlashService:FlashService,
$http:$http,
$controller:$controller
});
$scope.username="admin";
$scope.password="admin";
$scope.login();
it('should have a getData function', function() {
expect(angular.isFunction(AuthenticationServiceLogin.userLogin)).toBe(true);
});
$scope.email='admin#belvms.com';
var response1=function(response){};
console.log(response1);
expect(AuthenticationServiceLogin.userLogin).toHaveBeenCalledWith('admin','admin',response1);
});
});
});
Here i attached image that display error when run test script.
enter image description here
so give solution why this erroe or why can't fetch reponse from userLogin function in test script

unsupported_grant_type error in angularJS and web API

I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData)
{
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; //is not working
//var data = { username: loginData.userName, password: loginData.password, grant_type: "password" }; // I try this and is not working too
//data = $.param(data);
// how should I format my data for the web API to understand
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }
I made google search but still no solution; how can I resolve this issue?
thanks in advance!!

what is "error": "unsupported_grant_type" in web Api

I am trying to achieve user login
and logout using angularJS and web Api
But the server always return badrequest (400)
exception
the error is coming from this bit of code
AuthApp.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {
var authServiceFactory = {};
var _authentication =
{
isAuth: false,
userName: ""
};
// this is the login function
authServiceFactory.login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
// alert(data);
$http.post('/token', data, {
header: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName });
_authentication.isAuth = true;
_authentication.userName = loginData.userName;
deferred.resolve(response);
}).error(function (err) {
// _logout();
deferred.reject(err);
});
return deferred.promise;
}
authServiceFactory.logout = function ()
{
localStorageService.remove("authenticationData");
_authentication.isAuth = false;
_authentication.userName = "";
}
return authServiceFactory;
}]);
using postman to further see the error
this appears
{ "error": "unsupported_grant_type" }

Categories

Resources