cal.pub0.org/apps/web/pages/api/user/avatar.ts

73 lines
1.9 KiB
TypeScript
Raw Normal View History

import crypto from "crypto";
import type { NextApiRequest, NextApiResponse } from "next";
2022-12-08 09:50:03 +00:00
import { z } from "zod";
import { getPlaceholderAvatar } from "@calcom/lib/getPlaceholderAvatar";
import prisma from "@calcom/prisma";
import { defaultAvatarSrc } from "@lib/profile";
2022-12-08 09:50:03 +00:00
const querySchema = z
.object({
username: z.string(),
teamname: z.string(),
})
.partial();
async function getIdentityData(req: NextApiRequest) {
const { username, teamname } = querySchema.parse(req.query);
if (username) {
const user = await prisma.user.findUnique({
2022-12-08 09:50:03 +00:00
where: { username },
select: { avatar: true, email: true },
});
2022-12-08 09:50:03 +00:00
return {
name: username,
email: user?.email,
avatar: user?.avatar,
};
2022-12-08 09:50:03 +00:00
}
if (teamname) {
const team = await prisma.team.findUnique({
2022-12-08 09:50:03 +00:00
where: { slug: teamname },
select: { logo: true },
});
2022-12-08 09:50:03 +00:00
return {
name: teamname,
2022-12-08 09:50:03 +00:00
email: null,
avatar: team?.logo || getPlaceholderAvatar(null, teamname),
};
}
2022-12-08 09:50:03 +00:00
}
2022-12-08 09:50:03 +00:00
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const identity = await getIdentityData(req);
const img = identity?.avatar;
// If image isn't set or links to this route itself, use default avatar
2022-12-08 09:50:03 +00:00
if (!img) {
res.writeHead(302, {
2022-12-08 09:50:03 +00:00
Location: defaultAvatarSrc({
md5: crypto
.createHash("md5")
.update(identity?.email || "guest@example.com")
.digest("hex"),
}),
});
2022-12-08 09:50:03 +00:00
return res.end();
}
2022-12-08 09:50:03 +00:00
if (!img.includes("data:image")) {
res.writeHead(302, { Location: img });
return res.end();
}
2022-12-08 09:50:03 +00:00
const decoded = img.toString().replace("data:image/png;base64,", "").replace("data:image/jpeg;base64,", "");
const imageResp = Buffer.from(decoded, "base64");
res.writeHead(200, {
"Content-Type": "image/png",
"Content-Length": imageResp.length,
});
res.end(imageResp);
}