Created
July 9, 2024 22:00
-
-
Save claughinghouse/6e385e8467e65a7591404f4718128f63 to your computer and use it in GitHub Desktop.
auth.ts sstv2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCookie, useQueryParam, useResponse } from "sst/node/api"; | |
import { Config } from "sst/node/config"; | |
import { AuthHandler, GoogleAdapter } from "sst/node/future/auth"; | |
import { User } from "@strdb/core/user"; | |
declare module "sst/node/future/auth" { | |
export interface SessionTypes { | |
user: { | |
userID: string; | |
}; | |
} | |
} | |
export const handler = AuthHandler({ | |
async clients() { | |
return { | |
next: "", | |
}; | |
}, | |
providers: { | |
google: GoogleAdapter({ | |
mode: "oauth", | |
clientID: Config.GOOGLE_CLIENT_ID, | |
clientSecret: Config.GOOGLE_CLIENT_SECRET, | |
scope: "openid email profile", | |
}), | |
}, | |
async onAuthorize() { | |
const ref = useQueryParam("ref"); | |
if (ref) | |
useResponse().cookie({ | |
key: "ref", | |
value: ref, | |
httpOnly: true, | |
secure: true, | |
maxAge: 60 * 10, | |
sameSite: "Strict", | |
}); | |
}, | |
async onSuccess(input, response) { | |
let user: User.Info | undefined = undefined; | |
if (input.provider === "google") { | |
const claims = input.tokenset.claims(); | |
const email = claims.email; | |
if (!email) throw new Error("No email found"); | |
const exists = await User.fromEmail(email); | |
exists | |
? (user = exists) | |
: (user = await User.create({ | |
username: email.split("@")[0], | |
name: claims.name!, | |
email: email, | |
roles: "user", | |
avatar: claims.picture?.replace("s96-c", "s400-c") || "", | |
ref: useCookie("ref"), | |
})); | |
} | |
// return response.http({ | |
// statusCode: 200, | |
// body: JSON.stringify(input), | |
return response.session({ | |
type: "user", | |
properties: { | |
userID: user!.userID, | |
// email: user!.email, | |
// user: user, | |
}, | |
}); | |
}, | |
async onError() { | |
return { | |
statusCode: 400, | |
headers: { | |
"Content-Type": "text/plain", | |
}, | |
body: "Auth failed", | |
}; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment