import type { ServiceMethodFactory } from "@ethicdevs/react-monolith";
import { GitServer } from "@ethicdevs/fastify-git-server";
import { GitServerServiceDeps } from "./types";
import { ResourceVisibility } from "@prisma/client";
const makeAuthorizationResolver: ServiceMethodFactory<
GitServerServiceDeps,
[string, GitServer.AuthCredentials],
PromiseLike<boolean>
> = ({ cryptoService, request }) => {
return async (repoPath, { username, password }) => {
const [orgSlug, repoSlug] = repoPath.split("/");
const hashedPassword = cryptoService.computeHash(password);
const user = await request.prisma.user.findUnique({
where: {
username,
},
});
if (user == null) {
return false;
}
const org = await request.prisma.organization.findUnique({
include: {
owner: true,
memberships: true,
},
where: {
slug: orgSlug,
},
});
if (org == null) {
return false;
}
const repo = await request.prisma.repository.findFirst({
where: {
slug: repoSlug,
organization: {
slug: orgSlug,
},
},
});
if (repo == null) {
return false;
}
if (
repo.visibility === ResourceVisibility.PUBLIC ||
repo.visibility === ResourceVisibility.UNLISTED
) {
return true;
} else {
return !!(
(org.ownerId === user.id ||
org.memberships.find((m) => m.id === user.id)) &&
hashedPassword === user.hashedPassword
);
}
};
};
export default makeAuthorizationResolver;