district-politics/projects/speech-statistics/src/app/auth/auth.service.ts

44 lines
1.1 KiB
TypeScript

import {Injectable} from '@angular/core';
import {FirebaseService} from '../firebase/firebase.service';
import {User, UserCredential} from 'firebase/auth';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private currentUser: User | null = null;
constructor(private firebase: FirebaseService,
private router: Router) {
}
public getUser(): User|null {
return this.currentUser;
}
public isLoggedIn(): boolean {
return this.currentUser != null;
}
public login(email: string, password: string, redirectUrl: string) {
this.firebase.signIn(email, password)
.then((userCredential: UserCredential) => {
this.currentUser = userCredential.user;
this.router.navigateByUrl(redirectUrl);
})
.catch((error) => {
console.error(error.message());
});
}
public logout(redirectUrl: string) {
this.firebase.signOutCurrentUser()
.then(() => {
this.currentUser = null;
this.router.navigateByUrl(redirectUrl);
});
}
}