Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { AngularFireAuth } from 'angularfire2/auth';
- import { Router, CanActivate } from '@angular/router';
- import { firebase } from '@firebase/app';
- import { AngularFireDatabase } from 'angularfire2/database';
- import { User } from '../../models/user';
- import { Observable } from 'rxjs/Observable';
- import { CompetitionService } from '../competitionService/competition.service';
- import { UserService } from '../userService/user.service';
- @Injectable()
- export class AuthService implements CanActivate {
- defaultRole = 'player';
- constructor(
- public afAuth: AngularFireAuth,
- private router: Router,
- private db: AngularFireDatabase,
- private competitionService: CompetitionService,
- private userService: UserService
- ) {
- }
- get authenticated(): boolean {
- return this.userService.getLoggedInUserSource() !== null;
- }
- get currentUser(): any {
- return this.authenticated ? this.userService.getLoggedInUserSource() : null;
- }
- googleLogin() {
- const promise = new Promise((resolve, reject) => {
- const provider = new firebase.auth.GoogleAuthProvider();
- provider.addScope('profile');
- provider.addScope('email');
- firebase
- .auth()
- .signInWithPopup(provider)
- .then(result => {
- if (result.user) {
- const token = result.credential.accessToken;
- this.doesUserExist(result.user, resolve);
- } else {
- reject();
- }
- });
- });
- return promise;
- }
- doesUserExist(user, resolve) {
- this.userService.getAllUsersObservable().subscribe(dbUsers => {
- let alreadyExist = false;
- for (const dbUser of dbUsers) {
- const cast = dbUser as User;
- if (cast.uid === user.uid) {
- alreadyExist = true;
- this.userService.setLoggedInUser(cast);
- }
- }
- if (alreadyExist === false) {
- const newUser = new User(user.uid, user.displayName, this.defaultRole);
- this.db.list('/users/').push(newUser);
- this.userService.setLoggedInUser(newUser);
- }
- resolve();
- });
- }
- signOut() {
- const promise = new Promise((resolve, reject) => {
- this.afAuth.auth.signOut();
- this.userService.setLoggedInUser(null);
- this.router.navigate(['/']);
- });
- return promise;
- }
- canActivate(): boolean {
- if (this.userService.getLoggedInUserSource() == null) {
- this.router.navigate(['/']);
- return false;
- }
- return true;
- }
- isAdmin(): boolean {
- if (this.userService.getLoggedInUserSource() != null && this.userService.getLoggedInUserSource().role === 'admin') {
- return true;
- } else {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement