Simple User and Session store service for Cloudflare workers
import Auth from "@brevitybuilder/worker-auth";
import FaunaStore from "@brevitybuilder/worker-auth/fauna";
export interface Env {}
// setup store and auth
const store = new FaunaStore("fauna secret", "db.us.fauna.com");
const auth = new Auth({ secret: "jwt secret" }, store);
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const url = new URL(request.url);
// let auth handle the auth API routes
if (url.pathname.startsWith("/api/auth")) {
return await auth.handle(request);
}
// in a request, validate user is authenticated
// you need to pass a headers obj in because we may need to add a `Set-Cookie` header
// in the case that we had to revalidate the user.
const headers = new Headers();
const user = await auth.getUserFromRequest(request, headers);
if (user) {
return new Response("Authenticated", { status: 200, headers });
}
return new Response("Not Authenticated!", { status: 401, headers });
},
};
GET /api/auth/refresh
- Will refresh the stateless JWT using the stateful JWTGET /api/auth/signout
- End session and remove all cookiesGET /api/auth/signout/:sessionId
- End session with specific idGET /api/auth/sessions
- Get list of all active sessionId for userPOST /api/auth/signup
- Create new user and log inPOST /api/auth/signin
- Login user with given credentials
- Fauna
More providers coming soon.