logout() { this.soundService.tick.play(); const currentUser = firebase.auth().currentUser; firebase.auth().signOut() .then(() => { this.vm.currentState = this.vm.states.NOT_LOGGED_IN; this.vm.user = { displayName: null, email: null }; this.vm.loginData = { email: '', password: '' }; this.vm.signupData = { email: '', password: '', userName: '' }; this.$scope.$apply(); }) .then(() => { this.socketService.lobbiesSocket.emit('signOutUser', currentUser.uid); }) .catch(err => { console.log('Logout error', err), this.toastService.errorToast( 'Logout error', ' ' ); }); }
return new Promise((resolve, reject) => { var user = firebase.auth().currentUser; if (user) { // ensure we have current user var user = firebase.auth().currentUser; user.updateProfile({ displayName: u.displayName, photoUrl: '' // field for photo url }).then(data => { // renew user fetchUserObject(firebase.auth().currentUser).then(user => { resolve(user); }) }, error => { reject({ errorCode: error.code, errorMessage: error.message }) }) } else { resolve(null) } })
// Install access to firebase services as global properties export default function install (Vue) { // Initialize the Firebase Application firebase.initializeApp({ apiKey: 'AIzaSyDtJsucR1agKmbNxCvV3_yrT9-zlWWGpeo', authDomain: 'navy-app.firebaseapp.com', databaseURL: 'https://navy-app.firebaseio.com', storageBucket: 'navy-app.appspot.com' }) // Extend Vue with Firebase Object.defineProperties(Vue.prototype, { $firebase: { get () { return firebase } }, $database: { get () { return firebase.database() } }, $auth: { get () { return Object.assign(firebase.auth(), { signIn () { return firebase.auth().signInWithRedirect(provider) } }) } } }) }
const prepareDocForCreate = doc => { // timestamps doc.createdBy = Firebase.auth().currentUser ? Firebase.auth().currentUser.uid : null doc.createdOn = Firebase.firestore.Timestamp.now() return doc }
.catch((error) => { if (error.code === "auth/email-already-in-use") { console.log('User recognised, logging in'); firebase.auth().signInWithEmailAndPassword(email, password) .catch((error) => { ReactGA.event({ category: 'Error', action: 'Login', label: 'Failed to login password user' }); UiApi.showNewNotification({ message: error.message, }); UiApi.loaded(); console.error('Failed to login user.', error); }); } else { ReactGA.event({ category: 'Error', action: 'Registration', label: 'Failed to create user' }); UiApi.showNewNotification({ message: error.message, }); UiApi.loaded(); console.error('Failed to create user.', error); } });
return new Promise((resolve, reject) => { let provider = FireBaseTools.getProvider(p); firebase.auth().signInWithRedirect(provider).then(function(result) { if(result.credential) { let token = result.credential.accessToken; } let user = result.user; fetchUserObject(user).then(user => { resolve(user); }) }).catch(function(error) { let email = error.email; let credential = error.credential; reject({ errorCode: error.code, errorMessage: error.message }) }); })
constructor($scope, $uibModalInstance, currentSelectedPlayer, selectedPlayers, multiplayer, socketService) { this.vm = this; this.$scope = $scope; this.$uibModalInstance = $uibModalInstance; this.socketService = socketService; this.vm.currentSelectedPlayer = currentSelectedPlayer ? Object.assign({}, currentSelectedPlayer) : null; this.vm.oldAvatar = currentSelectedPlayer ? currentSelectedPlayer.avatar : null; this.vm.selectedPlayers = selectedPlayers.filter(x => x !== undefined); this.multiplayer = multiplayer; this.vm.avatars = avatars; this.vm.selectAvatar = this.selectAvatar; this.vm.ok = this.ok; this.vm.selectAvatarAndClose = this.selectAvatarAndClose; this.vm.avatarIsSelected = this.avatarIsSelected; this.vm.avatarIsTaken = this.avatarIsTaken; if (this.vm.currentSelectedPlayer && this.vm.currentSelectedPlayer.userName) { this.vm.currentSelectedPlayer.name = this.vm.currentSelectedPlayer.userName; } this.vm.takenAvatars = this.vm.selectedPlayers.map(x => x.avatar); // PUBLIC FIELDS $('.mainWrapper').css('filter', 'blur(5px)'); $('.mainWrapper').css('-webkit-filter', 'blur(5px)'); setTimeout(() => { if (this.vm.currentSelectedPlayer && this.vm.currentSelectedPlayer.avatar && this.vm.currentSelectedPlayer.avatar.svg) { loadSvgIntoDiv(this.vm.currentSelectedPlayer.avatar.svg, '#selectedCharacterSvg'); } }, 50); firebase.auth().onAuthStateChanged(user => { if (user) { firebase.database().ref('users/' + user.uid).on('value', snapshot => { const user = snapshot.val(); if (user && user.characters) { user.characters.forEach(c => { this.vm.avatars[c.name] = c; this.vm.avatars[c.name].customCharacter = true; this.vm.avatars[c.name].bgColor = getRandomColor(); }); } setTimeout(() => { this.loadSavedCharacterPortraits(); }, 500); }); } }); if (this.multiplayer) { // Is multiplayer game this.socketService.gameSocket.on('updatedPlayers', players => { this.vm.selectedPlayers = players.filter(x => x !== undefined); this.vm.takenAvatars = this.vm.selectedPlayers.map(x => x.avatar); this.$scope.$apply(); }); } }
currentUser.logOut = function() { firebase.auth().signOut().then(function() { console.log("logged out"); }, function(error) { console.log("failed to log out"); }); }
/** * Write FCM messagingToken to user profile * @param {String} messagingToken - Token to be written to user profile */ function updateUserProfileWithToken(messagingToken) { const currentUserUid = firebase.auth().currentUser && firebase.auth().currentUser.uid if (!currentUserUid) { return } return firebase .firestore() .collection('users') .doc(currentUserUid) .update({ messaging: { mostRecentToken: messagingToken, updatedAt: firebase.firestore.FieldValue.serverTimestamp() } }) }
}).then(data => { // renew user fetchUserObject(firebase.auth().currentUser).then(user => { resolve(user); }) }, error => {
() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { unsubscribe(); resolve({ user: createUser(user), }); }); },
const prepareDocForUpdate = doc => { // timestamps doc.updatedBy = Firebase.auth().currentUser ? Firebase.auth().currentUser.uid : null doc.updatedOn = Firebase.firestore.Timestamp.now() // don't save the id as part of the document delete doc.id // don't save values that start with an underscore (these are calculated by the backend) Object.keys(doc).forEach( key => { if (key.indexOf('_') === 0) { delete doc[key] } }) return doc }
export const setUserFireStore = user => { const id = firebase.auth().currentUser.uid; const newUser = { ...user, admin: false, id, }; return usersCollection.doc(id).set(newUser).then(() => newUser) };
return new Promise((resolve, reject) => { firebase.auth().signOut().then(function() { // Sign-out successful and clear data. localStorage.clear(); resolve({ success: 1, message: "logout" }); }); });
return ensureAuth().then(() => { const user = firebase.auth().currentUser; return user .delete() .then(noReturnValue) .catch(error => { throw new FirebaseProviderError(error); }); });
constructor() { app.initializeApp(config); this.auth = app.auth(); this.db = app.database(); this.store = firebase.firestore(); this.store.settings({ timestampsInSnapshots: true }); }
.then(snapshot => { let users = snapshot.val(); users = users ? users : []; const existingUser = Object.values(users).find(user => user.userName === this.vm.signupData.userName); if (existingUser) { // username already exists throw 'username-taken'; } else { return firebase.auth().createUserWithEmailAndPassword(this.vm.signupData.email, this.vm.signupData.password); } })
.then(() => { const user = firebase.auth().currentUser; user.updateProfile({ displayName: this.vm.signupData.userName }); this.toastService.successToast('', 'You have been registered successfully!'); this.vm.signupData = { email: '', password: '', userName: '' }; })
return new Promise((resolve, reject) => { let currentUser = firebase.auth().currentUser if (currentUser) { resolve(currentUser) return } firebase .auth() .signInWithEmailAndPassword('*****@*****.**', 'asdfasdf') .then(() => { currentUser = firebase.auth().currentUser console.log('firebase.auth().currentUser: '******'currentUser: '******'err: ', err) reject(err) }) })
firebase.auth().onAuthStateChanged(user => { //resolve(firebase.auth().currentUser); if (user) { fetchUserObject(firebase.auth().currentUser).then(user => { resolve(user); }) } else { resolve(null) } });
return new Promise((resolve, reject) => { if (redirect) { firebase.auth().signInWithRedirect(provider); resolve(); } else { firebase .auth() .signInWithPopup(provider) .then( result => { const user = createUser(result.user); user.accessToken = result.credential.accessToken; resolve(createUser(user)); }, error => { reject(new FirebaseProviderAuthenticationError(error)); } ); } });
const logout = () => { firebase.auth().signOut().then(() => { // Sign-out successful. store.dispatch(logoutSuccess()); }, (error) => { ReactGA.event({ category: 'Error', action: 'Logout', label: 'Failed to log out' }); console.error(error); }); }
const onAuth = () => { console.log('Setting up listener for auth state change'); firebase.auth().onAuthStateChanged((userOb) => { console.log('Auth state changed'); if (userOb) { console.log('got user object from state change, authenticating..'); fetchUser(userOb); } else { console.log('null user object, sending to login'); browserHistory.push('/login'); } }); }
return ensureAuth().then(() => firebase .auth() .signOut() .then(() => { for (const key in window.localStorage) { if (key.indexOf('firebase:authUser') === 0) { window.localStorage.removeItem(key); } } }) .catch(error => { throw new FirebaseProviderError(error); })
return new Promise((resolve, reject) => { var auth = firebase.auth(); auth.sendPasswordResetEmail(email).then((data) => { resolve({ message: 'Email sent', errorCode: null }) }, error => { // An error happened. reject({ errorCode: error.code, errorMessage: error.message }) }); });
const logIn = () => { ReactGA.event({ category: 'User', action: 'Log in', }) let provider = new Firebase.auth.GoogleAuthProvider() return Firebase.auth() .signInWithRedirect(provider) .then( result => { console.log(`logged in as ${result.user.displayName}`) }).catch( error => { console.error('could not sign in', error) }) }
return new Promise((resolve, reject) => { firebase.auth().signInWithEmailAndPassword(user.email, user.password).then(user => { // save user to localstorage fetchUserObject(user).then(user => { resolve(user); }) }).catch(error => { reject({ errorCode: error.code, errorMessage: error.message }) }); })
ensureAuth.then(() => { firebase .auth() .createUserWithEmailAndPassword(email, password) .then( () => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { unsubscribe(); resolve({ user: createUser(user), }); }); }, error => { reject(new FirebaseProviderAuthenticationError(error)); } ); });
setNewPassword() { this.vm.setNewPasswordLoading = true; if (!this.vm.currentPassword) { this.toastService.errorToast('', 'You must enter your current password'); return; } if (!this.vm.newPassword1 || !this.vm.newPassword2) { this.toastService.errorToast('', 'No new password entered'); return; } if (this.vm.newPassword1 !== this.vm.newPassword2) { this.toastService.errorToast('', 'The passwords entered don\'t match'); return; } const credential = firebase.auth.EmailAuthProvider.credential( this.vm.user.email, this.vm.currentPassword ); const user = firebase.auth().currentUser; user.reauthenticateAndRetrieveDataWithCredential(credential).then(() => { return user.updatePassword(this.vm.newPassword1); }).then(() => { this.toastService.successToast('', 'Your password has been changed successfully!'); this.vm.currentPassword = ''; this.vm.newPassword1 = ''; this.vm.newPassword2 = ''; this.vm.setNewPasswordLoading = false; this.$scope.$apply(); }).catch(error => { this.vm.setNewPasswordLoading = false; this.$scope.$apply(); if (error.code === 'auth/wrong-password') { this.toastService.errorToast('', 'Wrong current password!'); } else if (error.code === 'auth/weak-password') { this.toastService.errorToast('', 'That new password is too weak'); } }); }
login() { this.soundService.tick.play(); firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) .then(() => { firebase.auth().signInWithEmailAndPassword(this.vm.loginData.email, this.vm.loginData.password) .then(result => { console.log(result); this.vm.currentState = this.vm.states.LOGGED_IN; this.setUser(result.user); this.vm.loginData = { email: '', password: '' }; this.$scope.$apply(); }) .catch(err => { console.log('Login error', err); if (err.code === 'auth/invalid-email') { this.toastService.errorToast( 'Login error!', 'The email entered is not valid' ); } else if (err.code === 'auth/user-disabled') { this.toastService.errorToast( 'Login error!', 'The user has been disabled' ); } else if (err.code === 'auth/user-not-found') { this.toastService.errorToast( 'Login error!', 'No user with this email found' ); } else if (err.code === 'auth/wrong-password') { this.toastService.errorToast( 'Login error!', 'Incorrect password' ); } }); }) .catch(error => { console.log('setPersistence error', error); }); }