Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Verify Email and Reset Password in Flutter

Hii! Flutter Developer, I am here with another interesting flutter blog. In this blog, we shall learn how to authenticate using firebase API, verify the user email with OTP learn how to reset the password.

Using firebase_auth the package you can also do the same. Using this package is you can use the resetPassword method to send the reset password link on the user’s mail and there you can reset the password. But I wanted to reset the password from the app itself. So I researched about it and I got the following solution.

While making this app I came across a bug, that the firebase backend accepts the anonymous email while authentication. In general, accepting anonymous emails is not a good practice. So it would be really great to verify the user’s email with an OTP and then reset the password.

Before getting into the coding part let me first explain to you what we are going to build in the app. Firstly we will make a SignUp Login screen that will handle the authentication. On the Login page, we will use Forgot Password bottom to reset the password. On tapping it will navigate us to forget password screen, it will have one reset password button. This button will trigger the verify method that will send an OTP to the given mail. After that will build a screen to get the OTP from the user and then we will verify it, if it is right then we will navigate to a new screen that will take the new password from the user and update it on the database using API.


Let’s look at the packages used:

http: ^0.12.0+2
email_auth: ^0.0.1
firebase_core:
shared_preferences: ^2.0.5

http package is used to handle the API request. email_auth package is used to validate the mail. firebase_core is used for firebase integration with the app. shared_preferences package is used to store the auth TOKEN in-app local storage.

Configure app and firebase:

Firebase
Backed by Google and loved by app development teams – from startups to global enterprises Save the date – Google I/O…firebase.google.co

  • Go to the firebase website and connect your app with firebase.
  • Go to the authentication tab and enable the email password authentication method.
  • Open project setting to get the Web API key .
We will use this API key to handle API requests.

Now will start writing our code…

Offical Documentation

Firebase Auth REST API
AnalyticsUserPropertyAllowAdPersonalizationSignalsfirebase.google.com

First of all, we will build our authentication services that will be required to handle our authentication.

Create a class AuthServices . In this class, we will make _authenticate, signUp, login and changePassword .

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class AuthServices {
String _token;

Future<void> _authenticate(
String email, String password, String urlSegment) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final url =
'https://identitytoolkit..com/v1/accounts:$urlSegment?key='YOUR WEB API KEY';
final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
'returnSecureToken': true,
},
),
);
final responseData = json.decode(response.body);
 print(responseData);
_token = responseData['idToken'];
 print('************************' + _token.toString());
try {
if (urlSegment == "signUp") {
sharedPreferences.setString("token", _token.toString());
 }
} catch (e) {
print(e);
}
print("true");
}

Future<void> signUp(String email, String password) async {
return _authenticate(email, password, 'signUp');
}

Future<void> login(String email, String password) async {
return _authenticate(email, password, 'signInWithPassword');
}

Future<void> changePassword(String newPassword) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
print(newPassword);
_token = sharedPreferences.getString("token");
final url =
'https://identitytoolkit.googleapis.com/v1/accounts:update?key='YOUR WEB API KEY';
try {
await http.post(
url,
body: json.encode(
{
'idToken': _token,
'password': newPassword,
'returnSecureToken': true,
},
),
);
} catch (error) {
throw error;
}
}
}

_authenticate method

Here we have created a method _authenticate , this method takes three arguments email, password and urlSagment . It will handle the app signUp and sign in or any other desired activity using the urlSagement .

final url =
'https://identitytoolkit..com/v1/accounts:$urlSegment?key='YOUR WEB API KEY';

This URL is used to send API request to the firebase database, at the end of this URL a key is required i.e. the Web API Key that we got from the firebase project setting tab.

final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
'returnSecureToken': true,
},
),
);

Using the HTTP package we will send a post request that will intake the url as URL, inside the body, we will pass three fields email password and returnSecureToken . returnSecureToken is set to true because we will need token to change the password that is generated while signing Up the user.

final responseData = json.decode(response.body);
print(responseData);
_token = responseData['idToken'];

We will now decode the responseData and get the idToken in a _token variable.

try {
if (urlSegment == "signUp") {
sharedPreferences.setString("token", _token.toString());
}
} catch (e) {
print(e);
}

We need to store the token somewhere inside the local storage or on a database because we will need this token at the time of change password functionality. So we will be using SharedPreferences to store the token and we will fetch it when needed.

signUp method

Future<void> signUp(String email, String password) async {
return _authenticate(email, password, 'signUp');
}

In this method, we are returning the _authenticate method with signUp as the urlSagment.

login method

Future<void> login(String email, String password) async {
return _authenticate(email, password, 'signInWithPassword');
}

In this method, we are returning the _authenticate method with signInWithPassword as the urlSagment.

changePassword method

SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
_token = sharedPreferences.getString("token");

We will first fetch out token from our local database. and store it in our _token variable.

final url =
'https://identitytoolkit.googleapis.com/v1/accounts:update?key='YOUR WEB API KEY';

We will need an update urlSagment to update the password.

try {
await http.post(
url,
body: json.encode(
{
'idToken': _token,
'password': newPassword,
'returnSecureToken': true,
},
),
);
} catch (error) {
throw error;
}

Using the post method we will change the user password. The body will take three fields idToken, password, and returnSecureToken .

The above class will be able to handle our signUp, login, and changepassword functionality. Now we will discuss how we can verify the mail.

Verify email with OTP

Sending OTP to the email.

void sendOtp() async {
EmailAuth.sessionName = "Company Name";
bool result =
await EmailAuth.sendOtp(receiverMail: _emailController.value.text);
if (result) {
setState(() {
submitValid = true;
});
}
}

This method will send an OTP on the given email. EmailAuth package is used to send the OTP to the email. sendOtp method will return true if the OTP is sent, if not it will return false.

void verify() {
EmailAuth.validate(
receiverMail: _emailController.value.text,
userOTP: _otpController.value.text);
}

EmailAuth package provides us validate method to verify the OTP entered by the users.

+++OTP email received from firebase+++

GitHub Link:

Anmol Gupta-aeologic/reset_password
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

🌸🌼🌸 Thank you for reading. 🌸🌼🌸


Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app 987tr project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Leave comment

Your email address will not be published. Required fields are marked with *.