Add user change password
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import type { BUN_SQLITE_WGUI_USERS } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import type { ApiReqParams, TableType } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject> = async (
|
||||
params,
|
||||
) => {
|
||||
const req = params.req;
|
||||
const body = params.body as ApiReqParams;
|
||||
|
||||
if (req.method !== "POST") {
|
||||
return {
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
|
||||
const { user } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Unauthorized`,
|
||||
logoutUser: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const { new_password, confirm_password } = body;
|
||||
|
||||
if (!new_password) {
|
||||
throw new Error(`Please enter a new password`);
|
||||
}
|
||||
|
||||
if (new_password !== confirm_password) {
|
||||
throw new Error(`New passwords don't match`);
|
||||
}
|
||||
|
||||
const new_password_hash = await Bun.password.hash(new_password, {
|
||||
algorithm: "bcrypt",
|
||||
cost: AppData["HashCost"],
|
||||
});
|
||||
|
||||
const update_res = await BunSQLite.update<
|
||||
BUN_SQLITE_WGUI_USERS,
|
||||
TableType
|
||||
>({
|
||||
table: "users",
|
||||
data: {
|
||||
password: new_password_hash,
|
||||
},
|
||||
targetId: user.id,
|
||||
});
|
||||
|
||||
if (!update_res.success) {
|
||||
throw new Error(`Couldn't update password`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: `Password updated successfully`,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user