Flutter电子邮件认证插件auth_email的使用

Flutter电子邮件认证插件auth_email的使用

服务器端

步骤

  1. 下载PHP服务器文件(例如:v0.0.4),并修改src/config.php文件以适应你的配置。示例如下:
// 这是一个简单的配置,你可以在 `index.php` 中修改更多的配置。
$HOST = 'example.com';
$USER_NAME = 'auth@example.com';
$PASSWORD = 'password';
$PORT = 587;
$SEND_FROM = $USER_NAME;

$DEFAULT_SUBJECT = '验证邮箱';
$DEFAULT_BODY = '请输入此一次性密码(OTP)来验证您的邮箱,不要将此代码透露给任何人:{otp}';
$DEFAULT_OTP_LENGTH = 6;

// 客户端密钥:authemailtestkey
$SERVER_SHA256_KEY = '6955c3a2dbfd121697623896b38f5eb759d2cd503476980e14b9beb0cc036c4d';

// 应用的安全性。
$ALLOWED_APPS = [
    // 应用名称。必须与客户端侧的 `appName` 相同。
    'Auth Email Test' => [
        // 允许此应用使用修改后的主题。
        'modifiedSubject' => false,
        // 允许此应用使用修改后的正文。
        'modifiedBody' => false,
        // 允许此应用使用修改后的OTP长度。
        'modifiedOtpLength' => false,
    ],
];
  1. 仅上传src目录下的文件到你的服务器。

客户端

步骤

  1. auth_email添加为项目的依赖项。
  2. 创建一个用于auth_email的控制器:
final authEmail = AuthEmail(
    // 应用名称。必须在服务器上的 `$ALLOWED_APPS` 中可用。
    appName: 'Auth Email Test',
    // 服务器URL。
    server: 'https://example.com/auth/email',
    // 客户端密钥。
    serverKey: 'authemailtestkey',
    // 是否允许打印调试日志。
    isDebug: true,
);
  1. 发送OTP验证码到客户端邮箱:
final bool result = await authEmail.sendOTP(email: 'exampleclient@gmail.com');

你也可以通过参数更改邮件的主题、正文和OTP长度,但首先需要在PHP服务器配置中将其权限设置为true

  1. 验证OTP验证码:
final bool isVerified = authEmail.verifyOTP(email: 'exampleclient@gmail.com', otp: '<code>');

其他功能

你可以检查邮箱是否有效,然后再发送OTP验证码:

final bool isValidEmail = AuthEmail.isValidEmail('exampleclient@gmail.com');

测试服务器

步骤

  1. 该项目包含一个测试服务器,你可以使用以下配置创建自己的测试应用程序:
// 仅用于测试目的。
final authEmail = AuthEmail(
  appName: 'Auth Email Example', // <- 仅允许此应用名称用于测试
  server: 'https://pub.lamnhan.dev/auth-email/api',
  serverKey: 'ohYwh',
  isDebug: true,
);
  1. 你还可以在Web上测试此插件。

请注意,此配置仅用于测试目的。

贡献

如果您发现任何错误或缺少某些功能,请随时提交问题,我们也欢迎PR。


示例代码

以下是完整的示例代码:

import 'package:auth_email/auth_email.dart';
import 'package:flutter/material.dart';

// 仅用于测试目的。
final authEmail = AuthEmail(
  appName: 'Auth Email Example',
  server: 'https://pub.lamnhan.dev/auth-email/api',
  serverKey: 'ohYwh',
  isDebug: true,
);

void main() async {
  runApp(const MaterialApp(home: AuthEmailApp()));
}

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

  [@override](/user/override)
  State<AuthEmailApp> createState() => _AuthEmailAppState();
}

class _AuthEmailAppState extends State<AuthEmailApp> {
  String sendOtpButton = '发送OTP';
  String verifyOtpButton = '验证OTP';

