Compare commits
6 Commits
fix/card-e
...
feat/handl
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f975633baf | ||
|
|
8a02613d84 | ||
|
|
885f119404 | ||
|
|
b17a24455a | ||
|
|
0c9561467d | ||
|
|
47b6f06be4 |
@@ -15,4 +15,4 @@ pnpm-debug.log
|
||||
|
||||
README.md
|
||||
.next
|
||||
.git
|
||||
# .git
|
||||
40
.github/workflows/docker-publish.yml
vendored
40
.github/workflows/docker-publish.yml
vendored
@@ -34,6 +34,8 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# Install the cosign tool except on PR
|
||||
# https://github.com/sigstore/cosign-installer
|
||||
@@ -74,6 +76,42 @@ jobs:
|
||||
type=semver,pattern={{major}}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
# Extract version from git tag or ref
|
||||
# Uses git describe to get latest tag + commit hash in SemVer format: 1.2.3+abc1234
|
||||
- name: Extract version
|
||||
id: version
|
||||
run: |
|
||||
if [[ "${{ github.ref_type }}" == "tag" ]]; then
|
||||
VERSION="${{ github.ref_name }}"
|
||||
# Remove 'v' prefix if present
|
||||
VERSION="${VERSION#v}"
|
||||
else
|
||||
# Use git describe and simplify: v1.2.3-5-gabc1234 -> 1.2.3+abc1234
|
||||
GIT_DESCRIBE=$(git describe --tags --always --long 2>/dev/null || echo "")
|
||||
if [[ -n "$GIT_DESCRIBE" ]]; then
|
||||
# Match pattern: v1.2.3-5-gabc1234 (tag-commits-gcommit)
|
||||
if [[ "$GIT_DESCRIBE" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)-[0-9]+-g([a-f0-9]+)$ ]]; then
|
||||
# Format as tag+commit (SemVer build metadata)
|
||||
TAG_VERSION="${BASH_REMATCH[1]}"
|
||||
COMMIT_HASH="${BASH_REMATCH[2]}"
|
||||
VERSION="${TAG_VERSION}+${COMMIT_HASH:0:7}"
|
||||
elif [[ "$GIT_DESCRIBE" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
# Exactly on a tag
|
||||
VERSION="${BASH_REMATCH[1]}"
|
||||
else
|
||||
# Fallback: just commit hash
|
||||
COMMIT_SHA="${{ github.sha }}"
|
||||
VERSION="${COMMIT_SHA:0:7}"
|
||||
fi
|
||||
else
|
||||
# No tags exist, use commit hash
|
||||
COMMIT_SHA="${{ github.sha }}"
|
||||
VERSION="${COMMIT_SHA:0:7}"
|
||||
fi
|
||||
fi
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Version: $VERSION"
|
||||
|
||||
# Build and push Docker image with Buildx (don't push on PR)
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
@@ -86,6 +124,8 @@ jobs:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
APP_VERSION=${{ steps.version.outputs.version }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
|
||||
@@ -19,43 +19,45 @@ RUN pnpm config set store-dir ~/.pnpm-store
|
||||
|
||||
# 2. Prune projects
|
||||
FROM base AS pruner
|
||||
# https://stackoverflow.com/questions/49681984/how-to-get-version-value-of-package-json-inside-of-dockerfile
|
||||
# RUN export VERSION=$(npm run version)
|
||||
|
||||
ARG PROJECT
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache git
|
||||
|
||||
# It might be the path to <ROOT> turborepo
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
# Generate a partial monorepo with a pruned lockfile for a target workspace.
|
||||
# Assuming "@acme/nextjs" is the name entered in the project's package.json: { name: "@acme/nextjs" }
|
||||
|
||||
# Generate version from git (fallback if APP_VERSION not provided)
|
||||
RUN git fetch --tags --unshallow 2>/dev/null || git fetch --tags 2>/dev/null || true && \
|
||||
AUTO_VERSION=$(git describe --tags --always --long 2>/dev/null | \
|
||||
sed -E 's/^v?([0-9]+\.[0-9]+\.[0-9]+)-[0-9]+-g([a-f0-9]{7}).*/\1+\2/' | \
|
||||
sed 's/^v//' || \
|
||||
git rev-parse --short HEAD 2>/dev/null | head -c 7 || \
|
||||
echo "unknown") && \
|
||||
echo "$AUTO_VERSION" > /app/AUTO_VERSION
|
||||
|
||||
RUN turbo prune --scope=${PROJECT} --scope=@kan/db --docker
|
||||
|
||||
# 3. Build the project
|
||||
FROM base AS builder
|
||||
ARG PROJECT
|
||||
|
||||
# Environment to skip .env validation on build
|
||||
ENV CI=true
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy lockfile and package.json's of isolated subworkspace
|
||||
COPY --from=pruner /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
|
||||
COPY --from=pruner /app/out/pnpm-workspace.yaml ./pnpm-workspace.yaml
|
||||
COPY --from=pruner /app/out/json/ .
|
||||
COPY --from=pruner /app/AUTO_VERSION /tmp/AUTO_VERSION
|
||||
|
||||
ENV CI=true
|
||||
|
||||
# First install the dependencies (as they change less often)
|
||||
RUN --mount=type=cache,id=pnpm,target=~/.pnpm-store pnpm install --frozen-lockfile
|
||||
|
||||
# Copy source code of isolated subworkspace
|
||||
COPY --from=pruner /app/out/full/ .
|
||||
|
||||
|
||||
RUN pnpm build --filter=${PROJECT}
|
||||
# Use provided APP_VERSION or auto-generated from pruner stage
|
||||
RUN VERSION="${APP_VERSION:-$(cat /tmp/AUTO_VERSION 2>/dev/null | tr -d '\n\r' || echo 'unknown')}" && \
|
||||
NEXT_PUBLIC_APP_VERSION="$VERSION" pnpm build --filter=${PROJECT}
|
||||
|
||||
# # Copy static files to standalone directory
|
||||
# RUN mkdir -p apps/web/.next/standalone/.next && \
|
||||
|
||||
@@ -9,6 +9,7 @@ import { twMerge } from "tailwind-merge";
|
||||
|
||||
import { authClient } from "@kan/auth/client";
|
||||
|
||||
import { env } from "~/env";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { useKeyboardShortcuts } from "~/providers/keyboard-shortcuts";
|
||||
import { useModal } from "~/providers/modal";
|
||||
@@ -225,6 +226,25 @@ export default function UserMenu({
|
||||
</button>
|
||||
</Menu.Item>
|
||||
</div>
|
||||
{env.NEXT_PUBLIC_APP_VERSION && (
|
||||
<div className="light-border-600 border-t-[1px] p-1 dark:border-dark-600">
|
||||
<Menu.Item>
|
||||
<Link
|
||||
href={
|
||||
env.NEXT_PUBLIC_APP_VERSION.includes("+")
|
||||
? `https://github.com/kanbn/kan/commit/${env.NEXT_PUBLIC_APP_VERSION.split("+")[1]}`
|
||||
: `https://github.com/kanbn/kan/releases/tag/v${env.NEXT_PUBLIC_APP_VERSION}`
|
||||
}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={handleLinkClick}
|
||||
className="flex w-full items-center justify-center rounded-[5px] px-3 py-2 text-center text-xs text-light-900 hover:bg-light-200 dark:text-dark-900 dark:hover:bg-dark-400"
|
||||
>
|
||||
Version: {env.NEXT_PUBLIC_APP_VERSION}
|
||||
</Link>
|
||||
</Menu.Item>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
|
||||
@@ -95,6 +95,7 @@ export const env = createEnv({
|
||||
NEXT_PUBLIC_AVATAR_BUCKET_NAME: z.string().optional(),
|
||||
NEXT_PUBLIC_ATTACHMENTS_BUCKET_NAME: z.string().optional(),
|
||||
NEXT_PUBLIC_STORAGE_DOMAIN: z.string().optional(),
|
||||
NEXT_PUBLIC_APP_VERSION: z.string().optional(),
|
||||
NEXT_PUBLIC_ALLOW_CREDENTIALS: z
|
||||
.string()
|
||||
.transform((s) => (s === "" ? undefined : s))
|
||||
@@ -132,6 +133,7 @@ export const env = createEnv({
|
||||
NEXT_PUBLIC_ATTACHMENTS_BUCKET_NAME:
|
||||
process.env.NEXT_PUBLIC_ATTACHMENTS_BUCKET_NAME,
|
||||
NEXT_PUBLIC_STORAGE_DOMAIN: process.env.NEXT_PUBLIC_STORAGE_DOMAIN,
|
||||
NEXT_PUBLIC_APP_VERSION: process.env.NEXT_PUBLIC_APP_VERSION,
|
||||
NEXT_PUBLIC_ALLOW_CREDENTIALS: process.env.NEXT_PUBLIC_ALLOW_CREDENTIALS,
|
||||
NEXT_PUBLIC_DISABLE_SIGN_UP: process.env.NEXT_PUBLIC_DISABLE_SIGN_UP,
|
||||
NEXT_PUBLIC_USE_STANDALONE_OUTPUT:
|
||||
|
||||
@@ -327,7 +327,7 @@ export function NewCardForm({
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<div className="block max-h-48 w-full overflow-y-auto rounded-md border-0 bg-dark-300 bg-white/5 px-3 py-2 text-sm shadow-sm ring-1 ring-inset ring-light-600 focus-within:ring-2 focus-within:ring-inset focus-within:ring-light-700 dark:ring-dark-700 dark:focus-within:ring-dark-700 sm:leading-6">
|
||||
<div className="block max-h-48 min-h-24 w-full overflow-y-auto rounded-md border-0 bg-dark-300 bg-white/5 px-3 py-2 text-sm shadow-sm ring-1 ring-inset ring-light-600 focus-within:ring-2 focus-within:ring-inset focus-within:ring-light-700 dark:ring-dark-700 dark:focus-within:ring-dark-700 sm:leading-6">
|
||||
<Editor
|
||||
content={description}
|
||||
onChange={(value) => {
|
||||
|
||||
@@ -9,6 +9,8 @@ services:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: apps/web/Dockerfile
|
||||
args:
|
||||
APP_VERSION: ${APP_VERSION:-}
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,147 +1,23 @@
|
||||
import type { Subscription } from "@better-auth/stripe";
|
||||
import type Stripe from "stripe";
|
||||
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { stripe } from "@better-auth/stripe";
|
||||
import { ChatOrPushProviderEnum } from "@novu/api/models/components";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { createAuthEndpoint, createAuthMiddleware } from "better-auth/api";
|
||||
import { apiKey, genericOAuth } from "better-auth/plugins";
|
||||
import { magicLink } from "better-auth/plugins/magic-link";
|
||||
import { socialProviderList } from "better-auth/social-providers";
|
||||
import { env } from "next-runtime-env";
|
||||
|
||||
import type { dbClient } from "@kan/db/client";
|
||||
import * as memberRepo from "@kan/db/repository/member.repo";
|
||||
import * as subscriptionRepo from "@kan/db/repository/subscription.repo";
|
||||
import * as userRepo from "@kan/db/repository/user.repo";
|
||||
import * as workspaceRepo from "@kan/db/repository/workspace.repo";
|
||||
import * as schema from "@kan/db/schema";
|
||||
import { notificationClient, sendEmail } from "@kan/email";
|
||||
import { createEmailUnsubscribeLink } from "@kan/shared";
|
||||
import { createStripeClient } from "@kan/stripe";
|
||||
import { sendEmail } from "@kan/email";
|
||||
|
||||
export const configuredProviders = socialProviderList.reduce<
|
||||
Record<
|
||||
string,
|
||||
{
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
appBundleIdentifier?: string;
|
||||
tenantId?: string;
|
||||
requireSelectAccount?: boolean;
|
||||
clientKey?: string;
|
||||
issuer?: string;
|
||||
// Google-specific optional hints
|
||||
hostedDomain?: string;
|
||||
hd?: string;
|
||||
}
|
||||
>
|
||||
>((acc, provider) => {
|
||||
const id = process.env[`${provider.toUpperCase()}_CLIENT_ID`];
|
||||
const secret = process.env[`${provider.toUpperCase()}_CLIENT_SECRET`];
|
||||
if (id && id.length > 0 && secret && secret.length > 0) {
|
||||
acc[provider] = { clientId: id, clientSecret: secret };
|
||||
}
|
||||
if (
|
||||
provider === "apple" &&
|
||||
Object.keys(acc).includes("apple") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const bundleId =
|
||||
process.env[`${provider.toUpperCase()}_APP_BUNDLE_IDENTIFIER`];
|
||||
if (bundleId && bundleId.length > 0) {
|
||||
acc[provider].appBundleIdentifier = bundleId;
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "gitlab" &&
|
||||
Object.keys(acc).includes("gitlab") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const issuer = process.env[`${provider.toUpperCase()}_ISSUER`];
|
||||
if (issuer && issuer.length > 0) {
|
||||
acc[provider].issuer = issuer;
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "microsoft" &&
|
||||
Object.keys(acc).includes("microsoft") &&
|
||||
acc[provider]
|
||||
) {
|
||||
acc[provider].tenantId = "common";
|
||||
acc[provider].requireSelectAccount = true;
|
||||
}
|
||||
// Add Google domain hint if allowed domains is configured
|
||||
if (
|
||||
provider === "google" &&
|
||||
Object.keys(acc).includes("google") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const allowed = process.env.BETTER_AUTH_ALLOWED_DOMAINS?.split(",")
|
||||
.map((d) => d.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
if (allowed && allowed.length > 0) {
|
||||
// Use the first domain as an authorization hint
|
||||
acc[provider].hostedDomain = allowed[0];
|
||||
acc[provider].hd = allowed[0];
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "tiktok" &&
|
||||
Object.keys(acc).includes("tiktok") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const key = process.env[`${provider.toUpperCase()}_CLIENT_KEY`];
|
||||
if (key && key.length > 0) {
|
||||
acc[provider].clientKey = key;
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
export const socialProvidersPlugin = () => ({
|
||||
id: "social-providers-plugin",
|
||||
endpoints: {
|
||||
getSocialProviders: createAuthEndpoint(
|
||||
"/social-providers",
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
async (ctx) => {
|
||||
const providers = ctx.context.socialProviders.map((p) =>
|
||||
p.id.toLowerCase(),
|
||||
);
|
||||
// Add OIDC provider if configured
|
||||
if (
|
||||
process.env.OIDC_CLIENT_ID &&
|
||||
process.env.OIDC_CLIENT_SECRET &&
|
||||
process.env.OIDC_DISCOVERY_URL
|
||||
) {
|
||||
providers.push("oidc");
|
||||
}
|
||||
return ctx.json(providers);
|
||||
},
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
async function downloadImage(url: string): Promise<Buffer> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download image: ${response.statusText}`);
|
||||
}
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
import { createDatabaseHooks, createMiddlewareHooks } from "./hooks";
|
||||
import { createPlugins } from "./plugins";
|
||||
import { configuredProviders } from "./providers";
|
||||
|
||||
export const initAuth = (db: dbClient) => {
|
||||
return betterAuth({
|
||||
secret: process.env.BETTER_AUTH_SECRET!,
|
||||
secret: env("BETTER_AUTH_SECRET"),
|
||||
baseURL: env("NEXT_PUBLIC_BASE_URL"),
|
||||
trustedOrigins: process.env.BETTER_AUTH_TRUSTED_ORIGINS
|
||||
trustedOrigins: env("BETTER_AUTH_TRUSTED_ORIGINS")
|
||||
? [
|
||||
env("NEXT_PUBLIC_BASE_URL") ?? "",
|
||||
...process.env.BETTER_AUTH_TRUSTED_ORIGINS.split(","),
|
||||
...(env("BETTER_AUTH_TRUSTED_ORIGINS")?.split(",") ?? []),
|
||||
]
|
||||
: [env("NEXT_PUBLIC_BASE_URL") ?? ""],
|
||||
database: drizzleAdapter(db, {
|
||||
@@ -181,360 +57,9 @@ export const initAuth = (db: dbClient) => {
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
socialProvidersPlugin(),
|
||||
...(process.env.NEXT_PUBLIC_KAN_ENV === "cloud"
|
||||
? [
|
||||
stripe({
|
||||
stripeClient: createStripeClient(),
|
||||
stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
|
||||
createCustomerOnSignUp: true,
|
||||
subscription: {
|
||||
enabled: true,
|
||||
plans: [
|
||||
{
|
||||
name: "team",
|
||||
priceId: process.env.STRIPE_TEAM_PLAN_MONTHLY_PRICE_ID!,
|
||||
annualDiscountPriceId:
|
||||
process.env.STRIPE_TEAM_PLAN_YEARLY_PRICE_ID!,
|
||||
freeTrial: {
|
||||
days: 14,
|
||||
onTrialStart: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-start", subscription);
|
||||
},
|
||||
onTrialEnd: async ({ subscription }) => {
|
||||
await triggerWorkflow(db, "trial-end", subscription);
|
||||
},
|
||||
onTrialExpired: async (subscription) => {
|
||||
await triggerWorkflow(
|
||||
db,
|
||||
"trial-expired",
|
||||
subscription,
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pro",
|
||||
priceId: process.env.STRIPE_PRO_PLAN_MONTHLY_PRICE_ID!,
|
||||
annualDiscountPriceId:
|
||||
process.env.STRIPE_PRO_PLAN_YEARLY_PRICE_ID!,
|
||||
freeTrial: {
|
||||
days: 14,
|
||||
onTrialStart: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-start", subscription);
|
||||
},
|
||||
onTrialEnd: async ({ subscription }) => {
|
||||
await triggerWorkflow(db, "trial-end", subscription);
|
||||
},
|
||||
onTrialExpired: async (subscription) => {
|
||||
await triggerWorkflow(
|
||||
db,
|
||||
"trial-expired",
|
||||
subscription,
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
authorizeReference: async (data) => {
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
db,
|
||||
data.referenceId,
|
||||
);
|
||||
|
||||
if (!workspace) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const isUserInWorkspace =
|
||||
await workspaceRepo.isUserInWorkspace(
|
||||
db,
|
||||
data.user.id,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
return isUserInWorkspace;
|
||||
},
|
||||
getCheckoutSessionParams: () => {
|
||||
return {
|
||||
params: {
|
||||
allow_promotion_codes: true,
|
||||
},
|
||||
};
|
||||
},
|
||||
onSubscriptionComplete: async ({
|
||||
subscription,
|
||||
stripeSubscription,
|
||||
}) => {
|
||||
// Set unlimited seats to true for pro plans
|
||||
if (subscription.plan === "pro") {
|
||||
await subscriptionRepo.updateByStripeSubscriptionId(
|
||||
db,
|
||||
stripeSubscription.id,
|
||||
{
|
||||
unlimitedSeats: true,
|
||||
},
|
||||
);
|
||||
console.log(
|
||||
`Pro subscription ${stripeSubscription.id} activated with unlimited seats`,
|
||||
);
|
||||
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
db,
|
||||
subscription.referenceId,
|
||||
);
|
||||
|
||||
if (workspace?.id) {
|
||||
await memberRepo.unpauseAllMembers(db, workspace.id);
|
||||
|
||||
console.log(
|
||||
`Unpausing all members for workspace ${workspace.id}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
apiKey({
|
||||
enableSessionForAPIKeys: true,
|
||||
rateLimit: {
|
||||
enabled: true,
|
||||
timeWindow: 1000 * 60, // 1 minute
|
||||
maxRequests: 100, // 100 requests per minute
|
||||
},
|
||||
}),
|
||||
magicLink({
|
||||
expiresIn: 60 * 60 * 24 * 7, // 7 days
|
||||
sendMagicLink: async ({ email, url }) => {
|
||||
if (url.includes("type=invite")) {
|
||||
await sendEmail(
|
||||
email,
|
||||
"Invitation to join workspace",
|
||||
"JOIN_WORKSPACE",
|
||||
{
|
||||
magicLoginUrl: url,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await sendEmail(email, "Sign in to kan.bn", "MAGIC_LINK", {
|
||||
magicLoginUrl: url,
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
// Generic OIDC provider
|
||||
...(process.env.OIDC_CLIENT_ID &&
|
||||
process.env.OIDC_CLIENT_SECRET &&
|
||||
process.env.OIDC_DISCOVERY_URL
|
||||
? [
|
||||
genericOAuth({
|
||||
config: [
|
||||
{
|
||||
providerId: "oidc",
|
||||
clientId: process.env.OIDC_CLIENT_ID,
|
||||
clientSecret: process.env.OIDC_CLIENT_SECRET,
|
||||
discoveryUrl: process.env.OIDC_DISCOVERY_URL,
|
||||
scopes: ["openid", "email", "profile"],
|
||||
pkce: true,
|
||||
mapProfileToUser: (profile: {
|
||||
name?: string;
|
||||
display_name?: string;
|
||||
preferred_username?: string;
|
||||
given_name?: string;
|
||||
family_name?: string;
|
||||
email?: string;
|
||||
email_verified?: boolean;
|
||||
sub?: string;
|
||||
picture?: string;
|
||||
avatar?: string;
|
||||
}) => {
|
||||
console.log("OIDC profile:", profile);
|
||||
|
||||
const name =
|
||||
profile.name ??
|
||||
profile.display_name ??
|
||||
profile.preferred_username ??
|
||||
(profile.given_name && profile.family_name
|
||||
? `${profile.given_name} ${profile.family_name}`.trim()
|
||||
: (profile.given_name ?? profile.family_name)) ??
|
||||
profile.sub ??
|
||||
"";
|
||||
|
||||
return {
|
||||
email: profile.email,
|
||||
name: name,
|
||||
emailVerified: profile.email_verified ?? false,
|
||||
image: profile.picture ?? profile.avatar ?? null,
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
async before(user) {
|
||||
if (env("NEXT_PUBLIC_DISABLE_SIGN_UP")?.toLowerCase() === "true") {
|
||||
const pendingInvitation = await memberRepo.getByEmailAndStatus(
|
||||
db,
|
||||
user.email,
|
||||
"invited",
|
||||
);
|
||||
|
||||
if (!pendingInvitation) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
// Fall through to any additional checks below
|
||||
}
|
||||
// Enforce allowed domains (OIDC/social) if configured
|
||||
const allowed = process.env.BETTER_AUTH_ALLOWED_DOMAINS?.split(",")
|
||||
.map((d) => d.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
if (allowed && allowed.length > 0) {
|
||||
const domain = user.email.split("@")[1]?.toLowerCase();
|
||||
if (!domain || !allowed.includes(domain)) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(true);
|
||||
},
|
||||
async after(user) {
|
||||
let avatarKey = user.image;
|
||||
if (
|
||||
user.image &&
|
||||
!user.image.includes(process.env.NEXT_PUBLIC_STORAGE_DOMAIN!)
|
||||
) {
|
||||
try {
|
||||
const credentials =
|
||||
env("S3_ACCESS_KEY_ID") && env("S3_SECRET_ACCESS_KEY")
|
||||
? {
|
||||
accessKeyId: env("S3_ACCESS_KEY_ID")!,
|
||||
secretAccessKey: env("S3_SECRET_ACCESS_KEY")!,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const client = new S3Client({
|
||||
region: env("S3_REGION") ?? "",
|
||||
endpoint: env("S3_ENDPOINT") ?? "",
|
||||
forcePathStyle: env("S3_FORCE_PATH_STYLE") === "true",
|
||||
credentials,
|
||||
});
|
||||
|
||||
const allowedFileExtensions = ["jpg", "jpeg", "png", "webp"];
|
||||
|
||||
const fileExtension =
|
||||
user.image.split(".").pop()?.split("?")[0] || "jpg";
|
||||
const key = `${user.id}/avatar.${!allowedFileExtensions.includes(fileExtension) ? "jpg" : fileExtension}`;
|
||||
|
||||
const imageBuffer = await downloadImage(user.image);
|
||||
|
||||
await client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: env("NEXT_PUBLIC_AVATAR_BUCKET_NAME") ?? "",
|
||||
Key: key,
|
||||
Body: imageBuffer,
|
||||
ContentType: `image/${!allowedFileExtensions.includes(fileExtension) ? "jpeg" : fileExtension}`,
|
||||
ACL: "public-read",
|
||||
}),
|
||||
);
|
||||
|
||||
avatarKey = key;
|
||||
|
||||
await userRepo.update(db, user.id, {
|
||||
image: key,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (notificationClient) {
|
||||
try {
|
||||
const [firstName, ...rest] = user.name
|
||||
.split(" ")
|
||||
.filter(Boolean);
|
||||
const lastName = rest.length ? rest.join(" ") : undefined;
|
||||
const avatarUrl = avatarKey
|
||||
? `${env("NEXT_PUBLIC_STORAGE_URL")}/${env("NEXT_PUBLIC_AVATAR_BUCKET_NAME")}/${avatarKey}`
|
||||
: undefined;
|
||||
|
||||
const unsubscribeUrl = await createEmailUnsubscribeLink(
|
||||
user.id,
|
||||
);
|
||||
|
||||
await notificationClient.trigger({
|
||||
to: {
|
||||
subscriberId: user.id,
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
email: user.email,
|
||||
avatar: avatarUrl,
|
||||
data: {
|
||||
emailVerified: user.emailVerified,
|
||||
stripeCustomerId: user.stripeCustomerId,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
},
|
||||
},
|
||||
payload: {
|
||||
emailUnsubscribeUrl: unsubscribeUrl,
|
||||
},
|
||||
workflowId: "user-signup",
|
||||
});
|
||||
|
||||
await notificationClient.subscribers.credentials.update(
|
||||
{
|
||||
providerId: ChatOrPushProviderEnum.Discord,
|
||||
credentials: {
|
||||
webhookUrl: process.env.DISCORD_WEBHOOK_URL!,
|
||||
},
|
||||
integrationIdentifier: "discord",
|
||||
},
|
||||
user.id,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error adding user to notification client",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
hooks: {
|
||||
after: createAuthMiddleware(async (ctx) => {
|
||||
if (
|
||||
ctx.path === "/magic-link/verify" &&
|
||||
(ctx.query?.callbackURL as string | undefined)?.includes(
|
||||
"type=invite",
|
||||
)
|
||||
) {
|
||||
const userId = ctx.context.newSession?.session.userId;
|
||||
const callbackURL = ctx.query?.callbackURL as string | undefined;
|
||||
const memberPublicId = callbackURL?.split("memberPublicId=")[1];
|
||||
|
||||
if (userId && memberPublicId) {
|
||||
const member = await memberRepo.getByPublicId(db, memberPublicId);
|
||||
|
||||
if (member?.id) {
|
||||
await memberRepo.acceptInvite(db, {
|
||||
memberId: member.id,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
},
|
||||
plugins: createPlugins(db),
|
||||
databaseHooks: createDatabaseHooks(db),
|
||||
hooks: createMiddlewareHooks(db),
|
||||
advanced: {
|
||||
cookiePrefix: "kan",
|
||||
database: {
|
||||
@@ -543,37 +68,3 @@ export const initAuth = (db: dbClient) => {
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
async function triggerWorkflow(
|
||||
db: dbClient,
|
||||
workflowId: string,
|
||||
subscription: Subscription,
|
||||
cancellationDetails?: Stripe.Subscription.CancellationDetails | null,
|
||||
) {
|
||||
try {
|
||||
if (!subscription.stripeCustomerId || !notificationClient) return;
|
||||
|
||||
const user = await userRepo.getByStripeCustomerId(
|
||||
db,
|
||||
subscription.stripeCustomerId,
|
||||
);
|
||||
|
||||
if (!user || !notificationClient) return;
|
||||
|
||||
const unsubscribeUrl = await createEmailUnsubscribeLink(user.id);
|
||||
|
||||
await notificationClient.trigger({
|
||||
to: {
|
||||
subscriberId: user.id,
|
||||
},
|
||||
payload: {
|
||||
...subscription,
|
||||
cancellationDetails,
|
||||
emailUnsubscribeUrl: unsubscribeUrl,
|
||||
},
|
||||
workflowId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error triggering workflow", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "better-auth/client/plugins";
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
|
||||
import type { socialProvidersPlugin } from "./auth";
|
||||
import type { socialProvidersPlugin } from "./providers";
|
||||
|
||||
const socialProvidersPluginClient = {
|
||||
id: "social-providers-plugin",
|
||||
|
||||
183
packages/auth/src/hooks.ts
Normal file
183
packages/auth/src/hooks.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { ChatOrPushProviderEnum } from "@novu/api/models/components";
|
||||
import { createAuthMiddleware } from "better-auth/api";
|
||||
import { env } from "next-runtime-env";
|
||||
|
||||
import type { dbClient } from "@kan/db/client";
|
||||
import * as memberRepo from "@kan/db/repository/member.repo";
|
||||
import * as userRepo from "@kan/db/repository/user.repo";
|
||||
import { notificationClient } from "@kan/email";
|
||||
import { createEmailUnsubscribeLink } from "@kan/shared";
|
||||
|
||||
import { downloadImage } from "./utils";
|
||||
|
||||
type BetterAuthUser = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
email: string;
|
||||
emailVerified: boolean;
|
||||
name: string;
|
||||
image?: string | null | undefined;
|
||||
stripeCustomerId?: string | null | undefined;
|
||||
} & Record<string, unknown>;
|
||||
|
||||
export function createDatabaseHooks(db: dbClient) {
|
||||
return {
|
||||
user: {
|
||||
create: {
|
||||
async before(user: BetterAuthUser, _context: unknown) {
|
||||
if (env("NEXT_PUBLIC_DISABLE_SIGN_UP")?.toLowerCase() === "true") {
|
||||
const pendingInvitation = await memberRepo.getByEmailAndStatus(
|
||||
db,
|
||||
user.email,
|
||||
"invited",
|
||||
);
|
||||
|
||||
if (!pendingInvitation) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
// Fall through to any additional checks below
|
||||
}
|
||||
// Enforce allowed domains (OIDC/social) if configured
|
||||
const allowed = process.env.BETTER_AUTH_ALLOWED_DOMAINS?.split(",")
|
||||
.map((d) => d.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
if (allowed && allowed.length > 0) {
|
||||
const domain = user.email.split("@")[1]?.toLowerCase();
|
||||
if (!domain || !allowed.includes(domain)) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
}
|
||||
return Promise.resolve(true);
|
||||
},
|
||||
async after(user: BetterAuthUser, _context: unknown) {
|
||||
let avatarKey = user.image;
|
||||
const storageDomain = process.env.NEXT_PUBLIC_STORAGE_DOMAIN;
|
||||
if (
|
||||
user.image &&
|
||||
storageDomain &&
|
||||
!user.image.includes(storageDomain)
|
||||
) {
|
||||
try {
|
||||
const credentials =
|
||||
env("S3_ACCESS_KEY_ID") && env("S3_SECRET_ACCESS_KEY")
|
||||
? {
|
||||
accessKeyId: env("S3_ACCESS_KEY_ID")!,
|
||||
secretAccessKey: env("S3_SECRET_ACCESS_KEY")!,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const client = new S3Client({
|
||||
region: env("S3_REGION") ?? "",
|
||||
endpoint: env("S3_ENDPOINT") ?? "",
|
||||
forcePathStyle: env("S3_FORCE_PATH_STYLE") === "true",
|
||||
credentials,
|
||||
});
|
||||
|
||||
const allowedFileExtensions = ["jpg", "jpeg", "png", "webp"];
|
||||
|
||||
const fileExtension =
|
||||
user.image.split(".").pop()?.split("?")[0] ?? "jpg";
|
||||
const key = `${user.id}/avatar.${!allowedFileExtensions.includes(fileExtension) ? "jpg" : fileExtension}`;
|
||||
|
||||
const imageBuffer = await downloadImage(user.image);
|
||||
|
||||
await client.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: env("NEXT_PUBLIC_AVATAR_BUCKET_NAME") ?? "",
|
||||
Key: key,
|
||||
Body: imageBuffer,
|
||||
ContentType: `image/${!allowedFileExtensions.includes(fileExtension) ? "jpeg" : fileExtension}`,
|
||||
ACL: "public-read",
|
||||
}),
|
||||
);
|
||||
|
||||
avatarKey = key;
|
||||
|
||||
await userRepo.update(db, user.id, {
|
||||
image: key,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
if (notificationClient) {
|
||||
try {
|
||||
const [firstName, ...rest] = (user.name || "")
|
||||
.split(" ")
|
||||
.filter(Boolean);
|
||||
const lastName = rest.length ? rest.join(" ") : undefined;
|
||||
const avatarUrl = avatarKey
|
||||
? `${env("NEXT_PUBLIC_STORAGE_URL")}/${env("NEXT_PUBLIC_AVATAR_BUCKET_NAME")}/${avatarKey}`
|
||||
: undefined;
|
||||
|
||||
const unsubscribeUrl = await createEmailUnsubscribeLink(user.id);
|
||||
|
||||
await notificationClient.trigger({
|
||||
to: {
|
||||
subscriberId: user.id,
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
email: user.email,
|
||||
avatar: avatarUrl,
|
||||
data: {
|
||||
emailVerified: user.emailVerified,
|
||||
stripeCustomerId: user.stripeCustomerId,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
},
|
||||
},
|
||||
payload: {
|
||||
emailUnsubscribeUrl: unsubscribeUrl,
|
||||
},
|
||||
workflowId: "user-signup",
|
||||
});
|
||||
|
||||
await notificationClient.subscribers.credentials.update(
|
||||
{
|
||||
providerId: ChatOrPushProviderEnum.Discord,
|
||||
credentials: {
|
||||
webhookUrl: env("DISCORD_WEBHOOK_URL"),
|
||||
},
|
||||
integrationIdentifier: "discord",
|
||||
},
|
||||
user.id,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error adding user to notification client", error);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createMiddlewareHooks(db: dbClient) {
|
||||
return {
|
||||
after: createAuthMiddleware(async (ctx) => {
|
||||
if (
|
||||
ctx.path === "/magic-link/verify" &&
|
||||
(ctx.query?.callbackURL as string | undefined)?.includes("type=invite")
|
||||
) {
|
||||
const userId = ctx.context.newSession?.session.userId;
|
||||
const callbackURL = ctx.query?.callbackURL as string | undefined;
|
||||
const memberPublicId = callbackURL?.split("memberPublicId=")[1];
|
||||
|
||||
if (userId && memberPublicId) {
|
||||
const member = await memberRepo.getByPublicId(db, memberPublicId);
|
||||
|
||||
if (member?.id) {
|
||||
await memberRepo.acceptInvite(db, {
|
||||
memberId: member.id,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
225
packages/auth/src/plugins.ts
Normal file
225
packages/auth/src/plugins.ts
Normal file
@@ -0,0 +1,225 @@
|
||||
import { stripe } from "@better-auth/stripe";
|
||||
import { apiKey, genericOAuth } from "better-auth/plugins";
|
||||
import { magicLink } from "better-auth/plugins/magic-link";
|
||||
|
||||
import type { dbClient } from "@kan/db/client";
|
||||
import * as memberRepo from "@kan/db/repository/member.repo";
|
||||
import * as subscriptionRepo from "@kan/db/repository/subscription.repo";
|
||||
import * as workspaceRepo from "@kan/db/repository/workspace.repo";
|
||||
import { sendEmail } from "@kan/email";
|
||||
import { createStripeClient } from "@kan/stripe";
|
||||
|
||||
import { socialProvidersPlugin } from "./providers";
|
||||
import { triggerWorkflow } from "./utils";
|
||||
|
||||
export function createPlugins(db: dbClient) {
|
||||
return [
|
||||
socialProvidersPlugin(),
|
||||
...(process.env.NEXT_PUBLIC_KAN_ENV === "cloud"
|
||||
? [
|
||||
stripe({
|
||||
stripeClient: createStripeClient(),
|
||||
stripeWebhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
|
||||
createCustomerOnSignUp: true,
|
||||
subscription: {
|
||||
enabled: true,
|
||||
plans: [
|
||||
{
|
||||
name: "team",
|
||||
priceId: process.env.STRIPE_TEAM_PLAN_MONTHLY_PRICE_ID!,
|
||||
annualDiscountPriceId:
|
||||
process.env.STRIPE_TEAM_PLAN_YEARLY_PRICE_ID!,
|
||||
freeTrial: {
|
||||
days: 14,
|
||||
onTrialStart: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-start", subscription);
|
||||
},
|
||||
onTrialEnd: async ({ subscription }) => {
|
||||
await triggerWorkflow(db, "trial-end", subscription);
|
||||
},
|
||||
onTrialExpired: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-expired", subscription);
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pro",
|
||||
priceId: process.env.STRIPE_PRO_PLAN_MONTHLY_PRICE_ID!,
|
||||
annualDiscountPriceId:
|
||||
process.env.STRIPE_PRO_PLAN_YEARLY_PRICE_ID!,
|
||||
freeTrial: {
|
||||
days: 14,
|
||||
onTrialStart: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-start", subscription);
|
||||
},
|
||||
onTrialEnd: async ({ subscription }) => {
|
||||
await triggerWorkflow(db, "trial-end", subscription);
|
||||
},
|
||||
onTrialExpired: async (subscription) => {
|
||||
await triggerWorkflow(db, "trial-expired", subscription);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
authorizeReference: async (data) => {
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
db,
|
||||
data.referenceId,
|
||||
);
|
||||
|
||||
if (!workspace) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const isUserInWorkspace = await workspaceRepo.isUserInWorkspace(
|
||||
db,
|
||||
data.user.id,
|
||||
workspace.id,
|
||||
);
|
||||
|
||||
return isUserInWorkspace;
|
||||
},
|
||||
getCheckoutSessionParams: () => {
|
||||
return {
|
||||
params: {
|
||||
allow_promotion_codes: true,
|
||||
},
|
||||
};
|
||||
},
|
||||
onSubscriptionComplete: async ({
|
||||
subscription,
|
||||
stripeSubscription,
|
||||
}) => {
|
||||
// Set unlimited seats to true for pro plans
|
||||
if (subscription.plan === "pro") {
|
||||
await subscriptionRepo.updateByStripeSubscriptionId(
|
||||
db,
|
||||
stripeSubscription.id,
|
||||
{
|
||||
unlimitedSeats: true,
|
||||
},
|
||||
);
|
||||
console.log(
|
||||
`Pro subscription ${stripeSubscription.id} activated with unlimited seats`,
|
||||
);
|
||||
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
db,
|
||||
subscription.referenceId,
|
||||
);
|
||||
|
||||
if (workspace?.id) {
|
||||
await memberRepo.unpauseAllMembers(db, workspace.id);
|
||||
}
|
||||
}
|
||||
},
|
||||
onSubscriptionCancel: async ({
|
||||
subscription,
|
||||
cancellationDetails,
|
||||
}) => {
|
||||
await triggerWorkflow(
|
||||
db,
|
||||
"subscription-canceled",
|
||||
subscription,
|
||||
cancellationDetails,
|
||||
);
|
||||
|
||||
// for cancelled subscriptions, we need to pause all members and set their workspace plan to free
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
db,
|
||||
subscription.referenceId,
|
||||
);
|
||||
|
||||
if (workspace?.id) {
|
||||
await memberRepo.pauseAllMembers(db, workspace.id);
|
||||
await workspaceRepo.update(db, subscription.referenceId, {
|
||||
plan: "free",
|
||||
});
|
||||
}
|
||||
},
|
||||
onSubscriptionUpdate: async ({ subscription }) => {
|
||||
await triggerWorkflow(db, "subscription-updated", subscription);
|
||||
},
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
apiKey({
|
||||
enableSessionForAPIKeys: true,
|
||||
rateLimit: {
|
||||
enabled: true,
|
||||
timeWindow: 1000 * 60, // 1 minute
|
||||
maxRequests: 100, // 100 requests per minute
|
||||
},
|
||||
}),
|
||||
magicLink({
|
||||
expiresIn: 60 * 60 * 24 * 7, // 7 days
|
||||
sendMagicLink: async ({ email, url }) => {
|
||||
if (url.includes("type=invite")) {
|
||||
await sendEmail(
|
||||
email,
|
||||
"Invitation to join workspace",
|
||||
"JOIN_WORKSPACE",
|
||||
{
|
||||
magicLoginUrl: url,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await sendEmail(email, "Sign in to kan.bn", "MAGIC_LINK", {
|
||||
magicLoginUrl: url,
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
// Generic OIDC provider
|
||||
...(process.env.OIDC_CLIENT_ID &&
|
||||
process.env.OIDC_CLIENT_SECRET &&
|
||||
process.env.OIDC_DISCOVERY_URL
|
||||
? [
|
||||
genericOAuth({
|
||||
config: [
|
||||
{
|
||||
providerId: "oidc",
|
||||
clientId: process.env.OIDC_CLIENT_ID,
|
||||
clientSecret: process.env.OIDC_CLIENT_SECRET,
|
||||
discoveryUrl: process.env.OIDC_DISCOVERY_URL,
|
||||
scopes: ["openid", "email", "profile"],
|
||||
pkce: true,
|
||||
mapProfileToUser: (profile: {
|
||||
name?: string;
|
||||
display_name?: string;
|
||||
preferred_username?: string;
|
||||
given_name?: string;
|
||||
family_name?: string;
|
||||
email?: string;
|
||||
email_verified?: boolean;
|
||||
sub?: string;
|
||||
picture?: string;
|
||||
avatar?: string;
|
||||
}) => {
|
||||
console.log("OIDC profile:", profile);
|
||||
|
||||
const name =
|
||||
profile.name ??
|
||||
profile.display_name ??
|
||||
profile.preferred_username ??
|
||||
(profile.given_name && profile.family_name
|
||||
? `${profile.given_name} ${profile.family_name}`.trim()
|
||||
: (profile.given_name ?? profile.family_name)) ??
|
||||
profile.sub ??
|
||||
"";
|
||||
|
||||
return {
|
||||
email: profile.email,
|
||||
name: name,
|
||||
emailVerified: profile.email_verified ?? false,
|
||||
image: profile.picture ?? profile.avatar ?? null,
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
];
|
||||
}
|
||||
107
packages/auth/src/providers.ts
Normal file
107
packages/auth/src/providers.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { createAuthEndpoint } from "better-auth/api";
|
||||
import { socialProviderList } from "better-auth/social-providers";
|
||||
|
||||
export const configuredProviders = socialProviderList.reduce<
|
||||
Record<
|
||||
string,
|
||||
{
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
appBundleIdentifier?: string;
|
||||
tenantId?: string;
|
||||
requireSelectAccount?: boolean;
|
||||
clientKey?: string;
|
||||
issuer?: string;
|
||||
// Google-specific optional hints
|
||||
hostedDomain?: string;
|
||||
hd?: string;
|
||||
}
|
||||
>
|
||||
>((acc, provider) => {
|
||||
const id = process.env[`${provider.toUpperCase()}_CLIENT_ID`];
|
||||
const secret = process.env[`${provider.toUpperCase()}_CLIENT_SECRET`];
|
||||
if (id && id.length > 0 && secret && secret.length > 0) {
|
||||
acc[provider] = { clientId: id, clientSecret: secret };
|
||||
}
|
||||
if (
|
||||
provider === "apple" &&
|
||||
Object.keys(acc).includes("apple") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const bundleId =
|
||||
process.env[`${provider.toUpperCase()}_APP_BUNDLE_IDENTIFIER`];
|
||||
if (bundleId && bundleId.length > 0) {
|
||||
acc[provider].appBundleIdentifier = bundleId;
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "gitlab" &&
|
||||
Object.keys(acc).includes("gitlab") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const issuer = process.env[`${provider.toUpperCase()}_ISSUER`];
|
||||
if (issuer && issuer.length > 0) {
|
||||
acc[provider].issuer = issuer;
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "microsoft" &&
|
||||
Object.keys(acc).includes("microsoft") &&
|
||||
acc[provider]
|
||||
) {
|
||||
acc[provider].tenantId = "common";
|
||||
acc[provider].requireSelectAccount = true;
|
||||
}
|
||||
// Add Google domain hint if allowed domains is configured
|
||||
if (
|
||||
provider === "google" &&
|
||||
Object.keys(acc).includes("google") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const allowed = process.env.BETTER_AUTH_ALLOWED_DOMAINS?.split(",")
|
||||
.map((d) => d.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
if (allowed && allowed.length > 0) {
|
||||
// Use the first domain as an authorization hint
|
||||
acc[provider].hostedDomain = allowed[0];
|
||||
acc[provider].hd = allowed[0];
|
||||
}
|
||||
}
|
||||
if (
|
||||
provider === "tiktok" &&
|
||||
Object.keys(acc).includes("tiktok") &&
|
||||
acc[provider]
|
||||
) {
|
||||
const key = process.env[`${provider.toUpperCase()}_CLIENT_KEY`];
|
||||
if (key && key.length > 0) {
|
||||
acc[provider].clientKey = key;
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
export const socialProvidersPlugin = () => ({
|
||||
id: "social-providers-plugin",
|
||||
endpoints: {
|
||||
getSocialProviders: createAuthEndpoint(
|
||||
"/social-providers",
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
async (ctx) => {
|
||||
const providers = ctx.context.socialProviders.map((p) =>
|
||||
p.id.toLowerCase(),
|
||||
);
|
||||
// Add OIDC provider if configured
|
||||
if (
|
||||
process.env.OIDC_CLIENT_ID &&
|
||||
process.env.OIDC_CLIENT_SECRET &&
|
||||
process.env.OIDC_DISCOVERY_URL
|
||||
) {
|
||||
providers.push("oidc");
|
||||
}
|
||||
return ctx.json(providers);
|
||||
},
|
||||
),
|
||||
},
|
||||
});
|
||||
49
packages/auth/src/utils.ts
Normal file
49
packages/auth/src/utils.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import type { Subscription } from "@better-auth/stripe";
|
||||
import type Stripe from "stripe";
|
||||
|
||||
import type { dbClient } from "@kan/db/client";
|
||||
import * as userRepo from "@kan/db/repository/user.repo";
|
||||
import { notificationClient } from "@kan/email";
|
||||
import { createEmailUnsubscribeLink } from "@kan/shared";
|
||||
|
||||
export async function downloadImage(url: string): Promise<Buffer> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download image: ${response.statusText}`);
|
||||
}
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
export async function triggerWorkflow(
|
||||
db: dbClient,
|
||||
workflowId: string,
|
||||
subscription: Subscription,
|
||||
cancellationDetails?: Stripe.Subscription.CancellationDetails | null,
|
||||
) {
|
||||
try {
|
||||
if (!subscription.stripeCustomerId || !notificationClient) return;
|
||||
|
||||
const user = await userRepo.getByStripeCustomerId(
|
||||
db,
|
||||
subscription.stripeCustomerId,
|
||||
);
|
||||
|
||||
if (!user || !notificationClient) return;
|
||||
|
||||
const unsubscribeUrl = await createEmailUnsubscribeLink(user.id);
|
||||
|
||||
await notificationClient.trigger({
|
||||
to: {
|
||||
subscriberId: user.id,
|
||||
},
|
||||
payload: {
|
||||
...subscription,
|
||||
cancellationDetails,
|
||||
emailUnsubscribeUrl: unsubscribeUrl,
|
||||
},
|
||||
workflowId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error triggering workflow", error);
|
||||
}
|
||||
}
|
||||
@@ -121,3 +121,15 @@ export const unpauseAllMembers = async (db: dbClient, workspaceId: number) => {
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const pauseAllMembers = async (db: dbClient, workspaceId: number) => {
|
||||
await db
|
||||
.update(workspaceMembers)
|
||||
.set({ status: "paused" })
|
||||
.where(
|
||||
and(
|
||||
eq(workspaceMembers.workspaceId, workspaceId),
|
||||
eq(workspaceMembers.status, "active"),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user