热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[Angular2Fire]Firebaseauth(Google,Github)

Todoauth,firstyouneedtogofirebase.console.comtoenabletheauthmethods,forexample,enablegoogl

To do auth, first you need to go firebase.console.com to enable the auth methods, for example, enable google, github...

[Angular2Fire] Firebase auth (Google, Github)

 

Enable goolge is quite simple, just one click, enable Github, Twitter, you need to do more configuration.

 

Follow the link: https://firebase.google.com/docs/auth/web/github-auth

 

After successfully enable it, we create a service to do the auth:

import {AuthProviders, FirebaseAuthState, FirebaseAuth} from "angularfire2";
import {Injectable} from "@angular/core";

@Injectable()
export class AuthService {

  private authState: FirebaseAuthState = null;

  constructor(public auth$: FirebaseAuth) {
    auth$.subscribe((state: FirebaseAuthState) => {
      this.authState = state;
    });
  }

  get authenticated(): boolean {
    return this.authState !== null;
  }

  get id(): string {
    return this.authenticated ? this.authState.uid : '';
  }

  signIn(provider: number): firebase.Promise {
    return this.auth$.login({provider})
      .catch(error => console.log('ERROR @ AuthService#signIn() :', error));
  }

  signInWithGithub(): firebase.Promise {
    return this.signIn(AuthProviders.Github)
  }

  signInWithGoogle(): firebase.Promise {
    return this.signIn(AuthProviders.Google);
  }

  signInWithTwitter(): firebase.Promise {
    return this.signIn(AuthProviders.Twitter);
  }

  signOut(): void {
    this.auth$.logout();
  }
}

 

Using it in controller: 

<section class="signup">
  <button md-button (click)="signInWithGoogle()">Googlebutton>
  <button md-button (click)="signInWithTwitter()">Twitterbutton>
  <button md-button (click)="signInWithGithub()">Githubbutton>
section>
import {Component, OnInit} from '@angular/core';
import {AuthService} from "../shared";
import {Router} from "@angular/router";

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {

  constructor(private auth: AuthService, private router: Router) {

  }

  ngOnInit() {
  }

  signInWithGithub(){
    this.auth.signInWithGithub()
      .then(this.postSignIn.bind(this))
  }

  signInWithTwitter(){
    this.auth.signInWithTwitter()
      .then(this.postSignIn.bind(this))
  }

  signInWithGoogle(){
    this.auth.signInWithGoogle()
      .then(this.postSignIn.bind(this))
  }

  postSignIn() {
    console.log("Auth id: ", this.auth.id);
    this.router.navigate(['/home']);
  }

}

 

Happy Auth!

[Angular2Fire] Firebase auth (Google, Github)


推荐阅读
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有