feat: Add support for authentication to the sdk, and plug it in the admin (#7349)

* feat: Add support for authentication to the sdk, and plug it in the admin

* fix: await fetch before returning in sdk
This commit is contained in:
Stevche Radevski
2024-05-17 14:37:38 +02:00
committed by GitHub
parent ff337498a0
commit 00a37cede1
13 changed files with 207 additions and 133 deletions

View File

@@ -0,0 +1,33 @@
import { Client } from "../client"
import { Config } from "../types"
export class Auth {
private client: Client
private config: Config
constructor(client: Client, config: Config) {
this.client = client
this.config = config
}
login = async (payload: { email: string; password: string }) => {
// TODO: It is a bit strange to eg. require to pass `scope` in `login`, it might be better for us to have auth methods in both `admin` and `store` classes instead?
const { token } = await this.client.fetch<{ token: string }>(
"/auth/admin/emailpass",
{
method: "POST",
body: payload,
}
)
// By default we just set the token in memory, if configured to use sessions we convert it into session storage instead.
if (this.config?.auth?.type === "session") {
await this.client.fetch("/auth/session", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
})
} else {
this.client.setToken(token)
}
}
}