FireStoreのセキュリティールールについて学んでみる
皆さんセキュリティーどうしてますか?
Firebaseには、セキュリティールールというものがありまして、以前は書いてみたが、アプリが動かなくなりました。なぜだ〜😅
今回は、ドキュメントに書いてある書き方を参考に、データの書き込み、表示、更新、削除をやっていこうと思います。やる前に、「これで、動くんじゃね?」と思って書いてみたら、データの保存はできないし、データの表示もできなくなりました😱
公式ドキュメント
エラーのログ
>(ConnectionState.active, null, [cloud_firestore/permission-denied
permission-deniedって表示されたら、セキュリティールールの書き方が正しくなくて、Flutterの画面にデータが表示されなくなってしまいます!
セキュリティールール書いてみた
何度か書き換えていたのですが、読み込み、書き込み、更新、削除できるようになったと思えば、新規のユーザー登録ができなくなった?
で今は、こんな風に書いたらusersコレクションに新規ユーザーの登録ができました。
練習用としては、いいのかもしれない?
最初は、そもそもデータが保存されていないので、uidが一致してないとusersコレクションに書き込みができないようにするのは、問題があると思う😅
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
allow read, write: if request.auth != null && uid == request.auth.uid;
allow create: if true; // if trueにしないと新規登録できなかった!
match /messages/{message} {
// 認証通っている人が読み書きできる
allow read, write: if request.auth != null && uid == request.auth.uid;
}
match /admin_settings/{admin_setting} {
// 管理系の設定はユーザーに書き込みさせない(writeは、いずれroleベースの判断とする)
allow read: if request.auth != null && uid == request.auth.uid;
allow write: if false;
}
}
}
}
初めはこんな風に書いてました...
このルールだとログインしたユーザーのuidが一致すれば、画面にFireStoreの値を表示することができます。
今回の例だと、messagesサブコレクションのフィールドが増えると、セキュリティールール追加しないと画面に映せないと思ったのですが、後で追加したTimestmpが写ってました🤔
あら、不思議?
ドキュメント1個でいいのかな?
変更後のセキュリティールール
変更後のセキュリティールールは、ログインしたユーザーのuidが一致すれば、データの追加・表示・更新・削除を行えるようにしました。
数日前に書いたセキュリティールールだと、画面は映るがボタンを押しても追加・更新・削除ができませんでした。難しいですね〜😇
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
match /messages/{message} {
allow read, update, delete: if request.auth != null && uid == request.auth.uid;
allow create: if request.auth != null;
}
}
}
}
で、後で気づいたのですが、新規登録ができなかった😅
今回使ったサンプルコード
このようになっております。画面遷移先だけpageフォルダに作りました。
Firebase CLIを使ったので、iOS、Android、Flutter Webが使えます。
スクリーンショット
pabspec.yaml
name: auth_crud
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.17.3 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_core: ^1.19.1
firebase_auth: ^3.4.1
cloud_firestore: ^3.3.0
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
main.dart
import 'package:auth_crud/firebase_options.dart';
import 'package:auth_crud/page/home_page.dart';
import 'package:auth_crud/page/sign_up.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('FlutterZero'),
),
body: SignInPage(),
),
);
}
}
class SignInPage extends StatefulWidget {
const SignInPage({Key? key}) : super(key: key);
State<SignInPage> createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
String? email;
String? password;
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
TextField(
controller: _emailController,
onChanged: (email) {
this.email = email;
},
decoration: InputDecoration(hintText: 'Email'),
),
TextField(
controller: _passwordController,
onChanged: (password) {
this.password = password;
},
obscureText: true,
decoration: InputDecoration(hintText: 'Password'),
),
ElevatedButton(
child: Text('Sign In'),
onPressed: () async {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text.trim(),
password: _passwordController.text.trim(),
);
final user = FirebaseAuth.instance.currentUser!;
final snackBar = SnackBar(
content: Text(user.email!),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
Navigator.push(context,
MaterialPageRoute(builder: (context) => HomePage()));
} catch (e) {
print(e);
}
},
),
TextButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SignUpPage()));
},
child: Text('新規登録'))
],
),
);
}
}
page/sign_up.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class SignUpPage extends StatefulWidget {
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
// 入力されたユーザーの名前
String newUser = "";
// 入力されたメールアドレス
String newUserEmail = "";
// 入力されたパスワード
String newUserPassword = "";
// ユーザー情報を登録する関数を定義
Future<void> createAuth() async {
// FirebaseAuthが用意しているメールアドレスとパスワードを登録する関数を定義
final FirebaseAuth auth = FirebaseAuth.instance;
UserCredential result = await auth.createUserWithEmailAndPassword(
email: newUserEmail,
password: newUserPassword,
);
// 上のFirebaseAuthから、uidを取得する変数を定義
final user = result.user;
final uuid = user?.uid;
// usersコレクションを作成して、uidとドキュメントidを一致させるプログラムを定義
final users = FirebaseFirestore.instance.collection('users').doc(uuid).set({
'uid': uuid,
'name': newUser,
'email': newUserEmail,
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('ユーザー登録'),
),
// キーボードで隠れて、黄色エラーが出るので
// SingleChildScrollViewで、Centerウイジットをラップする
body: SingleChildScrollView(
child: Center(
child: Container(
padding: EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// かっこよくしたいので、画像を配置した!
const CircleAvatar(
radius: 75,
// images.unsplash.comの画像のパスを貼り付ける
backgroundImage: NetworkImage(
'https://images.unsplash.com/photo-1658033014478-cc3b36e31a5e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMDR8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=800&q=60'),
),
const SizedBox(height: 40),
TextFormField(
// テキスト入力のラベルを設定
decoration: InputDecoration(labelText: "ユーザー名"),
onChanged: (String value) {
setState(() {
newUser = value;
});
},
),
const SizedBox(height: 8),
TextFormField(
// テキスト入力のラベルを設定
decoration: InputDecoration(labelText: "メールアドレス"),
onChanged: (String value) {
setState(() {
newUserEmail = value;
});
},
),
const SizedBox(height: 8),
TextFormField(
decoration: InputDecoration(labelText: "パスワード(6文字以上)"),
// パスワードが見えないようにする
obscureText: true,
onChanged: (String value) {
setState(() {
newUserPassword = value;
});
},
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () async {
try {
// 作成した関数を実行する
createAuth();
} catch (e) {
print('登録に失敗しました!: $e');
}
},
child: Text("ユーザー登録"),
),
],
),
),
),
),
);
}
}
page/home_page.dart
import 'package:auth_crud/page/delete.dart';
import 'package:auth_crud/page/read.dart';
import 'package:auth_crud/page/update.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String newMessage = "";
DateTime now = DateTime.now();
void addMessage() async {
final user = FirebaseAuth.instance.currentUser;
final uid = user?.uid;
final msg = await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('messages')
.doc(uid)
.set({'uid': uid, 'message': newMessage, 'now': now});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HOME'),
),
body: Center(
child: Column(
children: [
TextField(
onChanged: (String value) {
setState(() {
newMessage = value;
});
},
),
ElevatedButton(
onPressed: () {
addMessage();
print('データを保存しました💀');
},
child: Text('データを保存')),
ElevatedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => UpdatePage()));
},
child: Text('データを更新')),
ElevatedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DeletePage()));
},
child: Text('データを削除')),
ElevatedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ReadPage()));
},
child: Text('データを表示')),
],
),
),
);
}
}
page/read.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:intl/intl.dart';
class ReadPage extends StatefulWidget {
const ReadPage({Key? key}) : super(key: key);
State<ReadPage> createState() => _ReadPageState();
}
class _ReadPageState extends State<ReadPage> {
final uid = FirebaseAuth.instance.currentUser?.uid;
Widget build(BuildContext context) {
final Stream<QuerySnapshot> _userStrem = FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('messages')
.snapshots();
return Scaffold(
appBar: AppBar(
title: Text('read'),
),
body: StreamBuilder<QuerySnapshot>(
stream: _userStrem,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
print('hasError✋: $snapshot');
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
print('connectionState: $snapshot');
return Text("Loading✋");
}
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
print('data✋: $data');
return ListTile(
subtitle: Text(
DateFormat("yyyy/MM/dd HH:mm:ss").format(data['now'].toDate()).toString(),
style: TextStyle(fontSize: 18.0, color: Colors.red[400]),
),
title: Text(data['message'], style: TextStyle(fontSize: 25, color: Colors.black87),),
);
}).toList(),
);
},
),
);
}
}
page/update.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class UpdatePage extends StatefulWidget {
UpdatePage({Key? key}) : super(key: key);
State<UpdatePage> createState() => _UpdatePageState();
}
class _UpdatePageState extends State<UpdatePage> {
String newMessage = "";
DateTime now = DateTime.now();
void updateMsg() async {
final user = FirebaseAuth.instance.currentUser;
final uid = user?.uid;
final updateMsg = await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('messages')
.doc(uid)
.update({'uid': uid, 'message': newMessage, "now": now});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HOME'),
),
body: Center(
child: Column(
children: [
TextField(
onChanged: (String value) {
setState(() {
newMessage = value;
});
},
),
ElevatedButton(
onPressed: () {
updateMsg();
print('データを更新しました🐼');
},
child: Text('データを更新'))
],
),
),
);
}
}
page/delete.dart
import 'package:auth_crud/page/update.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class DeletePage extends StatefulWidget {
DeletePage({Key? key}) : super(key: key);
State<DeletePage> createState() => _DeletePageState();
}
class _DeletePageState extends State<DeletePage> {
String newMessage = "";
void deleteMessage() async {
final user = FirebaseAuth.instance.currentUser;
final uid = user?.uid;
final msg = await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.collection('messages')
.doc(uid)
.delete();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HOME'),
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
deleteMessage();
print('データを削除しました👻');
},
child: Text('データを削除')),
],
),
),
);
}
}
やってみた感想
すごく難しいですね。実際に動くアプリを作ってルールを書き換えて、画面にデータが表示できるか、FireStoreにデータが追加できるのか実験しながら、理解しました。
アプリをリリースするときは、複雑なルールを書くと思いますが...
Discussion