ParseJS, AngularJS user registration error - javascript

I am using AngularJS to create a user profile registration with a Parse Backend. However, on my console I am getting an error saying Parse is not defined. How would I be able to make it work and insert a new user into the database?
Below is my code:
.controller('reg',['$scope',function($scope, $state, $rootScope){
$scope.signUp = function() {
var user = new Parse.User();
user.set("email", $scope.user.email);
user.set("password", $scope.user.password);
user.set("firstname", $scope.user.firstname);
user.set("lastname", $scope.user.lastname);
user.signUp(null, {
success: function(user) {
$rootScope.user = user;
$state.go('home');
},
error: function(user, error) {
alert("error here");
}
});
};
}])

Related

AngularJS authentication not working as expected

I'm trying to add authentication to my golang/angular app. the backend authentication works fine and logs that the user has logged in but the angular part is not working as expected, it doesn't set the username as when it successfully logs in and changes page, the username is not set.
app.js
blog.controller('LoginCtrl', function($scope, $http, $window, authService){
$scope.login = function({
authService.Login($scope.username, $scope.password, function(response, status){
if(status == 200){
authService.setCredentials($scope.username, $scope.password);
$window.location.href="/";
} else {
$scope.invalidLogin = true;
}
});
};
});
blog.factory('authService', function(username, password, callback){
var service = {};
var username = "";
$http.post('/login', {Username : username, Password: password}).
success(function(response, status){
service.setCredentials(username, password);
callback(response, status);
});
service.setCredentials = function(username, password){
username = username;
};
service.getCredentials = function(){
return username;
};
return service;
});
blog.controller('NavCtrl', function($scope, $rootScope, authService){
$scope.isAuth = (authService.getCredentials() != "");
console.log("username: " + authService.getCredentials());
$scope.username = authService.getCredentials();
});
The problem is that your authService doesn't have the Login method you're calling from your controller:
blog.controller('LoginCtrl', function($scope, $http, $window, authService){
$scope.login = function({
// Well there's your problem!
authService.Login($scope.username, $scope.password, function(response, status){
if(status == 200){
authService.setCredentials($scope.username, $scope.password);
$window.location.href="/";
} else {
$scope.invalidLogin = true;
}
});
};
});
Instead, you need to define your Login method within your factory like so:
myApp.factory('authService', function(){
var service = {};
var username = "";
service.setCredentials = function(loginUsername, password){
username = loginUsername;
};
service.getCredentials = function(){
return username;
};
service.Login = function(loginUsername, password, callback){
$http.post('/login', {Username : loginUsername, Password: password}).
success(function(response, status){
service.setCredentials(loginUsername, password);
callback(response, status);
});
}
return service;
});
Note that I've also changed the username function parameters to loginUsername as it was shadowing the variable you where trying to assign to. This was causing the username value to be undefined.

AngularJS $location only works second time after WebSocket call

In my AngularJS application I'm using WebSocket to connect the application and the API.
My problem is that after making a handshake I want to reroute the user to a new view. This should happen automatic after the call succeeded, this doesn't happen, however if I run the function again it works fine, how can this be?
Error:
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Controller:
...
$scope.signIn = function(){
if($scope.loginForm.$valid){
socketService.handshake($scope.login.username, $scope.login.password, function(response){
if(response.payload.success){
$scope.user = $scope.login;
$scope.user.isLoggedIn = true;
$scope.user = sharedProperties.setUser($scope.user);
$scope.login = {};
$location.path('view/' + sharedProperties.getConfig().views[0].route);
} else {
console.log('Error : Login failed');
}
});
}
};
...
SocketService:
...
var service = {},
socket;
service.handshake = function(username, password, callback){
handshake(username, password, function(response){
callback(response);
});
};
function handshake(username, password, callback){
var jsonObject = {
'agmt': '00001',
'usr': username,
'pwd': password,
"request": 'INIT'
};
socket = new WebSocket(config.socketAddress);
socket.onopen = function () {
console.log("Server is on!");
console.log('json', jsonObject);
socket.send(JSON.stringify(jsonObject));
};
socket.onmessage = function (response) {
console.log('\n' + new Date().toUTCString() + '\nServer responded');
console.log('handshake data : ', response);
callback(JSON.parse(response.data));
};
};
...

Parse Facebook login - Save input username and email

I'm working on a Facebook login for a Parse App, and have added the login element, but would now like to add the FB profile email and name into the database. However, I am unable to do so. How would I be able to insert the username and email of a new user who is using Facebook to register on the app?
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn("email", {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=name,email', function (response) {
var user = new Parse.User();
user.set("username", response.username);
user.set("email", response.email);
});
} else {
alert("You're logged in with Facebook!")
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
Just found out the solution to this. I needed to make a request from FB graphs on the url:
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=id,name,email,permissions', function (response) {
user.set('username', response.name);
user.set('email', response.email);
user.save();
alert("You're registered and logged with via Facebook!");
//redirect to dashboard
});
} else {
alert("You're logged in with Facebook!");
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
This should work for you...
FB.api('/me', function (me) {
user.set("facebook_id", me.id);
user.set("facebook_link", me.link);
user.set("firstName", me.first_name);
user.set("lastName", me.last_name);
user.setEmail(me.email);
user.save().then(function () {
//go to new page
});
});

Token is not defined - MEAN Stack

I've been following a book tutorial called mean machine. It has been super helpful. I am setting up authentication and can't figure out this error I'm getting.
Any help would be greatly appreciated! I can't seem to find the answer anywhere else.
ERROR: token is not defined
at Object.authTokenFactory.setToken (authService.js:69)
authService.js:
angular.module('authService', [])
// ===================================================
// auth factory to login and get information
// inject $http for communicating with the API
// inject $q to return promise objects
// inject AuthToken to manage tokens
// ===================================================
.factory('Auth', function($http, $q, AuthToken) {
// create auth factory obj
var authFactory = {};
// login user
authFactory.login = function(username, password) {
// return promise obj and its data
return $http.post('/api/authenticate', {
username: username,
password: password
})
.success(function(data) {
AuthToken.setToken(data.token);
return data;
});
};
// logout user by clearing token
authFactory.logout = function() {
AuthToken.setToken();
};
// check if user is logged in
// checks for local token
authFactory.isLoggedIn = function() {
if (AuthToken.getToken())
return true;
else
return false;
};
// get logged in user
authFactory.getUser = function() {
if (AuthToken.getToken())
return $http.get('/api/me', { cache : true});
else
return $q.reject({ message : 'User has no token.'});
};
return authFactory;
})
// ===================================================
// factory for handling tokens
// inject $window to store token client-side
//
//
// ===================================================
.factory('AuthToken', function($window) {
var authTokenFactory = {};
// get token out of local storage
authTokenFactory.getToken = function() {
return $window.localStorage.getItem('token');
};
// function to set token or clear token
// if a token is passed, set the token
// if there is no token, clear it from local storage
authTokenFactory.setToken = function() {
if (token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
};
return authTokenFactory;
})
// ===================================================
// application configuration to integrate token into requests
// ===================================================
.factory('AuthInterceptor', function($q, $location, AuthToken) {
var interceptorFactory = {};
// this will happen on all http requests
interceptorFactory.request = function(config) {
// grab token
var token = AuthToken.getToken;
// if token exists add it to the header as x-access-token
if (token)
config.headers['x-access-token'] = token;
return config;
};
// happens on response errors
interceptorFactory.responseError = function(response) {
// if 403 from server
if (response.status == 403) {
AuthToken.setToken();
$location.path('/login')
}
//return the errors from server as promise
return $q.reject(response);
};
return interceptorFactory;
});
mainCtrl.js
angular.module('mainCtrl', [])
.controller('MainController', function($rootScope, $location, Auth) {
var vm = this;
// get info if a person is logged in
vm.loggedIn = Auth.isLoggedIn();
// check to see if user is logged in on every req
$rootScope.$on('$routeChangeStart', function() {
vm.loggedIn = Auth.isLoggedIn();
// get user info on route change
// Auth.getUser()
// .success(function(data) {
// vm.u = data;
// });
Auth.getUser().then(function (data) {
vm.user = data;
},
function (response) {
// Handle case where user is not logged in
// or http request fails
});
});
// handle login form
vm.doLogin = function () {
vm.processing = true;
// clear error
vm.error = '';
// call Auth.login() func
Auth.login(vm.loginData.username, vm.loginData.password)
.success(function(data) {
vm.processing = false;
//if a user logs in, redirect to users pg
if (data.success)
$location.path('/users');
else
vm.error = data.message;
});
};
// log out
vm.doLogOut = function() {
Auth.logout();
vm.u = {};
$location.path('/login');
};
});
The error message you've received really says it all. The token variable is never defined in authTokenFactory.setToken().
authTokenFactory.setToken = function(token) { // Add this variable delcaration
if (token)
$window.localStorage.setItem('token', token);
else
$window.localStorage.removeItem('token');
};
}

Can Angular Service call a function in the Controller that invoke the service?

Here is my controller
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
function RegisterController($location, $scope, Authentication){
var vm = this;
vm.register = register;
function register(){
Authentication.register(vm.email, vm.password, vm.confirm_password, vm.username);
}
function register_error_display(error_list){
console.log("what is going on")
}
}
Here is my service
function Authentication($cookies, $http, RegisterController){
var Authentication = {
register: register
};
return Authentication;
// Register logic
function register(email, password, confirm_password, username){
return $http.post('/api/v1/accounts/',{
username: username,
password: password,
confirm_password: confirm_password,
email: email
}).then(registerSuccess, registerError);
}
function registerError(response){
error_list = response["data"];
RegisterController.register_error_display(error_list);
}
}
The flow is this register (controller) -> post (service) -> registerError (service) -> register_error_display (controller)
I believe this is returning me this error
Error: [$injector:unpr] Unknown provider: RegisterControllerProvider <- RegisterController <- Authentication
What is the reason of this error, is there a way around it?
You can't inject controllers in services. One of the reasons is that a controller is instantiated every time a directive is created, while the a service is instantiated once at startup.
Instead you can make the Authentication.register function return a promise. One can be created using the $q service.
Or, if you do not want to do anything after the authentication succeeds or fails in the Authentication service just return the promise you get from the $http.post call.
Returning the http.post response:
service
function Authentication($cookies, $http){
var Authentication = {
register: register
};
return Authentication;
// Register logic
function register(email, password, confirm_password, username){
return $http.post('/api/v1/accounts/',{
username: username,
password: password,
confirm_password: confirm_password,
email: email
});
}
controller
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
function RegisterController($location, $scope, Authentication){
var vm = this;
vm.register = register;
function register(){
Authentication.register(vm.email, vm.password, vm.confirm_password, vm.username).then(onSuccess, onError);
}
function onSuccess(result) {
console.log("HTTP request succeeded");
}
function onError(result) {
console.log("HTTP request failed");
}
}
Your own promise:
service
function Authentication($cookies, $http, $q){
var Authentication = {
register: register
};
return Authentication;
// Register logic
function register(email, password, confirm_password, username){
var deferred = $q.defer();
$http.post('/api/v1/accounts/',{
username: username,
password: password,
confirm_password: confirm_password,
email: email
}).then(function(result) {
deferred.resolve(result);
}, function(error) {
deferred.reject(result);
});
return deferred.promise();
}
}
controller
RegisterController.$inject = ['$location', '$scope', 'Authentication'];
function RegisterController($location, $scope, Authentication){
var vm = this;
vm.register = register;
function register(){
Authentication.register(vm.email, vm.password, vm.confirm_password, vm.username).then(onSuccess, onError);
}
function onSuccess(result) {
console.log("Authentication success");
}
function onError(result) {
console.log("Authentication success");
}
}
I would recommend making and returning your own promise. That way you can abstract from the controller how the authentication actually takes place.
For example you could still have a successful request but the response might be that the authentication failed.

Categories

Resources