Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"cmdk": "^1.1.1",
"cookies-next": "^6.0.0",
"date-fns": "^4.1.0",
"etsy-ts": "^4.2.0",
"discord-api-types": "^0.38.17",
"exa-js": "^1.8.8",
"fast-deep-equal": "^3.1.3",
Expand Down
24 changes: 24 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/app/_components/navbar/account-button/provider-icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
SiX,
SiSpotify,
SiStrava,
SiEtsy,
} from "@icons-pack/react-simple-icons";

interface Props {
Expand Down Expand Up @@ -40,6 +41,7 @@ export const AuthProviderIcon: React.FC<Props> = ({ provider, className }) => {
Notion: SiNotion,
Spotify: SiSpotify,
Strava: SiStrava,
Etsy: SiEtsy,
}[provider] ?? null;

return Icon ? <Icon className={cn("size-4", className)} /> : null;
Expand Down
4 changes: 4 additions & 0 deletions src/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ const createAuthSchema = () => {
authSchema.AUTH_SPOTIFY_SECRET = z.string();
}

if (process.env.AUTH_ETSY_ID) {
authSchema.AUTH_ETSY_ID = z.string();
}

return authSchema;
};

Expand Down
26 changes: 26 additions & 0 deletions src/server/api/routers/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,30 @@ export const accountsRouter = createTRPCRouter({
},
});
}),

updateAccount: protectedProcedure
.input(
z.object({
provider: z.string(),
providerAccountId: z.string(),
data: z.object({
access_token: z.string(),
refresh_token: z.string(),
expires_at: z.number(),
token_type: z.string(),
scope: z.string(),
}),
}),
)
.mutation(async ({ ctx, input: { provider, providerAccountId, data } }) => {
return ctx.db.account.update({
where: {
provider_providerAccountId: {
provider,
providerAccountId,
},
},
data,
});
}),
});
66 changes: 66 additions & 0 deletions src/server/auth/custom-providers/etsy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { env } from "@/env";

import type { OAuth2Config, OAuthUserConfig } from "next-auth/providers";

export interface EtsyProfile {
user_id: number;
primary_email?: string | null;
first_name?: string | null;
last_name?: string | null;
image_url_75x75?: string | null;
}

export const etsyScopes = "email_r shops_r listings_r";

export default function EtsyProvider<P extends EtsyProfile>(
options: OAuthUserConfig<P>,
): OAuth2Config<P> {
return {
id: "etsy",
name: "Etsy",
type: "oauth",
clientId: options.clientId,
clientSecret: options.clientId,
authorization: {
url: "https://www.etsy.com/oauth/connect",
params: {
scope: etsyScopes,
state: Math.random().toString(36).substring(2, 15),
},
},
token: {
url: "https://openapi.etsy.com/v3/public/oauth/token",
params: {
client_id: env.AUTH_ETSY_ID,
},
},
client: { token_endpoint_auth_method: "none" },
userinfo: {
url: "https://openapi.etsy.com/v3/application/users/me",
async request({ tokens }: { tokens: { access_token: string } }) {
const userId = parseInt(tokens.access_token.split(".")[0]!);

const response = await fetch(
`https://api.etsy.com/v3/application/users/${userId}`,
{
headers: {
"x-api-key": env.AUTH_ETSY_ID,
Authorization: `Bearer ${tokens.access_token}`,
},
},
);

return (await response.json()) as EtsyProfile;
},
},
profile(profile) {
return {
id: profile.user_id.toString(),
name: profile.first_name,
email: profile.primary_email,
image: profile.image_url_75x75,
};
},
options,
};
}
14 changes: 12 additions & 2 deletions src/server/auth/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ import SpotifyProvider, {
} from "next-auth/providers/spotify";
import StravaProvider, { type StravaProfile } from "next-auth/providers/strava";
import CredentialsProvider from "next-auth/providers/credentials";
import EtsyProvider, { type EtsyProfile } from "./custom-providers/etsy";

import { IS_DEVELOPMENT } from "@/lib/constants";
import { db } from "../db";

import type {
CredentialInput,
CredentialsConfig,
OAuthConfig,
} from "next-auth/providers";
import { IS_DEVELOPMENT } from "@/lib/constants";
import { db } from "../db";

