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.
45 lines
1.5 KiB
45 lines
1.5 KiB
import { dbGlobal } from "drizzle-pkg/lib/db";
|
|
import { users } from "drizzle-pkg/lib/schema/auth";
|
|
import { eq } from "drizzle-orm";
|
|
import { UNAUTHORIZED_MESSAGE } from "#server/constants/auth";
|
|
import { clearSessionCookie } from "#server/service/auth/cookie";
|
|
import { toPublicAuthError } from "#server/service/auth/errors";
|
|
import { getCache, setCache, delCache, requireUser } from "#server/utils/context";
|
|
|
|
export default defineWrappedResponseHandler(async (event) => {
|
|
try {
|
|
const user = await requireUser(event);
|
|
if (!user) {
|
|
clearSessionCookie(event);
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: UNAUTHORIZED_MESSAGE,
|
|
});
|
|
}
|
|
|
|
const cacheKey = `auth:me:${user.id}`;
|
|
const cached = await getCache<{ user: { id: number, username: string, role: string, nickname: string | null, avatar: string | null } }>(cacheKey);
|
|
if (cached) return R.success(cached);
|
|
|
|
const [row] = await dbGlobal
|
|
.select({
|
|
nickname: users.nickname,
|
|
avatar: users.avatar,
|
|
})
|
|
.from(users)
|
|
.where(eq(users.id, user.id))
|
|
.limit(1);
|
|
|
|
const result = {
|
|
user: {
|
|
...user,
|
|
nickname: row?.nickname ?? null,
|
|
avatar: row?.avatar ?? null,
|
|
},
|
|
};
|
|
await setCache(cacheKey, result, 60);
|
|
return R.success(result);
|
|
} catch (err) {
|
|
throw toPublicAuthError(err);
|
|
}
|
|
});
|
|
|