firebase - 如何为登录添加 if else 条件?
问题描述
我在通过 Flutter 应用程序中通过 Firebase 登录时遇到问题。在应用程序中,我有两种类型的用户可以登录:代理和普通用户。(在 cloud firestore 中,有 2 个名为 users 和机构的集合,分别具有唯一的 uid 和aid。)
普通用户可以正常登录并被重定向到他们的主页,但它不适用于代理机构。但是,代理可以注册一个帐户,并将其保存到代理集合下的 firebase 服务器中,并且它会立即被重定向到其名为 AgencyHomepage() 的主页。
但是对于登录,我想知道是否可以设置一个条件来识别尝试登录的人是代理用户还是普通用户,然后将他们重定向到各自的主页?
void signIn(String email, String password) async {
if (_formKey.currentState!.validate()) {
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(
timeInSecForIosWeb: 2,
gravity: ToastGravity.CENTER,
msg: "Login Successful"),
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => MainPage())),
})
.catchError((e) {
Fluttertoast.showToast(
timeInSecForIosWeb: 3,
gravity: ToastGravity.CENTER,
msg: "The email or password is invalid. Please check and try again.",
);
});
}
}
上面的代码是用户登录的功能,当你点击登录按钮时它会被触发。对于代理,我希望 MainPage() 改为 AgencyHomepage()。
完整代码:
class _LoginState extends State<Login> {
GoogleAuth authentication = GoogleAuth();
final _formKey = GlobalKey<FormState>();
final TextEditingController emailController = new TextEditingController();
final TextEditingController passwordController = new TextEditingController();
final _auth = FirebaseAuth.instance;
bool _showPwd = true;
@override
Widget build(BuildContext context) {
final emailField = TextFormField(
autofocus: false,
controller: emailController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ("Please enter your email");
}
// reg expression for email validation
if (!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]")
.hasMatch(value)) {
return ("Please enter a valid email");
}
return null;
},
onSaved: (value) {
emailController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.mail),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
));
final passwordField = TextFormField(
autofocus: false,
controller: passwordController,
obscureText: _showPwd,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ("Password is required");
}
if (!regex.hasMatch(value)) {
return ("Password needs to have minimum 6 characters");
}
},
onSaved: (value) {
passwordController.text = value!;
},
textInputAction: TextInputAction.done,
decoration: InputDecoration(
prefixIcon: Icon(Icons.vpn_key),
suffixIcon: IconButton(
icon: Icon(_showPwd ? Icons.visibility : Icons.visibility_off),
onPressed: () {
setState(() {
_showPwd = !_showPwd;
});
}),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
));
final loginButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Color(0xFF003893),
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: 300,
onPressed: () {
signIn(emailController.text, passwordController.text);
},
child: Text(
"Login",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
)),
);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: RichText(
text: TextSpan(
style: Theme.of(context)
.textTheme
.headline6!
.copyWith(fontWeight: FontWeight.bold),
children: [
TextSpan(
text: "Login",
style: TextStyle(color: Colors.black),
),
],
),
),
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black),
onPressed: () {
Navigator.of(context).pop();
},
),
),
body: SingleChildScrollView(
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 100,
child: Image.asset(
"assets/icons/temp.png",
fit: BoxFit.contain,
)),
SizedBox(height: 40),
emailField,
SizedBox(height: 25),
passwordField,
SizedBox(height: 40),
loginButton,
SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Don't have an account? "),
GestureDetector(
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserRegistration()));
},
child: Text(
"Sign Up",
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 15),
),
)
]),
Padding(
padding: const EdgeInsets.only(top: 30),
child: TextButton.icon(
style: TextButton.styleFrom(
primary: Color(0xfF003893),
),
onPressed: () async {
await authentication.googleLogin();
},
label: Text('Sign In with Google'),
icon: Image.asset('assets/icons/google_logo.png',
height: 30, width: 30),
),
),
],
),
),
),
),
),
);
}
void signIn(String email, String password) async {
if (_formKey.currentState!.validate()) {
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(
timeInSecForIosWeb: 2,
gravity: ToastGravity.CENTER,
msg: "Login Successful"),
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => MainPage())),
})
.catchError((e) {
Fluttertoast.showToast(
timeInSecForIosWeb: 3,
gravity: ToastGravity.CENTER,
msg: "The email or password is invalid. Please check and try again.",
);
});
}
}
}
解决方案
我遇到了这样的问题,我们使用这个函数解决了它:
Future<String> checkBothUserBasesForTheUser(String uid) async {
DocumentSnapshot _doc = await db.collection('users').doc(uid).get();
if (_doc.exists) return 'user';
DocumentSnapshot _userDoc =
await db.collection('agencyUsers').doc(uid).get();
if (_userDoc.exists || _doc.exists)
return 'agency';
else
return null;
}
*** 你应该知道每次有人登录时你都会有多次阅读。
推荐阅读
- javascript - 将函数参数传递给反应中的另一个组件
- python - 如何从 C:\Python37\Scripts 创建一个类似于 pip.exe、jupyter.exe 等的 .exe?
- python - 使用“替换”时出现熊猫分段错误
- mysql - 无法在 kubernetes 中运行 mysql statefulset
- spring - 所有属性的 @Value 的默认值
- c - c中的彩色输出
- c - c中的二维阵列水平反射
- hyperledger-fabric - 无法生成 orderer 创世块 - Hyperledger Fabric
- c - 在类 C 函数的宏中实现浮点相等检查:错误在哪里?
- php - WooCommerce:从产品变体中获取自定义字段并将其显示为变体价格的后缀