@auth/solid-start
Version:
Authentication for SolidStart.
72 lines (71 loc) • 2.58 kB
JavaScript
export async function signIn(provider, options, authorizationParams) {
const { callbackUrl, ...rest } = options ?? {};
const { redirect = true, redirectTo = callbackUrl ?? window.location.href, ...signInParams } = rest;
const isCredentials = provider === "credentials";
const signInUrl = `/api/auth/${isCredentials ? "callback" : "signin"}/${provider}`;
// TODO: Handle custom base path
const csrfTokenResponse = await fetch("/api/auth/csrf");
const { csrfToken } = await csrfTokenResponse.json();
const res = await fetch(`${signInUrl}?${new URLSearchParams(authorizationParams)}`, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
body: new URLSearchParams({
...signInParams,
csrfToken,
callbackUrl: redirectTo,
}),
});
const data = await res.json();
if (redirect) {
const url = data.url ?? redirectTo;
window.location.href = url;
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes("#"))
window.location.reload();
return;
}
const error = new URL(data.url).searchParams.get("error") ?? undefined;
const code = new URL(data.url).searchParams.get("code") ?? undefined;
return {
error,
code,
status: res.status,
ok: res.ok,
url: error ? null : data.url,
};
}
/**
* Signs the user out, by removing the session cookie.
* Automatically adds the CSRF token to the request.
*
* ```ts
* import { signOut } from "@auth/solid-start/client"
* signOut()
* ```
*/
export async function signOut(options) {
const { callbackUrl = window.location.href } = options ?? {};
// TODO: Custom base path
const csrfTokenResponse = await fetch("/api/auth/csrf");
const { csrfToken } = await csrfTokenResponse.json();
const res = await fetch(`/api/auth/signout`, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Auth-Return-Redirect": "1",
},
body: new URLSearchParams({
csrfToken,
callbackUrl,
}),
});
const data = await res.json();
const url = data.url ?? data.redirect ?? callbackUrl;
window.location.href = url;
// If url contains a hash, the browser does not reload the page. We reload manually
if (url.includes("#"))
window.location.reload();
}