  bool isSent = false;
  String desEmailTextField = '';
  String verifyTextField = '';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Auth Email'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          if (!isSent) ...[
            const Text('输入您的客户端邮箱:'),
            TextFormField(
              textAlign: TextAlign.center,
              initialValue: desEmailTextField,
              onChanged: (value) {
                desEmailTextField = value;
              },
              validator: (value) {
                if (!AuthEmail.isValidEmail(desEmailTextField)) {
                  return '此邮箱无效!';
                }
                return null;
              },
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: () async {
                setState(() {
                  sendOtpButton = '正在发送OTP...';
                });

                final result = await authEmail.sendOTP(email: desEmailTextField);

                if (!result) {
                  setState(() {
                    sendOtpButton = '发送OTP失败!';
                  });
                }
                setState(() {
                  isSent = result;
                });
              },
              child: Text(sendOtpButton),
            )
          ] else ...[
            const Text('输入您的OTP:'),
            TextField(
              textAlign: TextAlign.center,
              onChanged: (value) {
                verifyTextField = value;
              },
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: () async {
                final result = authEmail.verifyOTP(
                    email: desEmailTextField, otp: verifyTextField);

                if (result) {
                  setState(() {
                    verifyOtpButton = '验证OTP成功';
                  });
                } else {
                  setState(() {
                    verifyOtpButton = '验证OTP失败!';
                  });
                }
              },
              child: Text(verifyOtpButton),
            )
          ]
        ],
      ),
    );
  }
}

更多关于Flutter电子邮件认证插件auth_email的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter电子邮件认证插件auth_email的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用auth_email插件来实现电子邮件认证的示例代码。需要注意的是,auth_email并不是Flutter官方或广泛认可的插件名称,通常Flutter社区会使用一些更具体的库来处理电子邮件认证,比如结合Firebase Authentication。不过,为了示范目的,我将假设有一个名为auth_email的虚构库,并展示如何使用它(如果这样的库存在)。

首先,确保你已经在pubspec.yaml文件中添加了auth_email依赖:

dependencies:
  flutter:
    sdk: flutter
  auth_email: ^x.y.z  # 替换为实际的版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用auth_email插件进行电子邮件认证:

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:auth_email/auth_email.dart';  // 假设这是你的电子邮件认证插件
  1. 配置认证服务

通常,你需要配置一些服务参数,比如API密钥或服务器URL。这里假设auth_email插件提供了类似的配置方法。

void configureAuthService() {
  // 假设auth_email提供了一个配置函数
  AuthEmailService.configure(
    apiKey: 'YOUR_API_KEY',  // 替换为你的API密钥
    serverUrl: 'https://your-auth-server.com',  // 替换为你的服务器URL
  );
}
  1. 创建发送验证邮件的函数
Future<void> sendVerificationEmail(String email) async {
  try {
    await AuthEmailService.sendVerificationEmail(email: email);
    print('Verification email sent to $email');
  } catch (e) {
    print('Failed to send verification email: $e');
  }
}
  1. 处理邮件验证

用户点击邮件中的链接后,通常会跳转到一个网页或应用内的特定页面,你需要处理这个验证过程。

Future<void> handleEmailVerification(String verificationToken) async {
  try {
    await AuthEmailService.verifyEmail(verificationToken: verificationToken);
    print('Email verified successfully');
    // 跳转到主屏幕或执行其他操作
  } catch (e) {
    print('Failed to verify email: $e');
  }
}
  1. 在UI中集成

创建一个简单的UI来发送验证邮件和处理验证。

void main() {
  configureAuthService();  // 配置认证服务
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Email Verification Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Email Verification Demo'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                onChanged: (email) {
                  // 这里可以添加一些逻辑来保存email
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: () async {
                  String email = // 获取用户输入的email地址
                  await sendVerificationEmail(email);
                },
                child: Text('Send Verification Email'),
              ),
              SizedBox(height: 16.0),
              TextField(
                decoration: InputDecoration(labelText: 'Verification Token'),
                onChanged: (verificationToken) {
                  // 这里可以添加一些逻辑来保存verificationToken
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: () async {
                  String verificationToken = // 获取用户输入的verificationToken
                  await handleEmailVerification(verificationToken);
                },
                child: Text('Verify Email'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

注意:上述代码是一个简化的示例,实际上auth_email插件可能不存在,或者其API可能与示例中的不同。在实际项目中,你可能需要使用像Firebase Authentication这样的服务,它提供了更全面的身份验证解决方案,包括电子邮件和密码认证。

如果你确实在使用一个特定的电子邮件认证插件,请参考该插件的官方文档来获取准确的API调用和使用方法。

回到顶部