This commit is contained in:
Andras Bacsai 2022-09-11 12:20:01 +00:00
parent 3f5108268d
commit f956f612d3

View File

@ -3,15 +3,15 @@ import { compareVersions } from "compare-versions";
import cuid from "cuid"; import cuid from "cuid";
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { import {
asyncExecShell, asyncExecShell,
asyncSleep, asyncSleep,
cleanupDockerStorage, cleanupDockerStorage,
errorHandler, errorHandler,
isDev, isDev,
listSettings, listSettings,
prisma, prisma,
uniqueName, uniqueName,
version, version,
} from "../../../lib/common"; } from "../../../lib/common";
import { supportedServiceTypesAndVersions } from "../../../lib/services/supportedVersions"; import { supportedServiceTypesAndVersions } from "../../../lib/services/supportedVersions";
import { scheduler } from "../../../lib/scheduler"; import { scheduler } from "../../../lib/scheduler";
@ -20,321 +20,321 @@ import type { Login, Update } from ".";
import type { GetCurrentUser } from "./types"; import type { GetCurrentUser } from "./types";
export async function hashPassword(password: string): Promise<string> { export async function hashPassword(password: string): Promise<string> {
const saltRounds = 15; const saltRounds = 15;
return bcrypt.hash(password, saltRounds); return bcrypt.hash(password, saltRounds);
} }
export async function cleanupManually(request: FastifyRequest) { export async function cleanupManually(request: FastifyRequest) {
try { try {
const { serverId } = request.body; const { serverId } = request.body;
const destination = await prisma.destinationDocker.findUnique({ const destination = await prisma.destinationDocker.findUnique({
where: { id: serverId }, where: { id: serverId },
}); });
await cleanupDockerStorage(destination.id, true, true); await cleanupDockerStorage(destination.id, true, true);
return {}; return {};
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function checkUpdate(request: FastifyRequest) { export async function checkUpdate(request: FastifyRequest) {
try { try {
const isStaging = const isStaging =
request.hostname === "staging.coolify.io" || request.hostname === "staging.coolify.io" ||
request.hostname === "arm.coolify.io"; request.hostname === "arm.coolify.io";
const currentVersion = version; const currentVersion = version;
const { data: versions } = await axios.get( const { data: versions } = await axios.get(
`https://get.coollabs.io/versions.json?appId=${process.env["COOLIFY_APP_ID"]}&version=${currentVersion}` `https://get.coollabs.io/versions.json?appId=${process.env["COOLIFY_APP_ID"]}&version=${currentVersion}`
); );
const latestVersion = versions["coolify"].main.version; const latestVersion = versions["coolify"].main.version;
const isUpdateAvailable = compareVersions(latestVersion, currentVersion); const isUpdateAvailable = compareVersions(latestVersion, currentVersion);
if (isStaging) { if (isStaging) {
return { return {
isUpdateAvailable: true, isUpdateAvailable: true,
latestVersion: "next", latestVersion: "next",
}; };
} }
return { return {
isUpdateAvailable: isStaging ? true : isUpdateAvailable === 1, isUpdateAvailable: isStaging ? true : isUpdateAvailable === 1,
latestVersion, latestVersion,
}; };
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function update(request: FastifyRequest<Update>) { export async function update(request: FastifyRequest<Update>) {
const { latestVersion } = request.body; const { latestVersion } = request.body;
try { try {
if (!isDev) { if (!isDev) {
const { isAutoUpdateEnabled } = await prisma.setting.findFirst(); const { isAutoUpdateEnabled } = await prisma.setting.findFirst();
await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`); await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`);
await asyncExecShell(`env | grep COOLIFY > .env`); await asyncExecShell(`env | grep COOLIFY > .env`);
await asyncExecShell( await asyncExecShell(
`sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=${isAutoUpdateEnabled}' .env` `sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=${isAutoUpdateEnabled}' .env`
); );
await asyncExecShell( await asyncExecShell(
`docker run --rm -tid --env-file .env -v /var/run/docker.sock:/var/run/docker.sock -v coolify-db coollabsio/coolify:${latestVersion} /bin/sh -c "env | grep COOLIFY > .env && echo 'TAG=${latestVersion}' >> .env && docker stop -t 0 coolify && docker rm coolify && docker compose up -d --force-recreate"` `docker run --rm -tid --env-file .env -v /var/run/docker.sock:/var/run/docker.sock -v coolify-db coollabsio/coolify:${latestVersion} /bin/sh -c "env | grep COOLIFY > .env && echo 'TAG=${latestVersion}' >> .env && docker stop -t 0 coolify && docker rm coolify && docker compose up -d --force-recreate"`
); );
return {}; return {};
} else { } else {
await asyncSleep(2000); await asyncSleep(2000);
return {}; return {};
} }
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function resetQueue(request: FastifyRequest<any>) { export async function resetQueue(request: FastifyRequest<any>) {
try { try {
const teamId = request.user.teamId; const teamId = request.user.teamId;
if (teamId === "0") { if (teamId === "0") {
await prisma.build.updateMany({ await prisma.build.updateMany({
where: { status: { in: ["queued", "running"] } }, where: { status: { in: ["queued", "running"] } },
data: { status: "canceled" }, data: { status: "canceled" },
}); });
scheduler.workers.get("deployApplication").postMessage("cancel"); scheduler.workers.get("deployApplication").postMessage("cancel");
} }
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function restartCoolify(request: FastifyRequest<any>) { export async function restartCoolify(request: FastifyRequest<any>) {
try { try {
const teamId = request.user.teamId; const teamId = request.user.teamId;
if (teamId === "0") { if (teamId === "0") {
if (!isDev) { if (!isDev) {
asyncExecShell(`docker restart coolify`); asyncExecShell(`docker restart coolify`);
return {}; return {};
} else { } else {
return {}; return {};
} }
} }
throw { throw {
status: 500, status: 500,
message: "You are not authorized to restart Coolify.", message: "You are not authorized to restart Coolify.",
}; };
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function showDashboard(request: FastifyRequest) { export async function showDashboard(request: FastifyRequest) {
try { try {
const userId = request.user.userId; const userId = request.user.userId;
const teamId = request.user.teamId; const teamId = request.user.teamId;
const applications = await prisma.application.findMany({ const applications = await prisma.application.findMany({
where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { settings: true, destinationDocker: true, teams: true }, include: { settings: true, destinationDocker: true, teams: true },
}); });
const databases = await prisma.database.findMany({ const databases = await prisma.database.findMany({
where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { settings: true, destinationDocker: true, teams: true }, include: { settings: true, destinationDocker: true, teams: true },
}); });
const services = await prisma.service.findMany({ const services = await prisma.service.findMany({
where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { destinationDocker: true, teams: true }, include: { destinationDocker: true, teams: true },
}); });
const gitSources = await prisma.gitSource.findMany({ const gitSources = await prisma.gitSource.findMany({
where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { teams: true }, include: { teams: true },
}); });
const destinations = await prisma.destinationDocker.findMany({ const destinations = await prisma.destinationDocker.findMany({
where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } }, where: { teams: { some: { id: teamId === "0" ? undefined : teamId } } },
include: { teams: true }, include: { teams: true },
}); });
const settings = await listSettings(); const settings = await listSettings();
return { return {
applications, applications,
databases, databases,
services, services,
gitSources, gitSources,
destinations, destinations,
settings, settings,
}; };
} catch ({ status, message }) { } catch ({ status, message }) {
return errorHandler({ status, message }); return errorHandler({ status, message });
} }
} }
export async function login( export async function login(
request: FastifyRequest<Login>, request: FastifyRequest<Login>,
reply: FastifyReply reply: FastifyReply
) { ) {
if (request.user) { if (request.user) {
return reply.redirect("/dashboard"); return reply.redirect("/dashboard");
} else { } else {
const { email, password, isLogin } = request.body || {}; const { email, password, isLogin } = request.body || {};
if (!email || !password) { if (!email || !password) {
throw { status: 500, message: "Email and password are required." }; throw { status: 500, message: "Email and password are required." };
} }
const users = await prisma.user.count(); const users = await prisma.user.count();
const userFound = await prisma.user.findUnique({ const userFound = await prisma.user.findUnique({
where: { email }, where: { email },
include: { teams: true, permission: true }, include: { teams: true, permission: true },
rejectOnNotFound: false, rejectOnNotFound: false,
}); });
if (!userFound && isLogin) { if (!userFound && isLogin) {
throw { status: 500, message: "User not found." }; throw { status: 500, message: "User not found." };
} }
const { isRegistrationEnabled, id } = await prisma.setting.findFirst(); const { isRegistrationEnabled, id } = await prisma.setting.findFirst();
let uid = cuid(); let uid = cuid();
let permission = "read"; let permission = "read";
let isAdmin = false; let isAdmin = false;
if (users === 0) { if (users === 0) {
await prisma.setting.update({ await prisma.setting.update({
where: { id }, where: { id },
data: { isRegistrationEnabled: false }, data: { isRegistrationEnabled: false },
}); });
uid = "0"; uid = "0";
} }
if (userFound) { if (userFound) {
if (userFound.type === "email") { if (userFound.type === "email") {
if (userFound.password === "RESETME") { if (userFound.password === "RESETME") {
const hashedPassword = await hashPassword(password); const hashedPassword = await hashPassword(password);
if (userFound.updatedAt < new Date(Date.now() - 1000 * 60 * 10)) { if (userFound.updatedAt < new Date(Date.now() - 1000 * 60 * 10)) {
if (userFound.id === "0") { if (userFound.id === "0") {
await prisma.user.update({ await prisma.user.update({
where: { email: userFound.email }, where: { email: userFound.email },
data: { password: "RESETME" }, data: { password: "RESETME" },
}); });
} else { } else {
await prisma.user.update({ await prisma.user.update({
where: { email: userFound.email }, where: { email: userFound.email },
data: { password: "RESETTIMEOUT" }, data: { password: "RESETTIMEOUT" },
}); });
} }
throw { throw {
status: 500, status: 500,
message: message:
"Password reset link has expired. Please request a new one.", "Password reset link has expired. Please request a new one.",
}; };
} else { } else {
await prisma.user.update({ await prisma.user.update({
where: { email: userFound.email }, where: { email: userFound.email },
data: { password: hashedPassword }, data: { password: hashedPassword },
}); });
return { return {
userId: userFound.id, userId: userFound.id,
teamId: userFound.id, teamId: userFound.id,
permission: userFound.permission, permission: userFound.permission,
isAdmin: true, isAdmin: true,
}; };
} }
} }
const passwordMatch = await bcrypt.compare( const passwordMatch = await bcrypt.compare(
password, password,
userFound.password userFound.password
); );
if (!passwordMatch) { if (!passwordMatch) {
throw { throw {
status: 500, status: 500,
message: "Wrong password or email address.", message: "Wrong password or email address.",
}; };
} }
uid = userFound.id; uid = userFound.id;
isAdmin = true; isAdmin = true;
} }
} else { } else {
permission = "owner"; permission = "owner";
isAdmin = true; isAdmin = true;
if (!isRegistrationEnabled) { if (!isRegistrationEnabled) {
throw { throw {
status: 404, status: 404,
message: "Registration disabled by administrator.", message: "Registration disabled by administrator.",
}; };
} }
const hashedPassword = await hashPassword(password); const hashedPassword = await hashPassword(password);
if (users === 0) { if (users === 0) {
await prisma.user.create({ await prisma.user.create({
data: { data: {
id: uid, id: uid,
email, email,
password: hashedPassword, password: hashedPassword,
type: "email", type: "email",
teams: { teams: {
create: { create: {
id: uid, id: uid,
name: uniqueName(), name: uniqueName(),
destinationDocker: { connect: { network: "coolify" } }, destinationDocker: { connect: { network: "coolify" } },
}, },
}, },
permission: { create: { teamId: uid, permission: "owner" } }, permission: { create: { teamId: uid, permission: "owner" } },
}, },
include: { teams: true }, include: { teams: true },
}); });
} else { } else {
await prisma.user.create({ await prisma.user.create({
data: { data: {
id: uid, id: uid,
email, email,
password: hashedPassword, password: hashedPassword,
type: "email", type: "email",
teams: { teams: {
create: { create: {
id: uid, id: uid,
name: uniqueName(), name: uniqueName(),
}, },
}, },
permission: { create: { teamId: uid, permission: "owner" } }, permission: { create: { teamId: uid, permission: "owner" } },
}, },
include: { teams: true }, include: { teams: true },
}); });
} }
} }
return { return {
userId: uid, userId: uid,
teamId: uid, teamId: uid,
permission, permission,
isAdmin, isAdmin,
}; };
} }
} }
export async function getCurrentUser( export async function getCurrentUser(
request: FastifyRequest<GetCurrentUser>, request: FastifyRequest<GetCurrentUser>,
fastify fastify
) { ) {
let token = null; let token = null;
const { teamId } = request.query; const { teamId } = request.query;
try { try {
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: { id: request.user.userId }, where: { id: request.user.userId },
}); });
if (!user) { if (!user) {
throw "User not found"; throw "User not found";
} }
} catch (error) { } catch (error) {
throw { status: 401, message: error }; throw { status: 401, message: error };
} }
if (teamId) { if (teamId) {
try { try {
const user = await prisma.user.findFirst({ const user = await prisma.user.findFirst({
where: { id: request.user.userId, teams: { some: { id: teamId } } }, where: { id: request.user.userId, teams: { some: { id: teamId } } },
include: { teams: true, permission: true }, include: { teams: true, permission: true },
}); });
if (user) { if (user) {
const permission = user.permission.find( const permission = user.permission.find(
(p) => p.teamId === teamId (p) => p.teamId === teamId
).permission; ).permission;
const payload = { const payload = {
...request.user, ...request.user,
teamId, teamId,
permission: permission || null, permission: permission || null,
isAdmin: permission === "owner" || permission === "admin", isAdmin: permission === "owner" || permission === "admin",
}; };
token = fastify.jwt.sign(payload); token = fastify.jwt.sign(payload);
} }
} catch (error) { } catch (error) {
// No new token -> not switching teams // No new token -> not switching teams
} }
} }
return { return {
settings: await prisma.setting.findFirst(), settings: await prisma.setting.findFirst(),
supportedServiceTypesAndVersions, supportedServiceTypesAndVersions,
token, token,
...request.user, ...request.user,
}; };
} }