mirror of
https://github.com/fosrl/pangolin.git
synced 2025-07-30 23:55:49 +02:00
Merge branch 'main' of https://github.com/fosrl/pangolin
This commit is contained in:
commit
907504eefb
29 changed files with 411 additions and 254 deletions
42
server/auth/checkValidInvite.ts
Normal file
42
server/auth/checkValidInvite.ts
Normal file
|
@ -0,0 +1,42 @@
|
|||
import db from "@server/db";
|
||||
import { UserInvite, userInvites } from "@server/db/schema";
|
||||
import { isWithinExpirationDate } from "oslo";
|
||||
import { verifyPassword } from "./password";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
export async function checkValidInvite({
|
||||
inviteId,
|
||||
token
|
||||
}: {
|
||||
inviteId: string;
|
||||
token: string;
|
||||
}): Promise<{ error?: string; existingInvite?: UserInvite }> {
|
||||
const existingInvite = await db
|
||||
.select()
|
||||
.from(userInvites)
|
||||
.where(eq(userInvites.inviteId, inviteId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingInvite.length) {
|
||||
return {
|
||||
error: "Invite ID or token is invalid"
|
||||
};
|
||||
}
|
||||
|
||||
if (!isWithinExpirationDate(new Date(existingInvite[0].expiresAt))) {
|
||||
return {
|
||||
error: "Invite has expired"
|
||||
};
|
||||
}
|
||||
|
||||
const validToken = await verifyPassword(token, existingInvite[0].tokenHash);
|
||||
if (!validToken) {
|
||||
return {
|
||||
error: "Invite ID or token is invalid"
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
existingInvite: existingInvite[0]
|
||||
};
|
||||
}
|
|
@ -62,12 +62,17 @@ const environmentSchema = z.object({
|
|||
no_reply: z.string().email().optional()
|
||||
})
|
||||
.optional(),
|
||||
users: z.object({
|
||||
server_admin: z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string()
|
||||
})
|
||||
}),
|
||||
flags: z
|
||||
.object({
|
||||
allow_org_subdomain_changing: z.boolean().optional(),
|
||||
require_email_verification: z.boolean().optional(),
|
||||
disable_signup_without_invite: z.boolean().optional(),
|
||||
require_signup_secret: z.boolean().optional()
|
||||
disable_user_create_org: z.boolean().optional()
|
||||
})
|
||||
.optional()
|
||||
});
|
||||
|
@ -156,5 +161,13 @@ process.env.SESSION_COOKIE_NAME = parsedConfig.data.server.session_cookie_name;
|
|||
process.env.RESOURCE_SESSION_COOKIE_NAME =
|
||||
parsedConfig.data.server.resource_session_cookie_name;
|
||||
process.env.EMAIL_ENABLED = parsedConfig.data.email ? "true" : "false";
|
||||
process.env.DISABLE_SIGNUP_WITHOUT_INVITE = parsedConfig.data.flags
|
||||
?.disable_signup_without_invite
|
||||
? "true"
|
||||
: "false";
|
||||
process.env.DISABLE_USER_CREATE_ORG = parsedConfig.data.flags
|
||||
?.disable_user_create_org
|
||||
? "true"
|
||||
: "false";
|
||||
|
||||
export default parsedConfig.data;
|
||||
|
|
|
@ -89,7 +89,10 @@ export const users = sqliteTable("user", {
|
|||
emailVerified: integer("emailVerified", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
dateCreated: text("dateCreated").notNull()
|
||||
dateCreated: text("dateCreated").notNull(),
|
||||
serverAdmin: integer("serverAdmin", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false)
|
||||
});
|
||||
|
||||
export const newts = sqliteTable("newt", {
|
||||
|
|
|
@ -7,7 +7,7 @@ import {
|
|||
Preview,
|
||||
Section,
|
||||
Text,
|
||||
Tailwind,
|
||||
Tailwind
|
||||
} from "@react-email/components";
|
||||
import * as React from "react";
|
||||
|
||||
|
@ -20,7 +20,7 @@ interface VerifyEmailProps {
|
|||
export const VerifyEmail = ({
|
||||
username,
|
||||
verificationCode,
|
||||
verifyLink,
|
||||
verifyLink
|
||||
}: VerifyEmailProps) => {
|
||||
const previewText = `Verify your email, ${username}`;
|
||||
|
||||
|
@ -33,10 +33,10 @@ export const VerifyEmail = ({
|
|||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
primary: "#F97317",
|
||||
},
|
||||
},
|
||||
},
|
||||
primary: "#F97317"
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Body className="font-sans">
|
||||
|
@ -48,11 +48,8 @@ export const VerifyEmail = ({
|
|||
Hi {username || "there"},
|
||||
</Text>
|
||||
<Text className="text-base text-gray-700 mt-2">
|
||||
You’ve requested to verify your email. Please{" "}
|
||||
<a href={verifyLink} className="text-primary">
|
||||
click here
|
||||
</a>{" "}
|
||||
to verify your email, then enter the following code:
|
||||
You’ve requested to verify your email. Please use
|
||||
the code below to complete the verification process upon logging in.
|
||||
</Text>
|
||||
<Section className="text-center my-6">
|
||||
<Text className="inline-block bg-primary text-xl font-bold text-white py-2 px-4 border border-gray-300 rounded-xl">
|
||||
|
|
|
@ -16,16 +16,19 @@ import {
|
|||
createSession,
|
||||
generateId,
|
||||
generateSessionToken,
|
||||
serializeSessionCookie,
|
||||
serializeSessionCookie
|
||||
} from "@server/auth";
|
||||
import { ActionsEnum } from "@server/auth/actions";
|
||||
import config from "@server/config";
|
||||
import logger from "@server/logger";
|
||||
import { hashPassword } from "@server/auth/password";
|
||||
import { checkValidInvite } from "@server/auth/checkValidInvite";
|
||||
|
||||
export const signupBodySchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: passwordSchema,
|
||||
inviteToken: z.string().optional(),
|
||||
inviteId: z.string().optional()
|
||||
});
|
||||
|
||||
export type SignUpBody = z.infer<typeof signupBodySchema>;
|
||||
|
@ -50,11 +53,39 @@ export async function signup(
|
|||
);
|
||||
}
|
||||
|
||||
const { email, password } = parsedBody.data;
|
||||
const { email, password, inviteToken, inviteId } = parsedBody.data;
|
||||
|
||||
logger.debug("signup", { email, password, inviteToken, inviteId });
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
const userId = generateId(15);
|
||||
|
||||
if (config.flags?.disable_signup_without_invite) {
|
||||
if (!inviteToken || !inviteId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Signups are disabled without an invite code"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { error, existingInvite } = await checkValidInvite({
|
||||
token: inviteToken,
|
||||
inviteId
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, error));
|
||||
}
|
||||
|
||||
if (!existingInvite) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invite does not exist")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const existing = await db
|
||||
.select()
|
||||
|
@ -89,12 +120,15 @@ export async function signup(
|
|||
|
||||
if (diff < 2) {
|
||||
// If the user was created less than 2 hours ago, we don't want to create a new user
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"A verification email was already sent to this email address. Please check your email for the verification code."
|
||||
)
|
||||
);
|
||||
return response<SignUpResponse>(res, {
|
||||
data: {
|
||||
emailVerificationRequired: true
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: `A user with that email address already exists. We sent an email to ${email} with a verification code.`,
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} else {
|
||||
// If the user was created more than 2 hours ago, we want to delete the old user and create a new one
|
||||
await db.delete(users).where(eq(users.userId, user.userId));
|
||||
|
@ -105,7 +139,7 @@ export async function signup(
|
|||
userId: userId,
|
||||
email: email,
|
||||
passwordHash,
|
||||
dateCreated: moment().toISOString(),
|
||||
dateCreated: moment().toISOString()
|
||||
});
|
||||
|
||||
// give the user their default permissions:
|
||||
|
@ -125,12 +159,12 @@ export async function signup(
|
|||
|
||||
return response<SignUpResponse>(res, {
|
||||
data: {
|
||||
emailVerificationRequired: true,
|
||||
emailVerificationRequired: true
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: `User created successfully. We sent an email to ${email} with a verification code.`,
|
||||
status: HttpCode.OK,
|
||||
status: HttpCode.OK
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -139,7 +173,7 @@ export async function signup(
|
|||
success: true,
|
||||
error: false,
|
||||
message: "User created successfully",
|
||||
status: HttpCode.OK,
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof SqliteError && e.code === "SQLITE_CONSTRAINT_UNIQUE") {
|
||||
|
|
|
@ -28,6 +28,18 @@ export async function createOrg(
|
|||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
// should this be in a middleware?
|
||||
if (config.flags?.disable_user_create_org) {
|
||||
if (!req.user?.serverAdmin) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"Only server admins can create organizations"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const parsedBody = createOrgSchema.safeParse(req.body);
|
||||
if (!parsedBody.success) {
|
||||
return next(
|
||||
|
|
|
@ -11,6 +11,7 @@ import logger from "@server/logger";
|
|||
import { fromError } from "zod-validation-error";
|
||||
import { isWithinExpirationDate } from "oslo";
|
||||
import { verifyPassword } from "@server/auth/password";
|
||||
import { checkValidInvite } from "@server/auth/checkValidInvite";
|
||||
|
||||
const acceptInviteBodySchema = z
|
||||
.object({
|
||||
|
@ -42,44 +43,25 @@ export async function acceptInvite(
|
|||
|
||||
const { token, inviteId } = parsedBody.data;
|
||||
|
||||
const existingInvite = await db
|
||||
.select()
|
||||
.from(userInvites)
|
||||
.where(eq(userInvites.inviteId, inviteId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingInvite.length) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invite ID or token is invalid"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!isWithinExpirationDate(new Date(existingInvite[0].expiresAt))) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invite has expired")
|
||||
);
|
||||
}
|
||||
|
||||
const validToken = await verifyPassword(
|
||||
const { error, existingInvite } = await checkValidInvite({
|
||||
token,
|
||||
existingInvite[0].tokenHash
|
||||
);
|
||||
if (!validToken) {
|
||||
inviteId
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return next(createHttpError(HttpCode.BAD_REQUEST, error));
|
||||
}
|
||||
|
||||
if (!existingInvite) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invite ID or token is invalid"
|
||||
)
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invite does not exist")
|
||||
);
|
||||
}
|
||||
|
||||
const existingUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, existingInvite[0].email))
|
||||
.where(eq(users.email, existingInvite.email))
|
||||
.limit(1);
|
||||
if (!existingUser.length) {
|
||||
return next(
|
||||
|
@ -90,7 +72,7 @@ export async function acceptInvite(
|
|||
);
|
||||
}
|
||||
|
||||
if (req.user && req.user.email !== existingInvite[0].email) {
|
||||
if (req.user && req.user.email !== existingInvite.email) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
|
@ -104,7 +86,7 @@ export async function acceptInvite(
|
|||
const existingRole = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(eq(roles.roleId, existingInvite[0].roleId))
|
||||
.where(eq(roles.roleId, existingInvite.roleId))
|
||||
.limit(1);
|
||||
if (existingRole.length) {
|
||||
roleId = existingRole[0].roleId;
|
||||
|
@ -122,8 +104,8 @@ export async function acceptInvite(
|
|||
// add the user to the org
|
||||
await trx.insert(userOrgs).values({
|
||||
userId: existingUser[0].userId,
|
||||
orgId: existingInvite[0].orgId,
|
||||
roleId: existingInvite[0].roleId
|
||||
orgId: existingInvite.orgId,
|
||||
roleId: existingInvite.roleId
|
||||
});
|
||||
|
||||
// delete the invite
|
||||
|
@ -131,9 +113,9 @@ export async function acceptInvite(
|
|||
.delete(userInvites)
|
||||
.where(eq(userInvites.inviteId, inviteId));
|
||||
});
|
||||
|
||||
|
||||
return response<AcceptInviteResponse>(res, {
|
||||
data: { accepted: true, orgId: existingInvite[0].orgId },
|
||||
data: { accepted: true, orgId: existingInvite.orgId },
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Invite accepted",
|
||||
|
|
|
@ -15,6 +15,7 @@ async function queryUser(userId: string) {
|
|||
email: users.email,
|
||||
twoFactorEnabled: users.twoFactorEnabled,
|
||||
emailVerified: users.emailVerified,
|
||||
serverAdmin: users.serverAdmin
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.userId, userId))
|
||||
|
@ -56,7 +57,7 @@ export async function getUser(
|
|||
success: true,
|
||||
error: false,
|
||||
message: "User retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
|
|
|
@ -7,9 +7,9 @@ import logger from "@server/logger";
|
|||
export async function copyInConfig() {
|
||||
// create a url from config.app.base_url and get the hostname
|
||||
const domain = new URL(config.app.base_url).hostname;
|
||||
|
||||
|
||||
// update the domain on all of the orgs where the domain is not equal to the new domain
|
||||
// TODO: eventually each org could have a unique domain that we do not want to overwrite, so this will be unnecessary
|
||||
await db.update(orgs).set({ domain }).where(ne(orgs.domain, domain));
|
||||
logger.debug("Updated orgs with new domain");
|
||||
}
|
||||
logger.info(`Updated orgs with new domain (${domain})`);
|
||||
}
|
||||
|
|
|
@ -36,7 +36,7 @@ export async function ensureActions() {
|
|||
defaultRoles.map((role) => ({
|
||||
roleId: role.roleId!,
|
||||
actionId,
|
||||
orgId: role.orgId!,
|
||||
orgId: role.orgId!
|
||||
}))
|
||||
)
|
||||
.execute();
|
||||
|
@ -68,7 +68,7 @@ export async function createAdminRole(orgId: string) {
|
|||
orgId,
|
||||
isAdmin: true,
|
||||
name: "Admin",
|
||||
description: "Admin role with the most permissions",
|
||||
description: "Admin role with the most permissions"
|
||||
})
|
||||
.returning({ roleId: roles.roleId })
|
||||
.execute();
|
||||
|
@ -92,7 +92,7 @@ export async function createAdminRole(orgId: string) {
|
|||
actionIds.map((action) => ({
|
||||
roleId,
|
||||
actionId: action.actionId,
|
||||
orgId,
|
||||
orgId
|
||||
}))
|
||||
)
|
||||
.execute();
|
||||
|
|
|
@ -2,10 +2,17 @@ import { ensureActions } from "./ensureActions";
|
|||
import { copyInConfig } from "./copyInConfig";
|
||||
import logger from "@server/logger";
|
||||
import { runMigrations } from "./migrations";
|
||||
import { setupServerAdmin } from "./setupServerAdmin";
|
||||
|
||||
export async function runSetupFunctions() {
|
||||
logger.info(`Setup for version ${process.env.APP_VERSION}`);
|
||||
await runMigrations(); // run the migrations
|
||||
await ensureActions(); // make sure all of the actions are in the db and the roles
|
||||
await copyInConfig(); // copy in the config to the db as needed
|
||||
}
|
||||
try {
|
||||
logger.info(`Setup for version ${process.env.APP_VERSION}`);
|
||||
await runMigrations(); // run the migrations
|
||||
await copyInConfig(); // copy in the config to the db as needed
|
||||
await setupServerAdmin();
|
||||
await ensureActions(); // make sure all of the actions are in the db and the roles
|
||||
} catch (error) {
|
||||
logger.error("Error running setup functions", error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
|
86
server/setup/setupServerAdmin.ts
Normal file
86
server/setup/setupServerAdmin.ts
Normal file
|
@ -0,0 +1,86 @@
|
|||
import { generateId, invalidateAllSessions } from "@server/auth";
|
||||
import { hashPassword, verifyPassword } from "@server/auth/password";
|
||||
import { passwordSchema } from "@server/auth/passwordSchema";
|
||||
import config from "@server/config";
|
||||
import db from "@server/db";
|
||||
import { users } from "@server/db/schema";
|
||||
import logger from "@server/logger";
|
||||
import { eq } from "drizzle-orm";
|
||||
import moment from "moment";
|
||||
import { fromError } from "zod-validation-error";
|
||||
|
||||
export async function setupServerAdmin() {
|
||||
const {
|
||||
server_admin: { email, password }
|
||||
} = config.users;
|
||||
|
||||
const parsed = passwordSchema.safeParse(password);
|
||||
|
||||
if (!parsed.success) {
|
||||
throw Error(
|
||||
`Invalid server admin password: ${fromError(parsed.error).toString()}`
|
||||
);
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
try {
|
||||
const [existing] = await trx
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, email));
|
||||
|
||||
if (existing) {
|
||||
const passwordChanged = !(await verifyPassword(
|
||||
password,
|
||||
existing.passwordHash
|
||||
));
|
||||
|
||||
if (passwordChanged) {
|
||||
await trx
|
||||
.update(users)
|
||||
.set({ passwordHash })
|
||||
.where(eq(users.email, email));
|
||||
|
||||
// this isn't using the transaction, but it's probably fine
|
||||
await invalidateAllSessions(existing.userId);
|
||||
|
||||
logger.info(`Server admin (${email}) password updated`);
|
||||
}
|
||||
|
||||
if (existing.serverAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
await trx.update(users).set({ serverAdmin: false });
|
||||
|
||||
await trx
|
||||
.update(users)
|
||||
.set({
|
||||
serverAdmin: true
|
||||
})
|
||||
.where(eq(users.email, email));
|
||||
|
||||
logger.info(`Server admin (${email}) updated`);
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = generateId(15);
|
||||
|
||||
await db.insert(users).values({
|
||||
userId: userId,
|
||||
email: email,
|
||||
passwordHash,
|
||||
dateCreated: moment().toISOString(),
|
||||
serverAdmin: true,
|
||||
emailVerified: true
|
||||
});
|
||||
|
||||
logger.info(`Server admin (${email}) created`);
|
||||
} catch (e) {
|
||||
logger.error(e);
|
||||
trx.rollback();
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue