You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.2 KiB
34 lines
1.2 KiB
import { getRequestIP } from "h3";
|
|
import { loginUser } from "#server/service/auth";
|
|
import { toPublicAuthError } from "#server/service/auth/errors";
|
|
import { setSessionCookie } from "#server/service/auth/cookie";
|
|
import { captchaConsume } from "#server/service/captcha/store";
|
|
import { assertLoginRegisterCaptchaFieldsPresent } from "#server/service/captcha/validate-body";
|
|
import { assertUnderRateLimit } from "#server/utils/simple-rate-limit";
|
|
|
|
export default defineWrappedResponseHandler(async (event) => {
|
|
const ip = getRequestIP(event, { xForwardedFor: true }) ?? "unknown";
|
|
assertUnderRateLimit(`auth-login:${ip}`, 30, 60_000);
|
|
|
|
const body = await readBody(event);
|
|
assertLoginRegisterCaptchaFieldsPresent(body);
|
|
if (!captchaConsume(body.captchaId, body.captchaAnswer)) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: "验证码错误或已过期,请重试",
|
|
});
|
|
}
|
|
|
|
try {
|
|
const result = await loginUser({
|
|
username: body.username,
|
|
password: body.password,
|
|
});
|
|
setSessionCookie(event, result.sessionId);
|
|
return R.success({
|
|
user: result.user,
|
|
});
|
|
} catch (err) {
|
|
throw toPublicAuthError(err);
|
|
}
|
|
});
|
|
|