Skip to content

Commit

Permalink
fixed otp
Browse files Browse the repository at this point in the history
  • Loading branch information
raddi1972 committed Feb 17, 2022
1 parent 7a2a0cc commit feb2eb2
Show file tree
Hide file tree
Showing 6 changed files with 189 additions and 19 deletions.
1 change: 1 addition & 0 deletions lib/auth.config.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
var remoteServerConfiguration = {"server": "https://node-server-otp.herokuapp.com", "serverKey": "I057LM"};
17 changes: 8 additions & 9 deletions lib/auth.dart
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import 'package:carpool/auth.config.dart';
import 'package:carpool/landing.dart';
import 'package:email_auth/email_auth.dart';
import 'package:flutter/material.dart';
import 'package:carpool/email_auth.dart';

EmailAuth emailAuth = EmailAuth(sessionName: "TEST");

void sendOTP(email_id_controller) async {
EmailAuth.sessionName = "TEST";
var res = await EmailAuth.sendOtp(receiverMail: email_id_controller.text);
if (res) {
}
await emailAuth.config(remoteServerConfiguration);
bool res = await emailAuth.sendOtp(recipientMail: email_id_controller.text);
if (res) {}
}

Future<bool> verifyOTP(email_id_controller, otpcontroller, context) async {
var response = EmailAuth.validate(
receiverMail: email_id_controller.text, userOTP: otpcontroller.text);
bool response = emailAuth.validateOtp(recipientMail: email_id_controller.text, userOtp: otpcontroller.text);
if (response) {

return true;
} else {
return false;
Expand Down
177 changes: 177 additions & 0 deletions lib/email_auth.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/// This file contains a Class to handle the process of sending OTP
/// There are no static methods like the previous one, and they are all instance members
///
/// ------------- Remote server config --------------
/// requires a auth.config.dart pacakge
/// should follow the variable conventions as follows :
/// var remoteServerConfig = {"server" : "serverUrl", "serverKey" : "Key generted from the email-auth-node package"}
/// You can pass "remoteServerConfig" to the emailAuth instance.config() and generate them.
import 'dart:async';
import 'dart:convert' as convert;
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;

late String _finalOTP;
late String _finalEmail;

/// This function will check if the provided email ID is valid or not
bool _isEmail(String email) {
String p = r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
RegExp regExp = new RegExp(p);
return regExp.hasMatch(email);
}

Future<bool> _isValidServer(String url) async {
try {
/// Performs a get request to the dummy end of the server :
/// Expected result : {"message" : "success"}
http.Response _serverResponse = await http.get(Uri.parse("$url/test/dart"));
Map<String, dynamic> _jsonResponse = convert.jsonDecode(_serverResponse.body);
return (_jsonResponse.containsKey("message") && _jsonResponse['message'] == 'success');
} catch (error) {
print("--- Package Error ---");
if (error.runtimeType == FormatException) {
print("Unable to access remote server. 😑");
} else {
print(error);
}
// print(error);
print("--- End Package Error ---");
return false;
}
}

/// This function will take care of converting the reponse data and verify the mail ID provided.
bool _convertData(http.Response _response, String recipientMail) {
try {
Map<String, dynamic> _data = convert.jsonDecode(_response.body);
// print(_data); // : For future verification

/// On Success get the data from the message and store them in the variables for the final verification
if (_data["success"]) {
_finalEmail = recipientMail;
_finalOTP = _data["OTP"].toString();
print("email-auth >> OTP sent successfully ✅");
return true;
} else {
print("email-auth >> Failed to send OTP ❌");
print("email-auth >> Message from server :: ${_data["error"]}");
return false;
}
} catch (error) {
print("--- Package Error ---");
if (error.runtimeType == FormatException) {
print("Unable to access server. 😑");
} else {
print(error);
}
// print(error);
print("--- End Package Error ---");
return false;
}
}

class EmailAuth {
// The server
late String _server = "";
late String _serverKey = "";
bool _validRemote = false;

// The session name
String sessionName;

// Contructing the Class with the server and the session Name
EmailAuth({
required this.sessionName,
}) {
print("email-auth >> Initialising Email-Auth server");

// future patch
// _init();
}

// made for future patch
// _init() { }

/// configuring the external server
/// the Map should be of the pattern {"server" : "", "serverKey" : ""}
Future<bool> config(Map<String, String> data) async {
try {
// Check the existence of the keys
// print(data);

if (data.containsKey('server') &&
data.containsKey('serverKey') &&
data['server'] != null &&
data['server']!.length > 0 &&
data['serverKey'] != null &&
data['serverKey']!.length > 0) {
/// Only proceed further if the server is valid as per the function _isValidServer
if (await _isValidServer(data['server']!)) {
this._server = data['server']!;
this._serverKey = data['serverKey']!;
this._validRemote = true;
print("email-auth >> The remote server configurations are valid");
return true;
} else {
throw new ErrorDescription("email-auth >> The remote server is not a valid.\nemail-auth >> configured server : \"${data['server']}\"");
}
} else {
throw new ErrorDescription("email-auth >> Remote server configurations are not valid");
}
} catch (error) {
print("\n--- package Error ---\n");
print(error);
print("--- package Error ---");
return false;
}
}

/// Takes care of sending the OTP to the server.
/// returns a Boolean.
Future<bool> sendOtp({required String recipientMail, int otpLength = 6}) async {
try {
if (!_isEmail(recipientMail)) {
print("email-auth >> email ID provided is INVALID");
return false;
}

/// Defaults to the test server (reverts) : if the remote server is provided
if (this._server.isEmpty) {
print("email-auth >> Remote server is not available -- using test server --");
print("email-auth >> ❗ Warning this is not reliable on production");
http.Response _response = await http.get(Uri.parse(
// ignore: unnecessary_brace_in_string_interps
"https://app-authenticator.herokuapp.com/dart/auth/${recipientMail}?CompanyName=${this.sessionName}"));

return _convertData(_response, recipientMail);
} else if (_validRemote) {
http.Response _response = await http
.get(Uri.parse("${this._server}/dart/auth/$recipientMail?CompanyName=${this.sessionName}&key=${this._serverKey}&otpLength=$otpLength"));
return _convertData(_response, recipientMail);
}
return false;
} catch (error) {
print("--- Package Error ---");
print(error);
print("--- End Package Error ---");
return false;
}
}

/// Boolean function to verify that the provided OTP and the user Email Ids, are all same.
bool validateOtp({required String recipientMail, required String userOtp}) {
if (_finalEmail.isEmpty || _finalOTP.isEmpty) {
print("email-auth >> The OTP should be sent before performing validation");
return false;
}

if (_finalEmail.trim() == recipientMail.trim() && _finalOTP.trim() == userOtp.trim()) {
print("email-auth >> Validation success ✅");
return true;
}

print("email-auth >> Validation failure ❌");
return false;
}
}
2 changes: 1 addition & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class _LoginPageState extends State<LoginPage> {
setState(() => _body = Stack(children: const <Widget>[
TabNavigator(),
]));

LoginForm.u = null;
return;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ class User {
if (interval == null) return [];
List<BookingRecord>? brs = await DataBaseService.getBookingRecordsbyDate(br.date);
if (brs == null) return null;
brs!.remove(br);
brs.remove(br);
List<BookingRecord> ret = [];

for (var bookingRecord in brs) {
Expand Down
9 changes: 1 addition & 8 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -247,13 +247,6 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "0.12.11"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.3"
meta:
dependency: transitive
description:
Expand Down Expand Up @@ -461,7 +454,7 @@ packages:
name: test_api
url: "https://pub.dartlang.org"
source: hosted
version: "0.4.8"
version: "0.4.3"
typed_data:
dependency: transitive
description:
Expand Down

0 comments on commit feb2eb2

Please sign in to comment.