😱

Firebaseのパスワードを再登録する

2022/12/22に公開

パスワードを再登録するには?

認証機能でたまにパスワードの再登録の機能がついていないアプリやサービスがある。
これは大変ですね!
お問い合わせフォームがあったりして、そちらからパスワードのリセットをお願いしたりしますけどね。

今回はFlutterでFirebaseを使うときに、再登録をするdemoアプリを作りました。
今回は入力したメールアドレスにパスワードの再登録を行うメール送って、パスワードのリセットを行えるようにする機能を作成しました。

今回参考にした資料
https://zenn.dev/kazutxt/books/flutter_practice_introduction/viewer/30_chapter4_authentication

  • やること
  1. Firebaseのプロジェクトを作る.
  2. FirebaseAuthenticationの設定をする.
  3. メールアドレスとパスワードのログインを使用.

FirebaseAuthenticationには、メールを送るときにメッセージを送る設定画面があって、defaultでは英語なので、日本語に対応にします。

趣味レベルなら、細かい設定はいらないようですね。以前、Vue.jsでFirebaseAuthenticationを使ったときも簡単な設定にしていたような。

上のタブメニューからTemplatesを選択します。こちらの画面で設定を行います。
私の設定はこんな感じです!

デモのスクリーンショット

今回は、パスワードのリセットについて、学ぶのが目的なので、新規登録とログインは同じページに配置しました。
適当ですいません🙇‍♂️
パスワードのリセットは、申請するページに移動して、入力フォームからメールアドレスを入力して行います。

登録したメールアドレスにリセットの申請のメールが届けば成功!
迷惑メールに入っていることもあるので確認した方いいです!
迷惑メールの指定からはずす設定をすれば、通常のメールとして送られてきます。

指定されたリンクからFirebaseのパスワードのリセットを行うことができるページへ移動できます

こちらが、パスワードをリセットするフォームです

成功するとこのような表示が出ます

今回使用したソースコード

pubspec.yaml
name: fargot_password
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 is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.0 <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: ^2.4.0
  firebase_auth: ^4.2.1

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:fargot_password/fargot_password.dart';
import 'package:fargot_password/home_page.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

// MyAppのクラス
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 入力したメールアドレス・パスワード
  String _email = '';
  String _password = '';

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // メールアドレス入力用テキストフィールド
              TextFormField(
                decoration: const InputDecoration(labelText: 'メールアドレス'),
                onChanged: (String value) {
                  setState(() {
                    _email = value;
                  });
                },
              ),
              // パスワード入力用テキストフィールド
              TextFormField(
                decoration: const InputDecoration(labelText: 'パスワード'),
                obscureText: true,
                onChanged: (String value) {
                  setState(() {
                    _password = value;
                  });
                },
              ),
              // ユーザ登録ボタン
              ElevatedButton(
                child: const Text('ユーザ登録'),
                onPressed: () async {
                  try {
                    final User? user = (await FirebaseAuth.instance
                            .createUserWithEmailAndPassword(
                                email: _email, password: _password))
                        .user;
                    if (user != null)
                      print("ユーザ登録しました ${user.email} , ${user.uid}");
                  } catch (e) {
                    print(e);
                  }
                },
              ),
              // ログインボタン
              ElevatedButton(
                child: const Text('ログイン'),
                onPressed: () async {
                  try {
                    // メール/パスワードでログイン
                    final User? user = (await FirebaseAuth.instance
                            .signInWithEmailAndPassword(
                                email: _email, password: _password))
                        .user;
                    if (user != null)
                      print("ログインしました ${user.email} , ${user.uid}");
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) {
                          return HomePage(); // 遷移先の画面widgetを指定
                        },
                      ),
                    );
                  } catch (e) {
                    print(e);
                  }
                },
              ),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (context) {
                          return FargotPassword(); // 遷移先の画面widgetを指定
                        },
                      ),
                    );
                  },
                  child: Text('パスワードを忘れた'))
            ],
          ),
        ),
      ),
    );
  }
}
home.dart
import 'package:fargot_password/main.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class HomePage extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ログインしました!'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.logout),
            onPressed: () async {
              // ログアウト処理
              // 内部で保持しているログイン情報等が初期化される
              await FirebaseAuth.instance.signOut();
              await Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) {
                    return MyHomePage();
                  },
                ),
              );
            },
          ),
        ],
      ),
      body: Center(
        // ユーザー情報を表示
        child: Text('ようこそ!'),
      ),
    );
  }
}
fargot_password.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class FargotPassword extends StatefulWidget {
  const FargotPassword({Key? key}) : super(key: key);

  
  State<FargotPassword> createState() => _FargotPasswordState();
}

class _FargotPasswordState extends State<FargotPassword> {
  // 入力したメールアドレス
  String _email = '';

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('パスワードの再登録'),
      ),
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // メールアドレス入力用テキストフィールド
              TextFormField(
                decoration:
                    const InputDecoration(labelText: 'メールアドレスを入力してください'),
                onChanged: (String value) {
                  setState(() {
                    _email = value;
                  });
                },
              ),
              // パスワードリセットボタン
              ElevatedButton(
                  child: const Text('パスワードリセットする'),
                  onPressed: () async {
                    try {
                      await FirebaseAuth.instance
                          .sendPasswordResetEmail(email: _email);
                      print("パスワードリセット用のメールを送信しました");
                    } catch (e) {
                      print(e);
                    }
                  }),
            ],
          ),
        ),
      ),
    );
  }
}

最後に

認証機能はインターネットに接続するアプリケーションでは、基本的な機能なので、「パスワード忘れた!」ってなったら、危ういことになります!
パスワード忘れたり、メモしたけど忘れた、間違えて覚えていたってことがあるので、再登録は必須です!

おまけ

go_routerで画面遷移ができる設定を追加した完成品のコードを用意しました。
最近は、go_routerが流行りみたいなのでリファクタリングして、画面遷移はRouter APIに任せることにしました。
使用したgo_routeのversion
https://pub.dev/packages/go_router/versions/5.2.4
完成したコード
https://github.com/sakurakotubaki/FargotApp

Flutter大学

Discussion