Created
May 13, 2020 19:40
-
-
Save feliperfranco/50b7d29aa81f144591f32938d8a16e35 to your computer and use it in GitHub Desktop.
Autenticação com Firebase usando AngularFire
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { AngularFireAuth } from '@angular/fire/auth'; | |
import { AngularFireDatabase } from '@angular/fire/database'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class UsuarioService { | |
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) { } | |
criarConta(usuario: any) { | |
return new Promise((resolve, reject) => { | |
this.afAuth.auth.createUserWithEmailAndPassword(usuario.email, usuario.senha) | |
.then((userCredential: firebase.auth.UserCredential) => { | |
userCredential.user.updateProfile({ displayName: usuario.nome, photoURL: '' }); | |
resolve(); | |
}) | |
.catch((error: any) => { | |
reject(this.handlerError(error)); | |
}); | |
}); | |
} | |
login(email: string, senha: string) { | |
return new Promise((resolve, reject) => { | |
this.afAuth.auth.signInWithEmailAndPassword(email, senha) | |
.then(() => { | |
resolve(); | |
}) | |
.catch((error: any) => { | |
reject(this.handlerError(error)); | |
}); | |
}); | |
} | |
logout() { | |
return this.afAuth.auth.signOut(); | |
} | |
enviarEmailResetarSenha(email: string) { | |
return new Promise((resolve, reject) => { | |
this.afAuth.auth.sendPasswordResetEmail(email) | |
.then(() => { | |
resolve(); | |
}) | |
.catch((error: any) => { | |
reject(this.handlerError(error)); | |
}); | |
}); | |
} | |
handlerError(error: any) { | |
let mensagem = ''; | |
if (error.code == 'auth/email-already-in-use') { | |
mensagem = 'O e-mail informado já está sendo usado.'; | |
} else if (error.code == 'auth/invalid-email') { | |
mensagem = 'O e-mail informado é inválido.'; | |
} else if (error.code == 'auth/operation-not-allowed') { | |
mensagem = 'A autenticação por email e senha não está habilitada'; | |
} else if (error.code == 'auth/weak-password') { | |
mensagem = 'A senha utilizada é muito fraca. Por favor escolha outra senha.'; | |
} else if (error.code == 'auth/user-disabled') { | |
mensagem = 'O usuário está desabilitado, por favor contact o administrador.'; | |
} else if (error.code == 'auth/user-not-found' || error.code == 'auth/wrong-password') { | |
mensagem = 'O usuario/senha inválido(s)'; | |
} | |
return mensagem; | |
} | |
getDadosUsuario() { | |
const user = { name: '', email: '' }; | |
if (this.afAuth.auth.currentUser) { | |
user.name = this.afAuth.auth.currentUser.displayName, | |
user.email = this.afAuth.auth.currentUser.email | |
} | |
return user; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment