changePassword method
Future<void>
changePassword(
- String id, {
- required String oldPassword,
- required String newPassword,
- bool doLogoutFromAllDevices = true,
override
Implementation
@override
Future<void> changePassword(
String id, {
required String oldPassword,
required String newPassword,
/// this will prevent others from using the same jwt to log in after the password gets changed
bool doLogoutFromAllDevices = true,
}) async {
//? if old password is the same as new password
if (oldPassword == newPassword) {
throw Exception('oldPassword must be different from newPassword');
}
//? checking for the user password if it's right
AuthModel? authModel = await getUserById(id);
if (authModel == null) {
throw NoUserRegisteredException();
}
bool rightPassword =
SecurePassword(oldPassword).checkPassword(authModel.passwordHash);
if (!rightPassword) {
throw InvalidPassword();
}
// if reached here this means that the user email and password are right
// the user doesn't need to be logged in to do this
// //? checking if i need to log out from all other devices
if (doLogoutFromAllDevices) {
await logoutFromAllDevices(authModel.id);
await updateAuthInfo(
authModel.id,
ModelFields.password,
DateTime.now().toIso8601String(),
);
}
//? changing the password
String passwordHash = SecurePassword(newPassword).getPasswordHash();
var collection =
dbService.mongoDbController.collection(app.authSettings.collectionName);
var selector = where.eq(ModelFields.id, id);
var updateQuery = modify.set(ModelFields.passwordHash, passwordHash);
var res = await collection.updateOne(selector, updateQuery);
if (res.failure) {
throw Exception('can\'t edit the password');
}
}