在使用Firebaseui和Angular时,可以添加一个限制功能,使浏览自由,但需要进行身份验证才能写入
使用Firebaseui和Angular,对浏览进行自由访问,对写入进行限制并需要进行身份验证的功能添加。
之前的回合:我想要創建一個新的Angular項目 – 我想要使用material2和Service Worker
前前前次:在Angular项目中配置并引入Firebase
上次之前:通过Angular + Firebase实现CRUD功能。
我想使用Firebase的FireAuth来限制管理员页面。
在博客文章或其他页面的末尾通常会有一个评论栏。这些评论通常可以被任何人阅读,但要发表评论必须进行注册并通过图片验证。
我试用了Firebaseui,因为它非常容易实现,这是一个备忘录。
FirebaseUI是什么

Firebase的配置

Twitter、Facebook以及GitHub都需要API密钥,你知道如何获取它们吧。(虽然我不用Facebook)
为了预防起见,
例如:在Twitter的情况下
请访问 https://developer.twitter.com/apps 并点击”创建应用”按钮以创建新的应用程序。



我认为Facebook等类似的平台也是类似的工作。
安装 firebaseui-angular
然后在本地项目中使用npm install安装firebaseui-angular。
C:\projectA>npm install firebaseui-angular --save
firebaseui-angular需要添加FirebaseUI核心库和AngularFire2库来处理Firebase。
C:\projectA>npm install firebase firebaseui @angular/fire firebaseui-angular --save
会弹出这样的错误或者警告。
+ firebaseui-angular@3.4.1
updated 1 package and audited 40405 packages in 37.33s
found 10 vulnerabilities (2 low, 8 high)
run `npm audit fix` to fix them, or `npm audit` for details
按照被说的那样,运行npm audit fix。
C:\projectA>npm audit fix
创建组件
C:\projectA>ng g component compoent/LoginFirebaseUI
可以任何一个名字都可以。在这里我们取名为LoginFirebaseUI。
在app.module.ts文件中添加。
这里是关键,在添加模块时要确保没有泄漏。
//Angularモジュールのインポート
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {HttpClient, HttpClientModule} from '@angular/common/http';
import { environment } from '../environments/environment';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { FirebaseUIModule, firebase, firebaseui } from 'firebaseui-angular'; // 追加.FirebaseUIのモジュール
//Material2モジュールのインポート
…省略…
// 作成したコンポーネントのインポート
import {RootComponent} from './component/root/root.component';
import { RouterModule } from '@angular/router';
import { AppRoutes } from './app.route';
import { HomeComponent } from './component/home/home.component';
import { LoginComponent } from './component/login/login.component';
import { LoginFirebaseUIComponent } from './component/login-firebase-ui/login-firebase-ui.component'; // 追加.FirebaseUIの処理用コンポーネント
// FirebaseUI初期化コード
const firebaseUiAuthConfig: firebaseui.auth.Config = {
autoUpgradeAnonymousUsers: false, // 匿名認証ユーザー自動アップグレード
signInFlow: 'popup', // redirect or popup
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
{
scopes: [
'public_profile',
'email',
'user_likes',
'user_friends'
],
customParameters: {
'auth_type': 'reauthenticate'
},
provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID
},
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID,
{
requireDisplayName: false,
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID
},
firebase.auth.PhoneAuthProvider.PROVIDER_ID,
firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
tosUrl: 'http://localhost:6200/TOS', // 'Team Of Serviceのリンク先URL'
privacyPolicyUrl: 'プライバシーポリシーのURL',
signInSuccessUrl: 'http://localhost:6200/home',
credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
siteName: 'projectA',
};
//アプリで使用するモジュール定義
@NgModule({
//モジュール
imports: [
BrowserModule,
BrowserAnimationsModule,
ReactiveFormsModule,
FormsModule,
…Material2関連省略…
//ルーターの定義
RouterModule.forRoot(AppRoutes),
//Firebaseの定義
AngularFireModule.initializeApp(environment.firebase), // 追加
AngularFirestoreModule, // 追加.Firestore用モジュール
AngularFireAuthModule, // 追加.angularfireのAuth用モジュール
FirebaseUIModule.forRoot(firebaseUiAuthConfig), // FirebaseUI用のモジュール
// 作成したコンポーネント
declarations: [
RootComponent,
HomeComponent,
LoginFirebaseUIComponent,
],
// DIするサービス
providers: [
],
// 初めに呼び出すコンポーネント
bootstrap: [RootComponent]
})
export class AppModule {
}
以下是对于FirebaseUI初始化代码中的”const firebaseUiAuthConfig: firebaseui.auth.Config = {…}”部分的描述。说实话,这段代码更像是列举配置值而不是处理代码。但是通过查看,大致可以明白正在设置哪些内容。
例如,我现在不会使用Facebook和Github,所以我将将其注释掉。

app.module.ts —> 应用模块.ts
// FirebaseUI初期化
const firebaseUiAuthConfig: firebaseui.auth.Config = {
autoUpgradeAnonymousUsers: false, // 匿名認証ユーザー自動アップグレード
signInFlow: 'popup', // redirect or popup
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
/*{
scopes: [
'public_profile',
'email',
'user_likes',
'user_friends'
],
customParameters: {
'auth_type': 'reauthenticate'
},
provider: firebase.auth.FacebookAuthProvider.PROVIDER_ID
},
*/
firebase.auth.TwitterAuthProvider.PROVIDER_ID,
// firebase.auth.GithubAuthProvider.PROVIDER_ID,
{
requireDisplayName: false,
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID
},
firebase.auth.PhoneAuthProvider.PROVIDER_ID,
firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
/*
tosUrl: 'aaa', // 'Team Of Serviceのリンク先URL'
privacyPolicyUrl: 'プライバシーポリシーのURL',
signInSuccessUrl: 'http://localhost:6200/home',
credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
siteName: 'projectA',
*/
};
应用样式
为了避免显示错误,需要应用CSS样式。请在Angular首先加载的index.html文件的标签中加入样式。
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.0.0/firebaseui.css" />
直接复制粘贴。
显示LoginFirebaseUIComponent
如果您使用app.component.html,您只需在某个地方插入,然后运行’ng serve -o’命令,屏幕会显示”login-firebase-ui works!”。
我的ProjectA使用bootstrap:[RootComponent],因此修改了app.routes.ts,使LoginFirebaseUIComponent首先显示出来。
app的路由.ts
//====================
// ルータ定義
//====================
import {Routes} from "@angular/router";
import {RootComponent} from "./component/root/root.component";
import { HomeComponent } from './component/home/home.component';
import { LoginFirebaseUIComponent } from './component/login-firebase-ui/login-firebase-ui.component'; // 追加
//urlパスと表示するコンポーネントの関連づけ
export const AppRoutes: Routes = [
{path: "", component: LoginFirebaseUIComponent}, // 変更
{path: "login", component: LoginFirebaseUIComponent}, // 変更
{path: "home", component: HomeComponent},
];
哦,顺便说一下,在RootComponent的HTML中有以下的组件插入标签。
路由组件.html
<!--各コンポーネントを入れる枠内-->
<div style="position: absolute;top:86px;left:0px; width: 100%; max-width:1024px; ">
<router-outlet></router-outlet>
</div>
RootComponent是一个在所有页面上显示头部和底部的组件,这只是个旁白。
的说明省略不提

家庭.component.html
…省略…
<div>
<app-login-firebase-ui></app-login-firebase-ui>
</div>
当然,目前仅仅是显示“login-firebase-ui works!”而已。因此,需要编辑login-firebase-ui.component.ts和login-firebase-ui.component.html文件。
登录-firebase-ui.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Observable } from 'rxjs';
import { FirebaseUISignInSuccessWithAuthResult, FirebaseUISignInFailure } from 'firebaseui-angular';
@Component({
selector: 'app-login-firebase-ui',
templateUrl: './login-firebase-ui.component.html',
styleUrls: ['./login-firebase-ui.component.css']
})
export class LoginFirebaseUIComponent implements OnInit {
user: Observable<firebase.User>;
constructor(private angularFireAuth: AngularFireAuth) { }
ngOnInit() {
this.user = this.angularFireAuth.authState;
}
// ログアウト
async logout() {
this.angularFireAuth.auth.signOut();
}
// 成功時のコールバック
successCallback(signInSuccessData: FirebaseUISignInSuccessWithAuthResult) {
console.log(signInSuccessData);
}
// 失敗時のコールバック
async errorCallback(errorData: FirebaseUISignInFailure) {
console.log(errorData);
}
}
直接复制粘贴。
登陆-firebase-ui.component.html
这可以以简洁的方式表达如下。
<firebase-ui
(signInSuccessWithAuthResult)="successCallback($event)"
(signInFailure)="errorCallback($event)">
</firebase-ui>
然而,由于缺少登出按钮,因此需要在已认证时添加登出按钮,在未认证时与firebaseui的登录页面一起添加注意事项。我们要创建一个login-firebase-ui.component.html文件。
登录-firebase-ui.component.html
<div *ngIf="(user | async) || {} as user">
<div *ngIf="user.uid; else notLoggedIn">
<!-- 認証されている場合 -->
<p>ログイン中。uid: {{user.uid}}</p>
<button mat-flat-button color="accent" (click)="logout()">ログアウト</button>
</div>
<ng-template #notLoggedIn>
<!-- 認証されていない場合 -->
<p>書き込みする場合は下記いずれかの方法でサインインしてください。</p>
</ng-template>
</div>
<firebase-ui
(signInSuccessWithAuthResult)="successCallback($event)"
(signInFailure)="errorCallback($event)">
</firebase-ui>
应该会出现验证界面。
更改Firestore的规则

确认操作

尽管会出现新的记录一瞬间显示出来,但由于无法写入Firestore,所以仍然会显示以前的界面。



通过电话进行登录以进行操作验证



补充
如果外观不好看,想要在另一个屏幕上显示firebaseui,可以使用以下代码。
主居.component.html
書き込みする場合はまずサインインしてください。<button mat-flat-button color="accent" (click)="goToLink('login')">サインイン画面へ</button>
家.component.ts
goToLink(url: string){
window.open(url, "_blank", "width=400,height=500");
}

我想要把日本语化,但是稍微查了一下还是不懂。
请参考以下内容: Angular 使用 FirebaseUI 的方法 (angularfire2)
使用FirebaseUI在网页应用上轻松添加登录功能。
使用FirebaseUI + vue进行登录处理