|
| 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 | +} |
0 commit comments