-
Notifications
You must be signed in to change notification settings - Fork 1
/
CloudFunctionsPage.dart
123 lines (111 loc) · 3.66 KB
/
CloudFunctionsPage.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import 'package:flutter/material.dart';
import 'package:cloud_functions/cloud_functions.dart';
class CloudFunctionsPage extends StatefulWidget {
CloudFunctionsPage({Key key}) : super(key: key);
@override
CloudFunctionsPageState createState() {
return new CloudFunctionsPageState();
}
}
class CloudFunctionsPageState extends State<CloudFunctionsPage> {
CloudFunctionsPageState(): super();
// Cloud Functions
FirebaseFunctions functions = FirebaseFunctions.instance;
// Form
final formKey = GlobalKey<FormState>();
String email;
String emailAddressValidator(String email) {
if (!email.contains("@")) {
return "Please enter a valid email";
}
return null;
}
int lastEmailTimestamp = 0;
Future<void> sendEmail(email) async {
try {
final HttpsCallableResult result = await functions.httpsCallable("EmailSender")(email);
if (result.data != null) {
print("Message received from EmailSender: " + result.data);
} else {
print("Error: no data received");
}
} on FirebaseFunctionsException catch (err) {
print("Error: " + err.message);
} catch(err) {
print("Error: " + err);
}
}
onSendEmailClicked() {
// prevent spam
int currentTime = DateTime.now().millisecondsSinceEpoch;
if (currentTime - lastEmailTimestamp > 1000 * 60) { // once per minute
if (formKey.currentState.validate()) {
formKey.currentState.save();
sendEmail(email);
lastEmailTimestamp = DateTime.now().millisecondsSinceEpoch;
}
} else {
print("Spam prevented");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cloud Functions"),
backgroundColor: Colors.orange,
),
body: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: Text(
"Email Sender",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 36
),
)
),
Form(
key: formKey,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 32.0),
child: TextFormField(
decoration: const InputDecoration(
icon: Icon(Icons.email),
labelText: "Email"
),
validator: this.emailAddressValidator,
onSaved: (value) {
email = value;
}
)
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 32.0),
child: Center(
child: ElevatedButton(
onPressed: onSendEmailClicked,
child: Text('Send Demo Email'),
)
)
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 32.0),
child: Center(
child: Text(
"(limit one per minute)"
)
)
),
]
)
)
);
}
}