Skip to content

Commit 2932c33

Browse files
docs: backup from Readme
1 parent 752a921 commit 2932c33

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+3776
-0
lines changed

docs/v0.2.3/Auth/login.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
---
2+
title: "login"
3+
slug: "login"
4+
excerpt: "Login users with Polyfire Auth"
5+
hidden: false
6+
createdAt: "Wed Sep 27 2023 07:29:51 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:49 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
> 📘 Auth is required
10+
>
11+
> All the components and functions in the SDK require you to connect your users to Polyfire Auth.
12+
>
13+
> Because all calls to the Polyfire API use LLMs (and therefore cost money) or access user data, the client needs some kind of secured authentification.
14+
>
15+
> You don't need to authenticate your users entirely through Polyfire (e.g. we can authenticate your Firebase or Supabase user tokens). If you need a custom auth provider integrated, [tell us on Discord](https://discord.polyfire.com).
16+
17+
Login users client-side to create unique user sessions.
18+
19+
- Works with providers "Google" and "GitHub" but also "Firebase" (see below).
20+
- Must be called to use _models_ and _data_ modules client-side.
21+
22+
```typescript
23+
export declare function login(input: LoginFunctionInput, projectOptions: {
24+
project: string;
25+
endpoint: string;
26+
}): Promise<void>;
27+
```
28+
29+
## Types
30+
31+
```typescript
32+
type SimpleProvider = "github" | "google";
33+
type LoginWithFirebaseInput = {
34+
token: string;
35+
provider: "firebase";
36+
};
37+
type LoginFunctionInput = SimpleProvider | {
38+
provider: SimpleProvider;
39+
} | LoginWithFirebaseInput;
40+
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: "Anonymous (Not intended for Production)"
3+
slug: "anonymous-not-intended-for-production"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Mon Oct 16 2023 12:05:20 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:49 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
To simplify your onboarding with polyfire, we added an "anonymous" login method.
10+
11+
It must first be activated in the dashboard in your project settings.
12+
13+
**After that, logging in should be automatic.**
14+
15+
You can also try to call it manually (after a logout for example) with:
16+
17+
```js Javascript
18+
login({ provider: "anonymous" });
19+
```
20+
21+
If you want to simulate multiple users, the login function also provides you with the ability to add an email to differentiate them like this:
22+
23+
```js Javascript
24+
login({ provider: "anonymous", email: "user@example.com" });
25+
```
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
title: "Custom Authentification System"
3+
slug: "custom-authentification-system"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Mon Oct 16 2023 11:41:24 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:49 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
If you are already using a custom authentification system and want to link Polyfire to your authentification system, you can use the "custom" provider.
10+
11+
You will need to sign a Json Web Token using the RSA/RS256 algorithm and input your public key in the PEM format in the dashboard in the "Custom Auth Public Key" field of your project's settings.
12+
13+
Your JWT must contains these fields:
14+
15+
- `iss`: Your project alias
16+
- `aud`: must be:`polyfire_custom_auth_api`
17+
- `sub`: The id of the user you want to identify. It can be any string as long as it is unique to the user.
18+
19+
For example. Assuming the public key is already added in the dashboard "Custom Auth Public Key" field, somewhere in server-side code:
20+
21+
```js Javascript
22+
23+
const token = jwt.sign(
24+
{
25+
iss: projectAlias,
26+
aud: "polyfire_custom_auth_api", // Don't change this string
27+
sub: userID,
28+
},
29+
privateKey, // Leaking this key would allow to connect as any user. Make sure it's never sent client-side.
30+
{ algorithm: "RS256" }
31+
);
32+
```
33+
34+
The generated token can then be used client-side in the login function like this:
35+
36+
```js Javascript
37+
login({ provider: "custom", token: theTokenGeneratedBefore })
38+
```

docs/v0.2.3/Auth/login/firebase.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
title: "Firebase"
3+
slug: "firebase"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Mon Oct 16 2023 11:40:36 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:49 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
## Add your Firebase Project ID to your project
10+
11+
Before being able to use firebase as a login method you first need to link your Firebase project to your polyfire project.
12+
13+
You can find your Firebase Project ID in your project settings in the firebase console <https://console.firebase.google.com/>. Choose your project, click on the gear icon in the top left corner and click on "Project Settings". Your Project ID will be displayed among other infos.
14+
15+
To link it to your Polyfire project, go on <https://beta.polyfire.com/> and choose your project. When you are in the project detail page, click on the Edit button and add your Firebase Project ID before saving.
16+
17+
## Setup the Firebase login
18+
19+
If you didn't do it already, follow this tutorial to setup the login with firebase: <https://firebase.google.com/docs/auth/web/start>
20+
21+
## Link your Firebase User Session to Polyfire
22+
23+
You can set the provider to firebase and send a firebase token to the login function parameter. To get a firebase token, you can use the `getIdToken()` method of the firebase user object.
24+
25+
For example:
26+
27+
```js Javascript
28+
const userCredentials = await signInWithEmailAndPassword(
29+
auth,
30+
"john.doe@example.com",
31+
"correct_horse_battery_staple"
32+
);
33+
34+
const user = userCredentials.user;
35+
36+
const firebaseToken = await user.getIdToken();
37+
38+
const polyfire = PolyfireClientBuilder({ project: "your_project_alias" })
39+
await polyfire.auth.login({ provider: "firebase", token: firebaseToken })
40+
41+
// You can now use the Polyfire Client:
42+
const helloWorldHaiku = await polyfire.generate("Write me a hello world haiku");
43+
44+
console.log(helloWorldHaiku);
45+
```
46+
47+
> 📘 With the usePolyfire React Hook
48+
>
49+
> Using the usePolyfire React Hook it would work the same except that you would be importing the _auth_ module from usePolyfire instead of creating a client object like higher up.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
title: "OAuth Providers"
3+
slug: "login-with-providers"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Wed Sep 27 2023 07:17:47 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:41:44 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
For Polyfire to work client-side, **you need to setup unique user sessions**. That way, each user of your app will have a custom, rate-limited, API token and can use your app according to the restrictions you give them.
10+
11+
To do that you can use our login functions, from the _auth_ module.
12+
13+
```jsx
14+
import React from 'react';
15+
import { usePolyfire } from 'polyfire-js/hooks';
16+
17+
function App() {
18+
const { auth } = usePolyfire();
19+
const { login, status } = auth;
20+
21+
if (status == 'loading') {
22+
return (
23+
<div>Loading...</div>
24+
)
25+
} else if (status == 'authenticated') {
26+
return (
27+
<div>We already logged in!</div>
28+
)
29+
} else if (status == 'unauthenticated') {
30+
return (
31+
<button onClick={() => login("github")}>Login With GitHub</button>
32+
)
33+
} else {
34+
return <div />
35+
}
36+
}
37+
38+
export default App;
39+
```
40+
41+
# Linking pre-existing auth system
42+
43+
If you have Firebase Auth setup. Pass in your JWT as shown [in that tutorial](doc:signin-firebase). If you want integrations to other auth providers:[message us on our Discord](https://www.polyfire.com/discord).
44+
45+
You can also connect your own auth system [by doing a custom auth.](doc:custom-authentification-system)
46+
47+
# Providers Available
48+
49+
The sign in providers available are GitHub, Google, Microsoft (Azure) and Firebase (passing your Firebase JWT).
50+
51+
[Reach out on Discord if you want more.](discord.polyfire.com)

docs/v0.2.3/Auth/logout.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: "logout"
3+
slug: "logout"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Wed Sep 27 2023 07:32:37 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:48 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
Ends user session and cleans cache.
10+
11+
- Doesn't return anything.
12+
- Will require user to re-authenticate user to use API modules. (models, data, etc).
13+
14+
```typescript
15+
export declare function logout(): Promise<void>;
16+
```
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
---
2+
title: "Stripe Integration"
3+
slug: "react-stripe-subscriptions"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Mon Sep 11 2023 09:26:19 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Wed Nov 29 2023 15:37:38 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
# 1. Initialize the Stripe webhook
10+
11+
- You first need a Polyfire project. You can [create one here](https://beta.polyfire.com/project/new).
12+
- Go to _Auth > Payments_ on your Polyfire dashboard.
13+
- Copy the webhook URL for one of the next steps.
14+
15+
# 2. Configure User Rate Limits
16+
17+
- **Free User Rate Limit** :
18+
Set a dollar threshold for free app usage under `Free User Rate Limit`.
19+
- **Premium User Rate Limit **:
20+
Assign a higher dollar limit for premium users in the `Premium User Rate Limit`.
21+
- **Developer Rate Limit Testing**:
22+
To test rate limits, toggle `Dev has rate limit?` to 'On' in development.
23+
Adjust or disable this in production.
24+
Now save your settings by clicking on the "Save" button.
25+
26+
# 2. Add the webhook on the Stripe dashboard
27+
28+
- Add the generated webhook [here on Stripe](https://dashboard.stripe.com/webhooks) .
29+
- Configure the webhook to be sent on all events (You can also select manually theses events: _customer.created, customer.updated, checkout.session.completed, customer.subscription.created, customer.subscription.updated and customer.subscription.deleted_)
30+
31+
# 3. Create a payment link
32+
33+
- Create a new Stripe payment link [here](https://dashboard.stripe.com/payment-links/create) on your Stripe dashboard.
34+
- In the product field, select Add new product, give it the name, image, description and price you want. Set the payment to Recurring and select Monthly in billing period.
35+
- In the After payment tab, choose Don't show confirmation page and set the address of your app.
36+
_NOTE: for localhost, use <http://127.0.0.1>, you will need this address instead of http\://localhost in your tests to stay connected after the payment._
37+
- Create the link and copy it.
38+
39+
# 4. Add the paywall to your app
40+
41+
For this part, I am going to use the chat we made in this tutorial: [Making ChatGPT](doc:chatgpt-clone)
42+
43+
We create a component that will be displayed instead of the chat if this user didn't pay yet. Don't forget to replace `<YOUR_STRIPE_PAYMENT_LINK>` by your payment link.
44+
45+
Polyfire uses the userID as the identifier to know which user paid a subscription, this is why we use the client_reference_id query parameter.
46+
47+
```jsx
48+
function Paywall({ userId }: { userId: string }) {
49+
return (
50+
<div className="flex flex-col justify-center items-center h-full py-2">
51+
<a className="cursor-pointer bg-black text-white ml-2 p-2 px-5 font-mono" href={`<YOUR_STRIPE_PAYMENT_LINK>?client_reference_id=${userId}`}>
52+
Access this application for only 420.69$/month
53+
</a>
54+
</div>
55+
);
56+
}
57+
58+
```
59+
60+
We can then modify the App component to get the userId and add the paywall when the rate limit has been reached - which should be right away in this case since the rate limit is 0.
61+
62+
```jsx
63+
function App() {
64+
const polyfire = usePolyfire();
65+
66+
const { login, status, user } = polyfire.auth;
67+
const { getAuthID, usage } = user;
68+
69+
const { Chat } = polyfire.utils;
70+
71+
72+
const [chat, setChat] = useState<ChatType>();
73+
const [paywall, setPaywall] = useState(false);
74+
const [userId, setUserId] = useState<string>();
75+
const [messages, setMessages] = useState<
76+
{ is_user_message: boolean; content: string }[]
77+
>([]);
78+
79+
useEffect(() => {
80+
if (status === "authenticated") {
81+
const updateUsage = async () => {
82+
const userId = await getAuthID();
83+
setUserId(userId);
84+
85+
const userUsage = await usage();
86+
if (userUsage.rateLimit === undefined || userUsage.rateLimit === null) {
87+
setPaywall(false);
88+
} else {
89+
setPaywall(userUsage.rateLimit <= userUsage.usage);
90+
}
91+
92+
setChat(new Chat());
93+
};
94+
95+
updateUsage();
96+
}
97+
}, [status]);
98+
99+
if (status === "unauthenticated") {
100+
return (
101+
<button onClick={() => login({ provider: "github" })}>
102+
Login with Github
103+
</button>
104+
);
105+
}
106+
107+
if (chat && !paywall) {
108+
return (
109+
<ChatBox
110+
messages={messages}
111+
onMessage={async (message: string) => {
112+
await chat.sendMessage(message);
113+
setMessages((await chat.getMessages()).reverse());
114+
}}
115+
/>
116+
);
117+
}
118+
119+
if (paywall && userId && status !== "loading") {
120+
return <Paywall userId={userId} />;
121+
}
122+
123+
return <div>Loading...</div>;
124+
}
125+
```

docs/v0.2.3/Auth/user.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
title: "user"
3+
slug: "user"
4+
excerpt: ""
5+
hidden: false
6+
createdAt: "Wed Sep 27 2023 07:39:48 GMT+0000 (Coordinated Universal Time)"
7+
updatedAt: "Fri Mar 01 2024 06:33:49 GMT+0000 (Coordinated Universal Time)"
8+
---
9+
User object with Auth and Token IDs.
10+
11+
- Give you access to a unique userID
12+
- Useful to mesure rateLimit and user's usage if you want to trigger a paywall / payment flow.
13+
14+
```typescript
15+
export type UserClient = {
16+
usage: () => Promise<{
17+
usage: number;
18+
rateLimit?: number;
19+
}>;
20+
getAuthID: () => Promise<string>;
21+
getToken: () => Promise<string>;
22+
};
23+
```

0 commit comments

Comments
 (0)