Skip to content

Commit

Permalink
feat: add modifyPassword
Browse files Browse the repository at this point in the history
  • Loading branch information
AsyncFox committed Dec 6, 2023
1 parent 8176dd9 commit 306b4af
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion server/trpc/controllers/user.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import bcrypt from 'bcrypt';
import { and, eq } from 'drizzle-orm';
import { LibsqlError } from '@libsql/client';
import { type TNewUser, db } from '../../db/db';
import { type TNewUser, type TRawUser, db } from '../../db/db';
import { refreshTokens, users } from '../../db/schema/';
import { Auth } from '../utils/auth';

Expand Down Expand Up @@ -55,4 +55,14 @@ export class UserController {
const newAccessToken = await this.auth.produceAccessToken(id);
return { accessToken: newAccessToken, refreshToken: newRefreshToken };
}

async modifyPassword(user: TRawUser, oldPassword: string, newPassword: string) {
if (!await bcrypt.compare(oldPassword, user.password))
return { success: false, message: '旧密码不正确' };
if (newPassword === oldPassword)
return { success: false, message: '新密码不能与旧密码相同' };

await db.update(users).set({ password: await bcrypt.hash(newPassword, 8) }).where(eq(users.id, user.id));
return { success: true, message: '修改成功' };
}
}
10 changes: 10 additions & 0 deletions server/trpc/routers/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,14 @@ export const userRouter = router({
return res;
}),

modifyPassword: protectedProcedure
.input(z.object({ oldPassword: z.string(), newPassword: z.string().min(8, { message: '用户密码长度应至少为8' }) }))
.mutation(async ({ ctx, input }) => {
const res = await ctx.userController.modifyPassword(ctx.user, input.oldPassword, input.newPassword);
if (!res.success)
throw new TRPCError({ code: 'BAD_REQUEST', message: res.message });
else
return res;
}),

});

0 comments on commit 306b4af

Please sign in to comment.