feat: Add resetPassword mutation

This commit is contained in:
Faruk AYDIN
2023-02-19 11:04:17 +01:00
parent 8ea176b5f0
commit 9dbfcf4262
4 changed files with 59 additions and 1 deletions

View File

@@ -15,6 +15,7 @@ import deleteStep from './mutations/delete-step';
import createUser from './mutations/create-user.ee';
import updateUser from './mutations/update-user';
import forgotPassword from './mutations/forgot-password.ee';
import resetPassword from './mutations/reset-password.ee';
import login from './mutations/login';
const mutationResolvers = {
@@ -35,6 +36,7 @@ const mutationResolvers = {
createUser,
updateUser,
forgotPassword,
resetPassword,
login,
};

View File

@@ -0,0 +1,30 @@
import User from '../../models/user';
type Params = {
input: {
token: string;
password: string;
};
};
const resetPassword = async (_parent: unknown, params: Params) => {
const { token, password } = params.input;
if (!token) {
throw new Error('Reset password token is required!');
}
const user = await User.query().findOne({ reset_password_token: token });
if (!user || !user.isResetPasswordTokenValid()) {
throw new Error(
'Reset password link is not valid or expired. Try generating a new link.'
);
}
await user.resetPassword(password);
return;
};
export default resetPassword;

View File

@@ -51,6 +51,7 @@ type Mutation {
createUser(input: CreateUserInput): User
updateUser(input: UpdateUserInput): User
forgotPassword(input: ForgotPasswordInput): Boolean
resetPassword(input: ResetPasswordInput): Boolean
login(input: LoginInput): Auth
}
@@ -313,7 +314,12 @@ input UpdateUserInput {
}
input ForgotPasswordInput {
email: String
email: String!
}
input ResetPasswordInput {
token: String!
password: String!
}
input LoginInput {

View File

@@ -87,6 +87,26 @@ class User extends Base {
await this.$query().patch({ resetPasswordToken, resetPasswordTokenSentAt });
}
async resetPassword(password: string) {
return await this.$query().patch({
resetPasswordToken: null,
resetPasswordTokenSentAt: null,
password,
});
}
async isResetPasswordTokenValid() {
if (!this.resetPasswordTokenSentAt) {
return false;
}
const sentAt = new Date(this.resetPasswordTokenSentAt);
const now = new Date();
const fourHoursInMilliseconds = 1000 * 60 * 60 * 4;
return now.getTime() - sentAt.getTime() < fourHoursInMilliseconds;
}
async generateHash() {
this.password = await bcrypt.hash(this.password, 10);
}