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.
Related
I'm trying to use Django REST Framework's token-based authentication scheme with an AngularJS client. I'm able to successfully retrieve and store a token from the server, but I'm having trouble figuring out how to attach the token to subsequent responses. Here's the service that manages logging in and saving a token:
angular.module('mymodule')
.factory('loginService', function ($http, $window) {
var api_base = "link to my api";
return {
async: function() {
return $http.get(api_base + "authentication/login/").then(function (response) {
return response.data;
}, function errorCallback(response) {
console.log("Testuser API Error: " + response);
return null;
});
},
loginUser: function(email, password) {
self.saveToken = function(auth_token) {
$window.localStorage['jwtToken'] = auth_token;
};
self.getToken = function() {
return $window.localStorage['jwtToken'];
};
console.log("...to listing " + email);
return $http.post("link to my api/authentication/login/", {
email: email,
password: password
}).then(function(response) {
if(response.config.url.indexOf("link to my api") === 0 && response.data.auth_token) {
self.saveToken(response.data.auth_token);
}
return response;
});
}
};
});
Here's the controller associated with the above service to handle logging in:
angular.module('mymodule').controller("LoginController", function(loginService, $scope) {
$scope.loginusers = [];
$scope.refresh = function() {
loginService.async().then(function(data) {
if (data == null)
return;
console.log(data[0]["email"]);
$scope.loginusers = [];
for (var loginuser in data)
$scope.loginusers.push(loginuser);
});
};
$scope.refresh();
// Test //
$scope.loginTestUser = function() {
console.log("something...");
loginService.loginUser(
$scope.email,
$scope.password
)
};
//////
});
And here's the service that I'd like to use for displaying a user's profile after the token is sent back to the server.
angular.module('mymodule').factory("profileService", function($http, loginService, $httpProvider) {
var api_base = "link to my api";
$httpProvider.interceptors.push(function($q, $window) {
return {
'request': function(config) {
config.headers['Token'] = $window.localStorage['jwtToken'];
return config;
}
};
});
return {
async: function() {
return $http.get(api_base + "authentication/me/").then(function (response) {
return response.data[0];
}, function errorCallback(response) {
console.log("Profile API Error: " + response);
return null;
});
}
};
});
How should I be approaching this?
Once users login, a json web token is created and then saved in local storage. However, my express middleware is returning message: 'No token provided'. Once i hit refresh in the browser, then it detects the token properly and the user is shown as logged in. I imagine this is a simple fix but I have not been able to figure it out. Any ideas please?
Angular Controller:
angular.module('mainController', ['authService'])
.controller('mainCtrl', function($http, $timeout, $location, Auth, $rootScope, $route) {
var app = this;
$rootScope.$on('$routeChangeStart', function() {
app.loggedIn = Auth.isLoggedIn();
Auth.getUser().then(function(data) {
app.user = data.data;
console.log(app.user);
});
});
app.doLogin = function(userData) {
app.user = false;
app.loading = true;
app.errorMsg = false;
Auth.doLogin(app.userData).then(function(data) {
if (data.data.success) {
app.loading = false;
app.successMsg = data.data.message + '...Redirecting';
$timeout(function() {
$location.path('/');
}, 2000);
} else {
app.loading = false;
app.errorMsg = data.data.message;
}
});
};
Angular Authentication Service:
angular.module('authService', [])
.factory('Auth', function($http, AuthToken, $q) {
var authFactory = {};
authFactory.doLogin = function(userData) {
return $http.post('/api/authenticate', userData).then(function(data) {
AuthToken.setToken(data.data.token);
return data;
});
};
authFactory.doLogout = function() {
AuthToken.setToken();
}
authFactory.isLoggedIn = function() {
if (AuthToken.getToken()) {
return true;
} else {
return false;
}
};
authFactory.getUser = function() {
if (AuthToken.getToken()) {
return $http.get('/api/me');
} else {
return $q.reject({ message: 'User has no token' });
}
}
return authFactory;
})
.factory('AuthToken', function($window) {
var authTokenFactory = {};
authTokenFactory.setToken = function(token) {
if (token) {
$window.localStorage.setItem('token', token);
} else {
$window.localStorage.removeItem('token');
}
};
authTokenFactory.getToken = function() {
return $window.localStorage.getItem('token');
};
return authTokenFactory;
})
.factory('AuthInterceptor', function($location, $q, AuthToken) {
var AuthInterceptorFactory = {};
var token = AuthToken.getToken();
AuthInterceptorFactory.request = function(config) {
if (token) config.headers['x-access-token'] = token;
return config;
};
AuthInterceptorFactory.responseError = function(response) {
if (response.status === 403) {
AuthToken.setToken();
$location.path('/login');
}
return $q.reject(response);
};
return AuthInterceptorFactory;
});
Angular Config File to Attach Tokens to all requests:
angular.module('userApp', ['appRoutes', 'userControllers', 'mainController', 'authService'])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
Express:
// middleware to check for tokens
router.use(function(req, res, next) {
var token = req.body.token || req.body.query || req.headers['x-access-token'];
if (token) {
jwt.verify(token, secret, function(err, decoded) {
if (err) {
res.json({ success: false, message: 'failed to authenticate token' });
} else {
req.decoded = decoded;
next();
}
});
} else {
res.json({ success: false, message: 'No token provided'});
}
});
// Route to get the current user
router.get('/me', function(req, res) {
res.send(req.decoded);
});
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"
});
}
})
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.
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');
});
});
}
});
}
})();