Issue
I'm doing an app with Ionic Framework and Firebase. I made a custom login to get data inside Firebase, but every single time the app is restarted I need to login again. How can I persist the login? The user should login the first time, and not need to do it again.
Here is my service:
(function() {
'use strict';
angular
.module('mytodo.login')
.factory('LoginService', LoginService);
LoginService.$inject = ['$state', '$ionicLoading', '$firebaseAuth', '$firebaseObject','$rootScope', '$timeout', 'fb', '$q'];
function LoginService($state, $ionicLoading, $firebaseAuth, $firebaseObject, $rootScope, $timeout, fb, $q){
var service = {
CustomLogin: CustomLogin,
GetCurrentUser: GetCurrentUser,
RegisterUser: RegisterUser,
};
return service;
function CustomLogin(email, password) {
if(email ==null | password == null){
console.log('Preencha todos os campos!');
return;
}
$ionicLoading.show({
showBackdrop: false,
template: '<p>Carregando...</p><ion-spinner icon="android" style="stroke: #1d9c9e;fill:#1d9c9e;"></ion-spinner>'
});
$firebaseAuth().$signInWithEmailAndPassword(email, password).then(function(authData) {
$rootScope.currentUser = GetCurrentUser(authData.uid);
$timeout(function() {
$ionicLoading.hide();
$state.go('tab.todo', {});
}, 1000);
}).catch(function(error) {
showToast();
$ionicLoading.hide();
console.log(error);
});
}
function showToast(){
ionicToast.show('Usuário ou senha inválido', 'middle', false, 1500);
}
function GetCurrentUser(userId) {
var query = fb.child('/users/' + userId);
var currentUser = $firebaseObject(query)
return currentUser;
}
function SaveUser(authData) {
console.log(authData.uid);
var deffered = $q.defer();
var uid = authData.uid;
var user = {
displayName: authData.displayName,
name: authData.displayName,
photoURL: authData.photoURL,
email: authData.email,
emailVerified: authData.emailVerified,
providerId: authData.providerData[0].providerId
};
var ref = fb.child('/users/' + uid);
ref.once("value")
.then(function(snapshot) {
if (snapshot.exists()) {
console.log('User already exists');
} else {
ref.set(user);
}
deffered.resolve(snapshot);
});
return deffered.promise;
};
function RegisterUser(user) {
var deffered = $q.defer();
$ionicLoading.show();
$firebaseAuth().$createUserWithEmailAndPassword(user.email, user.password).then(function(authData) {
var newUser = {
name: user.name,
email: user.email,
providerId: authData.providerData[0].providerId
};
var userId = authData.uid;
var ref = fb.child('/users/' + userId);
ref.once("value")
.then(function(snapshot) {
if (snapshot.exists()) {
//console.log('User already exists');
} else {
ref.set(newUser).then(function(user){
$rootScope.currentUser = GetCurrentUser(userId);
})
}
deffered.resolve(snapshot);
CustomLogin(user.email, user.password);
});
}).catch(function(error) {
$ionicLoading.hide();
var errorCode = error.code;
console.log(errorCode);
if(errorCode === 'auth/weak-password')
ionicToast.show('Erro, a senha precisa ter no mínimo 6 digitos.', 'middle', false, 3000);
if(errorCode === 'auth/email-already-in-use')
ionicToast.show('Erro, o email: ' + user.email + ' já existe em nossa base de dados.', 'middle', false, 3000);
})
return deffered.promise;
};
}
})();
Solution
I've figured out how to do this. Maybe it's not the most correct anwser for it, but it worked for me. I used localSotrage to store the username and password. I could store the tolken as well, but I want to create a "remember password" screen. When I do my first login I do this in my service.
service.js when I store the user data;
localStorage.setItem("uPassword",password);
localStorage.setItem("uEmail",email);
controller.js if statement:
if(localStorage.getItem("uEmail")!==undefined && localStorage.getItem("uPassword")!==undefined) {
LoginService.CustomLogin(localStorage.getItem("uEmail"),localStorage.getItem("uPassword"))
}
Answered By - Lucas Gaspar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.