Unable to minify JS - angularjs

Before implementing Firebase authentication this JS file successfully minifyed without any problems.
The file works without any problems when using the none-midifyed version, I'm unable to test the minifyed version as Atom will not allow me to minify and save due to the following error (See attached)!
I'm using and following Scotch.io's advice: https://scotch.io/tutorials/declaring-angularjs-modules-for-minification
Any pointers/advice would be great!
Error
Controller JS
var fbcontrollers = angular.module('fbcontrollers', []);
fbcontrollers.controller('authCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
// Store User Data
function userData() {
var isNewUser = true;
var fire = new Firebase('https://courtyard-bridal.firebaseio.com/');
fire.onAuth(function(authData) {
if (authData && isNewUser) {
fire.child("users").child(authData.uid).set({
name: getName(authData),
email: getEmail(authData),
provider: authData.provider
});
}
function getName(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'facebook':
return authData.facebook.displayName;
}
}
function getEmail(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email;
case 'facebook':
return authData.facebook.email;
}
}
});
}
// Facebook Login
$scope.fblogin = function() {
var scope = {
scope: 'email'
};
$scope.auth.$authWithOAuthPopup('facebook', scope).then(function(auth) {
// Store Data
userData();
// Redirtect on Success
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
};
// Default Form Data
$scope.form = ({
'email': '',
'password': ''
});
// Login Form
$scope.login = function() {
var email = $scope.form.email;
var password = $scope.form.password;
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log(error);
});
};
// Register (Create User) Form
$scope.register = function() {
var email = $scope.form.email;
var password = $scope.form.password;
// Create User
$scope.auth.$createUser({
email: email,
password: password
}).then(function(Auth) {
// Store Data
userData();
// Login Created User
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
}).catch(function(error) {
console.log(error);
});
};
}]);
fbcontrollers.controller('dashCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
if($scope.user.provider === 'facebook') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.facebook.displayName;
$scope.email = $scope.user.facebook.email;
$scope.profile = $scope.user.facebook.profileImageURL;
} else if ($scope.user.provider === 'password') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.password.email.replace(/#.*/, '');
$scope.email = $scope.user.password.email;
$scope.profile = $scope.user.password.profileImageURL;
}
console.log($scope.user);
// Logout
$scope.logout = function() {
$scope.auth.$unauth();
$location.path('/auth');
};
}]);

I am pretty sure the problem is connected with the use of catch. Note that catch is a keyword in javascript, used in exception (error) handling. Promises use catch as a method name and that's a bit of a collision. In general it's safer to use it indirectly:
}).then(function(...) {
...
})['catch'](function(error) {
...
});
The same applies to the finally keyword.

Related

Firebase Authentication AUTHENTICATION_DISABLED error

