[Angular2Fire] Firebase auth (Google, Github)

To do auth, first you need to go firebase.console.com to enable the auth methods, for example, enable 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<FirebaseAuthState> {
    return this.auth$.login({provider})
      .catch(error => console.log('ERROR @ AuthService#signIn() :', error));
  }

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

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

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

  signOut(): void {
    this.auth$.logout();
  }
}
复制代码

 

Using it in controller: 

<section class="signup">
  <button md-button (click)="signInWithGoogle()">Google</button>
  <button md-button (click)="signInWithTwitter()">Twitter</button>
  <button md-button (click)="signInWithGithub()">Github</button>
</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!

posted @   Zhentiw  阅读(968)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示