Skip to content

Commit feb2eb2

Browse files
committed
fixed otp
1 parent 7a2a0cc commit feb2eb2

File tree

6 files changed

+189
-19
lines changed

6 files changed

+189
-19
lines changed

lib/auth.config.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
var remoteServerConfiguration = {"server": "https://node-server-otp.herokuapp.com", "serverKey": "I057LM"};

lib/auth.dart

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
1+
import 'package:carpool/auth.config.dart';
12
import 'package:carpool/landing.dart';
2-
import 'package:email_auth/email_auth.dart';
3-
import 'package:flutter/material.dart';
3+
import 'package:carpool/email_auth.dart';
4+
5+
EmailAuth emailAuth = EmailAuth(sessionName: "TEST");
46

57
void sendOTP(email_id_controller) async {
6-
EmailAuth.sessionName = "TEST";
7-
var res = await EmailAuth.sendOtp(receiverMail: email_id_controller.text);
8-
if (res) {
9-
}
8+
await emailAuth.config(remoteServerConfiguration);
9+
bool res = await emailAuth.sendOtp(recipientMail: email_id_controller.text);
10+
if (res) {}
1011
}
1112

1213
Future<bool> verifyOTP(email_id_controller, otpcontroller, context) async {
13-
var response = EmailAuth.validate(
14-
receiverMail: email_id_controller.text, userOTP: otpcontroller.text);
14+
bool response = emailAuth.validateOtp(recipientMail: email_id_controller.text, userOtp: otpcontroller.text);
1515
if (response) {
16-
1716
return true;
1817
} else {
1918
return false;

lib/email_auth.dart

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/// This file contains a Class to handle the process of sending OTP
2+
/// There are no static methods like the previous one, and they are all instance members
3+
///
4+
/// ------------- Remote server config --------------
5+
/// requires a auth.config.dart pacakge
6+
/// should follow the variable conventions as follows :
7+
/// var remoteServerConfig = {"server" : "serverUrl", "serverKey" : "Key generted from the email-auth-node package"}
8+
/// You can pass "remoteServerConfig" to the emailAuth instance.config() and generate them.
9+
import 'dart:async';
10+
import 'dart:convert' as convert;
11+
import 'package:flutter/cupertino.dart';
12+
import 'package:http/http.dart' as http;
13+
14+
late String _finalOTP;
15+
late String _finalEmail;
16+
17+
/// This function will check if the provided email ID is valid or not
18+
bool _isEmail(String email) {
19+
String p = r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
20+
RegExp regExp = new RegExp(p);
21+
return regExp.hasMatch(email);
22+
}
23+
24+
Future<bool> _isValidServer(String url) async {
25+
try {
26+
/// Performs a get request to the dummy end of the server :
27+
/// Expected result : {"message" : "success"}
28+
http.Response _serverResponse = await http.get(Uri.parse("$url/test/dart"));
29+
Map<String, dynamic> _jsonResponse = convert.jsonDecode(_serverResponse.body);
30+
return (_jsonResponse.containsKey("message") && _jsonResponse['message'] == 'success');
31+
} catch (error) {
32+
print("--- Package Error ---");
33+
if (error.runtimeType == FormatException) {
34+
print("Unable to access remote server. 😑");
35+
} else {
36+
print(error);
37+
}
38+
// print(error);
39+
print("--- End Package Error ---");
40+
return false;
41+
}
42+
}
43+
44+
/// This function will take care of converting the reponse data and verify the mail ID provided.
45+
bool _convertData(http.Response _response, String recipientMail) {
46+
try {
47+
Map<String, dynamic> _data = convert.jsonDecode(_response.body);
48+
// print(_data); // : For future verification
49+
50+
/// On Success get the data from the message and store them in the variables for the final verification
51+
if (_data["success"]) {
52+
_finalEmail = recipientMail;
53+
_finalOTP = _data["OTP"].toString();
54+
print("email-auth >> OTP sent successfully ✅");
55+
return true;
56+
} else {
57+
print("email-auth >> Failed to send OTP ❌");
58+
print("email-auth >> Message from server :: ${_data["error"]}");
59+
return false;
60+
}
61+
} catch (error) {
62+
print("--- Package Error ---");
63+
if (error.runtimeType == FormatException) {
64+
print("Unable to access server. 😑");
65+
} else {
66+
print(error);
67+
}
68+
// print(error);
69+
print("--- End Package Error ---");
70+
return false;
71+
}
72+
}
73+
74+
class EmailAuth {
75+
// The server
76+
late String _server = "";
77+
late String _serverKey = "";
78+
bool _validRemote = false;
79+
80+
// The session name
81+
String sessionName;
82+
83+
// Contructing the Class with the server and the session Name
84+
EmailAuth({
85+
required this.sessionName,
86+
}) {
87+
print("email-auth >> Initialising Email-Auth server");
88+
89+
// future patch
90+
// _init();
91+
}
92+
93+
// made for future patch
94+
// _init() { }
95+
96+
/// configuring the external server
97+
/// the Map should be of the pattern {"server" : "", "serverKey" : ""}
98+
Future<bool> config(Map<String, String> data) async {
99+
try {
100+
// Check the existence of the keys
101+
// print(data);
102+
103+
if (data.containsKey('server') &&
104+
data.containsKey('serverKey') &&
105+
data['server'] != null &&
106+
data['server']!.length > 0 &&
107+
data['serverKey'] != null &&
108+
data['serverKey']!.length > 0) {
109+
/// Only proceed further if the server is valid as per the function _isValidServer
110+
if (await _isValidServer(data['server']!)) {
111+
this._server = data['server']!;
112+
this._serverKey = data['serverKey']!;
113+
this._validRemote = true;
114+
print("email-auth >> The remote server configurations are valid");
115+
return true;
116+
} else {
117+
throw new ErrorDescription("email-auth >> The remote server is not a valid.\nemail-auth >> configured server : \"${data['server']}\"");
118+
}
119+
} else {
120+
throw new ErrorDescription("email-auth >> Remote server configurations are not valid");
121+
}
122+
} catch (error) {
123+
print("\n--- package Error ---\n");
124+
print(error);
125+
print("--- package Error ---");
126+
return false;
127+
}
128+
}
129+
130+
/// Takes care of sending the OTP to the server.
131+
/// returns a Boolean.
132+
Future<bool> sendOtp({required String recipientMail, int otpLength = 6}) async {
133+
try {
134+
if (!_isEmail(recipientMail)) {
135+
print("email-auth >> email ID provided is INVALID");
136+
return false;
137+
}
138+
139+
/// Defaults to the test server (reverts) : if the remote server is provided
140+
if (this._server.isEmpty) {
141+
print("email-auth >> Remote server is not available -- using test server --");
142+
print("email-auth >> ❗ Warning this is not reliable on production");
143+
http.Response _response = await http.get(Uri.parse(
144+
// ignore: unnecessary_brace_in_string_interps
145+
"https://app-authenticator.herokuapp.com/dart/auth/${recipientMail}?CompanyName=${this.sessionName}"));
146+
147+
return _convertData(_response, recipientMail);
148+
} else if (_validRemote) {
149+
http.Response _response = await http
150+
.get(Uri.parse("${this._server}/dart/auth/$recipientMail?CompanyName=${this.sessionName}&key=${this._serverKey}&otpLength=$otpLength"));
151+
return _convertData(_response, recipientMail);
152+
}
153+
return false;
154+
} catch (error) {
155+
print("--- Package Error ---");
156+
print(error);
157+
print("--- End Package Error ---");
158+
return false;
159+
}
160+
}
161+
162+
/// Boolean function to verify that the provided OTP and the user Email Ids, are all same.
163+
bool validateOtp({required String recipientMail, required String userOtp}) {
164+
if (_finalEmail.isEmpty || _finalOTP.isEmpty) {
165+
print("email-auth >> The OTP should be sent before performing validation");
166+
return false;
167+
}
168+
169+
if (_finalEmail.trim() == recipientMail.trim() && _finalOTP.trim() == userOtp.trim()) {
170+
print("email-auth >> Validation success ✅");
171+
return true;
172+
}
173+
174+
print("email-auth >> Validation failure ❌");
175+
return false;
176+
}
177+
}

lib/main.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class _LoginPageState extends State<LoginPage> {
6363
setState(() => _body = Stack(children: const <Widget>[
6464
TabNavigator(),
6565
]));
66-
66+
6767
LoginForm.u = null;
6868
return;
6969
}

lib/user.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ class User {
238238
if (interval == null) return [];
239239
List<BookingRecord>? brs = await DataBaseService.getBookingRecordsbyDate(br.date);
240240
if (brs == null) return null;
241-
brs!.remove(br);
241+
brs.remove(br);
242242
List<BookingRecord> ret = [];
243243

244244
for (var bookingRecord in brs) {

pubspec.lock

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -247,13 +247,6 @@ packages:
247247
url: "https://pub.dartlang.org"
248248
source: hosted
249249
version: "0.12.11"
250-
material_color_utilities:
251-
dependency: transitive
252-
description:
253-
name: material_color_utilities
254-
url: "https://pub.dartlang.org"
255-
source: hosted
256-
version: "0.1.3"
257250
meta:
258251
dependency: transitive
259252
description:
@@ -461,7 +454,7 @@ packages:
461454
name: test_api
462455
url: "https://pub.dartlang.org"
463456
source: hosted
464-
version: "0.4.8"
457+
version: "0.4.3"
465458
typed_data:
466459
dependency: transitive
467460
description:

0 commit comments

Comments
 (0)