I'm working with angularfire, where I just want to implement authentication with firebase, but for some reason it keeps spitting out AUTHENTICATION_DISABLED error whenever I make a authWithPassword and createUser
I cloned the skeleton code from https://github.com/firebase/angularfire-seed
And it works fine when I run it in my local machine, however, after adding more functionalities, it doesn't work anymore.
Here is my code for login.js
"use strict";
angular.module('myApp.login', ['firebase.utils', 'firebase.auth', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
controller: 'LoginCtrl',
templateUrl: 'login/login.html'
});
}])
.controller('LoginCtrl', ['$scope', 'Auth', '$location', 'fbutil', function($scope, Auth, $location, fbutil) {
d3.select('svg').remove();
d3.select('svg').remove();
$scope.email = null;
$scope.pass = null;
$scope.confirm = null;
$scope.createMode = false;
$scope.login = function(email, pass) {
$scope.err = null;
Auth.$authWithPassword({ email: email, password: pass }, {rememberMe: true})
.then(function(authData/* user */) {
console.log("Logged in as : " + authData.uid);
//$location.path('/account');
}, function(err) {
console.log("Error occured :(");
$scope.err = errMessage(err);
});
};
$scope.createAccount = function() {
$scope.err = null;
if( assertValidAccountProps() ) {
var email = $scope.email;
var pass = $scope.pass;
// create user credentials in Firebase auth system
Auth.$createUser({email: email, password: pass})
.then(function() {
// authenticate so we have permission to write to Firebase
return Auth.$authWithPassword({ email: email, password: pass });
})
.then(function(user) {
// create a user profile in our data store
var ref = fbutil.ref('users', user.uid);
return fbutil.handler(function(cb) {
ref.set({email: email, name: name||firstPartOfEmail(email)}, cb);
});
})
.then(function(/* user */) {
// redirect to the account page
console.log("User saved");
//$location.path('/account');
}, function(err) {
console.log("Error in createAccount");
$scope.err = errMessage(err);
});
}
};
function assertValidAccountProps() {
if( !$scope.email ) {
$scope.err = 'Please enter an email address';
}
else if( !$scope.pass || !$scope.confirm ) {
$scope.err = 'Please enter a password';
}
else if( $scope.createMode && $scope.pass !== $scope.confirm ) {
$scope.err = 'Passwords do not match';
}
return !$scope.err;
}
function errMessage(err) {
return angular.isObject(err) && err.code? err.code : err + '';
}
function firstPartOfEmail(email) {
return ucfirst(email.substr(0, email.indexOf('#'))||'');
}
function ucfirst (str) {
// inspired by: http://kevin.vanzonneveld.net
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}]);
Any insight on why it's not working would be very helpful. If there is any information about dependencies I'll post them right away.

how do you do a remember me or a stay signed in function with AngualarFire?

or using normal email and password method so that everytime i open the app i dont have to sign in. just go through..
.controller('signupCtrl', function(taskref, $scope, $firebaseArray, $state, $firebaseAuth) {
var fbref = $firebaseAuth(taskref);
$scope.createUser = function() {
taskref.$createUser({
email: $scope.email,
password: $scope.password
})
.then(function(authData) {
$state.go('settings');
};
})
with this sign in function with either googleAuth or email&password methods
.controller('googleSignUpCtrl', function(taskref, $scope, $firebaseObject, $firebaseAuth, $state) {
$scope.googleSignIn = function() {
var authData = taskref.getAuth();
taskref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
taskref.child("users").child(authData.uid).once("value", function(snapshot) {
var ifExists = snapshot.exists();
if (ifExists) {
$state.go('tabsController.pendingTasks');
console.log("user already exists");
} else {
$state.go('settings');
$scope.authData = authData;
}
});
}
}, {
remember: "sessionOnly",
scope: "email"
});
}
})

How can I store User data to my User node using AngularFir?