export const providers: (
| OAuthConfig<DiscordProfile>
Expand All @@ -31,6 +33,7 @@ export const providers: (
| OAuthConfig<NotionProfile>
| OAuthConfig<StravaProfile>
| OAuthConfig<SpotifyProfile>
| OAuthConfig<EtsyProfile>
| CredentialsConfig<Record<string, CredentialInput>>
)[] = [
...("AUTH_GOOGLE_ID" in env && "AUTH_GOOGLE_SECRET" in env
Expand Down Expand Up @@ -121,6 +124,13 @@ export const providers: (
}),
]
: []),
...("AUTH_ETSY_ID" in env
? [
EtsyProvider({
clientId: env.AUTH_ETSY_ID,
}),
]
: []),
...(IS_DEVELOPMENT
? [
CredentialsProvider({
Expand Down
19 changes: 19 additions & 0 deletions src/toolkits/toolkits/Etsy/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { z } from "zod";

import { EtsyTools } from "./tools/tools";

import { getListings } from "@/toolkits/toolkits/etsy/tools/get-listings/base";

import type { ToolkitConfig } from "@/toolkits/types";

export const etsyParameters = z.object({});

export const baseEtsyToolkitConfig: ToolkitConfig<
EtsyTools,
typeof etsyParameters.shape
> = {
tools: {
[EtsyTools.getListings]: getListings,
},
parameters: etsyParameters,
};
41 changes: 41 additions & 0 deletions src/toolkits/toolkits/Etsy/client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { SiEtsy } from "@icons-pack/react-simple-icons";

import { EtsyWrapper } from "./wrapper";

import { Link } from "../components/link";

import { baseEtsyToolkitConfig } from "./base";

import { createClientToolkit } from "@/toolkits/create-toolkit";

import { getListingsClientConfig } from "@/toolkits/toolkits/etsy/tools/get-listings/client";

import { ToolkitGroups } from "@/toolkits/types";
import { EtsyTools } from "./tools/tools";

export const etsyClientToolkit = createClientToolkit(
baseEtsyToolkitConfig,
{
name: "Etsy Toolkit",
description: "Etsy toolkit for fetching listing details.",
icon: SiEtsy,
form: null,
type: ToolkitGroups.DataSource,
Wrapper: EtsyWrapper,
envVars: [
{
type: "all",
keys: ["AUTH_ETSY_ID"],
description: (
<span>
Create a Etsy OAuth application{" "}
<Link href="https://www.etsy.com/developers">here</Link>
</span>
),
},
],
},
{
[EtsyTools.getListings]: getListingsClientConfig,
},
);
37 changes: 37 additions & 0 deletions src/toolkits/toolkits/Etsy/security-data-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { ISecurityDataStorage, SecurityDataFilter, Tokens } from "etsy-ts";
import { api } from "@/trpc/server";
import { etsyScopes } from "@/server/auth/custom-providers/etsy";

export class EtsySecurityDataStorage implements ISecurityDataStorage {
async storeAccessToken(filter: SecurityDataFilter, accessToken: Tokens) {
await api.accounts.updateAccount({
provider: "etsy",
providerAccountId: filter.etsyUserId.toString(),
data: {
access_token: accessToken.accessToken,
refresh_token: accessToken.refreshToken,
token_type: accessToken.tokenType,
expires_at: accessToken.expiresIn + Date.now() / 1000,
scope: etsyScopes,
},
});
}

async findAccessToken(): Promise<Tokens | undefined> {
const account = await api.accounts.getAccountByProvider("etsy");
if (
!account?.access_token ||
!account.refresh_token ||
!account.token_type ||
!account.expires_at
)
return undefined;

return {
accessToken: account.access_token,
refreshToken: account.refresh_token,
tokenType: account.token_type,
expiresIn: account.expires_at - Date.now() / 1000,
};
}
}
38 changes: 38 additions & 0 deletions src/toolkits/toolkits/Etsy/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Etsy } from "etsy-ts";

import { createServerToolkit } from "../../create-toolkit";

import { api } from "@/trpc/server";

import { baseEtsyToolkitConfig } from "./base";

import { EtsyTools } from "./tools/tools";
import { EtsySecurityDataStorage } from "./security-data-storage";

import { getListingsServerConfig } from "@/toolkits/toolkits/etsy/tools/get-listings/server";

export const etsyToolkitServer = createServerToolkit(
baseEtsyToolkitConfig,
"You have access to the Etsy toolkit for general account management. Currently, this toolkit provides:\n" +
"- **Get Listings**: Retrieves all listings and their image URLs associated with the shop associated with the signed-in user.\n\n",
async () => {
const account = await api.accounts.getAccountByProvider("etsy");

if (!account) {
throw new Error("No Etsy account found");
}
if (!account.access_token) {
throw new Error("No Etsy access token found");
}

const etsy = new Etsy({
apiKey: process.env.AUTH_ETSY_ID!,
securityDataStorage: new EtsySecurityDataStorage(),
enableTokenRefresh: true,
});

return {
[EtsyTools.getListings]: getListingsServerConfig(etsy),
};
},
);
12 changes: 12 additions & 0 deletions src/toolkits/toolkits/Etsy/tools/get-listings/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { z } from "zod";
import { createBaseTool } from "@/toolkits/create-tool";
import type { IShopListing } from "etsy-ts";

export const getListings = createBaseTool({
description:
"Fetches all listings from the Etsy shop associated with the authenticated user.",
inputSchema: z.object({}),
outputSchema: z.object({
results: z.array(z.custom<IShopListing>()),
}),
});
Loading
Loading