I Have created my login and have been able to allow users to signup now. However I want to store user data to my node. I added the code that I thought should work inside the addUser function. I have worked on this for ages but cannot find a solution. Could someone point me in the right direction as to what I am doing wrong?
The code I have written is below. Thanks in advance.
'use strict';
var theBigWeddingBook = angular.module('theBigWeddingBook');
theBigWeddingBook.controller('RegCtrl', function ($scope, $firebaseAuth, $firebaseObject)
{
var ref = new Firebase("https://the-big-wedding-book.firebaseio.com");
var reg = $firebaseAuth(ref);
$scope.user = {};
$scope.addUser = function() {
var username = $scope.user.email;
var password = $scope.user.password;
var uid = $scope.user.uid;
reg.$createUser({
email: username,
password: password
}).then(function(user) {
console.log('User has been successfully created!');
}).catch(function(error) {
console.log(error);
})
ref.child('user').child(user.uid).set(user).then(function(user) {
console.log('Data Saved Successfully!');
}).catch(function(error) {
console.log(error);
})
};
})
$scope.addUser = function() {
var uid = $scope.user.uid;
reg.$createUser({
email: $scope.user.email,
password: $scope.user.password
}).then(function(user) {
console.log('User has been successfully created!');
}).catch(function(error) {
console.log(error);
})
})
OR
$scope.addUser = function() {
var username = $scope.user.email;
var password = $scope.user.password;
var uid = $scope.user.uid;
reg.$createUser({
email: this.username,
password: this.password
}).bind(this)
.then(function(user) {
console.log('User has been successfully created!');
}).catch(function(error) {
console.log(error);
})
I got it working. I basically change it so that when Someone registers they are automatically logged in and then on authentication the data is saved to the user node as you can see below.
var theBigWeddingBook = angular.module('theBigWeddingBook');
theBigWeddingBook.controller('RegCtrl', function ($scope, $firebaseAuth, $firebaseObject) {
var ref = new Firebase("https://the-big-wedding-book.firebaseio.com");
var reg = $firebaseAuth(ref);
ref.onAuth(function(authData) {
if (authData) {
console.log("Authenticated with uid:", authData.uid);
} else {
console.log("Client unauthenticated.")
}
});
$scope.user = {};
$scope.addUser = function() {
var username = $scope.user.email;
var password = $scope.user.password;
var uid = $scope.user.uid;
reg.$createUser({
email: username,
password: password
}).then(function(user) {
console.log('User has been successfully created!');
return reg.$authWithPassword({ email: username, password: password });
}).catch(function(error) {
console.log(error);
})
};
ref.onAuth(function(authData) {
ref.child('user').child(authData.uid).set(authData).then(function(auth) {
console.log('Data Saved Successfully!');
}).catch(function(error) {
console.log(error);
})
})
})

router.post returns error "undefined is not a function" .Using mongo and express.js

I'm trying to buld an app using files from LINK .I found that posting is where the code breaks.Has express js changed or is it syntax mistake ?
The router.post breaks once it reaches Maid.registerMaid(new Maid({... .I'm able to make it work using .save() but could anyone explain why this callback is beaking ?
Putting the code below.. sorry, i'm a beginner in M.E.A.N
API.js
var express = require('express'),
router = express.Router(),
passport = require('passport');
User = require('../models/user.js');
Maid = require('../models/maid.js');
router.post('/AddMaid', function(req, res) {
console.log(req.body, req.body.FirstName,req.body.LastName);
Maid.registerMaid(new Maid({ FirstName: req.body.FirstName }), ({LastName: req.body.LastName}), function(err, account) {
if (err) {
return res.status(500).json({err : err})
}
return res.status(200).json({status: 'Registration successful!'});
});
});
Services.js
angular.module('myApp').factory('AuthService',['$q', '$timeout', '$http', function ($q, $timeout, $http) {
var user = null;
return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,
logout: logout,
register: register,
registerMaid: registerMaid
});
function registerMaid(Fname, Lname) {
var deferred = $q.defer();
$http.post('/maid/AddMaid', {
FirstName : Fname,
LastName : Lname
}).success(function(data, status) {
if (status === 200 && data.status) {
deferred.resolve();
} else {
deferred.reject();
}
}).error(function(data) {
debugger;
alert("Error in Services AddMaid");
deferred.reject();
});
return deferred.promise;
} }]);
Controllers.js
angular.module('myApp').controller('AddMaidController', ['$scope', '$http','$location', 'AuthService', function($scope, $http,$location, AuthService) {
console.log(AuthService.getUserStatus());
$scope.register = function () {
$scope.error = false;
$scope.disabled = true;
AuthService.registerMaid($scope.registerForm.FirstName,$scope.registerForm.LastName).then(function () {
$scope.disabled = false;
$scope.registerForm = {};
}).catch(function () {
$scope.error = true;
$scope.errorMessage = "Something went wrong!";
});
};}]);
maid.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Maid = new Schema({
First_Name: String,
Last_Name: String
});
module.exports = mongoose.model('maids', Maid);
First of all you globally defined ur User and Maid modules, that is not a good practice.
Error occurs because your Maid module (Maid model on server side, i.e. Nodejs) doesnt have registerMaid method. You need to use Maid.create instead

Making promises in modules

I try to make facebook registration module in my app. Facebook API is faster than my Angular controller, so promise should be used here. The problem is that $q seems to be an empty object and defer function is undefined.
module:
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'herecomesmycode');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$q', '$ionicPlatform', '$state', 'authService', 'datacontext', '$location'];
function FacebookAPI(UserService, $q, $ionicLoading, fbAppId, $state, authService, datacontext, $location) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
};
and here $q.defer is undefined:
function fbRegister() {
console.log($q.defer);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
Without using promise, it gets fast from API but all variables I want to fill with values from API, are initiated before API finishes and are undefined.
The whole module:
(function() {
'use strict';
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'myappkey');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$ionicPlatform', '$state', 'authService', '$q'];
function FacebookAPI(UserService, $ionicLoading, fbAppId, $state, authService, $q) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
}
function fbRegister() {
console.log($q);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
function getApiData() {
var formData = {};
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
function (result) {
if (result.gender == "male") {
result.gender = '1';
} else {
result.gender = '2';
}
formData = {
name: result.first_name + " " + result.last_name,
email: result.email,
birthday: new Date(result.birthday),
gender: result.gender
}
console.log("moduĊ‚" + formData);//here we have nice and neat data
return formData;
}, function(res) {
});
}
};
//This is the success callback from the login method
function fbLoginSuccess(response) {
var fbLogged = $q.defer();
if (!response.authResponse) {
fbLoginError("Cannot find the authResponse");
return;
}
var expDate = new Date(
new Date().getTime() + response.authResponse.expiresIn * 1000
).toISOString();
var authData = {
id: String(response.authResponse.userID),
access_token: response.authResponse.accessToken,
expiration_date: expDate
}
authService.facebookLogin(response.authResponse.accessToken).then(function() {
fbLogged.resolve(authData);
});
};
//This is the fail callback from the login method
function fbLoginError(error) {
var fbLogged = $q.defer();
fbLogged.reject(error);
alert(error);
$ionicLoading.hide();
};
//this method is to get the user profile info from the facebook api
function getFacebookProfileInfo() {
var info = $q.defer();
facebookConnectPlugin.api('/me', "",
function(response) {
info.resolve(response);
},
function(response) {
info.reject(response);
}
);
return info.promise;
}
//This method is executed when the user press the "Login with facebook" button
function fbLogin() {
if (!cordova) {
//this is for browser only
facebookConnectPlugin.browserInit(fbAppId);
}
//check if we have user's data stored
var user = UserService.getUser();
facebookConnectPlugin.getLoginStatus(function(success) {
//alert(JSON.stringify(success, null, 3));
if (success.status === 'connected') {
// the user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email", ["public_profile", "email"],
function(result) {
//alert("Result: " + JSON.stringify(result));
//alert(result.first_name);
})
var accessToken = success.authResponse.accessToken;
authService.facebookLogin(accessToken).then(function() {
$state.go('app.map');
}, function(err) { alert('auth failed: ' + JSON.stringify(err, null, 2)); });
} else {
//if (success.status === 'not_authorized') the user is logged in to Facebook, but has not authenticated your app
//else The person is not logged into Facebook, so we're not sure if they are logged into this app or not.
$ionicLoading.show({
template: 'Loging in...'
});
// permissions from facebook
facebookConnectPlugin.login([
'email',
'public_profile',
'user_about_me',
'user_likes',
'user_location',
'read_stream',
'user_photos'
], fbLoginSuccess, fbLoginError);
fbLogged.promise.then(function(authData) {
var fb_uid = authData.id,
fb_access_token = authData.access_token;
//get user info from FB
getFacebookProfileInfo().then(function(data) {
var user = data;
user.picture = "http://graph.facebook.com/" + fb_uid + "/picture?type=large";
user.access_token = fb_access_token;
//save the user data
//store it on local storage but it should be save it on a database
UserService.setUser(user);
$ionicLoading.hide();
$state.go('app.map');
});
});
}
});
}
})();

Resources