-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: ✨ implement google oauth #27
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
751eff3
feat: ✨ [SEMI-STABLE] implement google oauth
KevinWu098 c1fdb54
chore: 🔧 cleanup code
KevinWu098 6122bac
feat: ✨ use sub prop for id
KevinWu098 61f33a8
style: 🎨 move google button to layout
KevinWu098 1192128
fix: 🐛 handle empty name fields
KevinWu098 016c2cd
chore: 🔧 [STABLE] remove unused deps
KevinWu098 6ddc698
chore: 🔧 remove unused fields
KevinWu098 70ea250
feat: ✨ use email as userId
KevinWu098 7e74bbb
fix: 🐛 add console log to try block
KevinWu098 baedba9
Merge remote-tracking branch 'origin' into 23-google-auth
KevinWu098 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Binary file not shown.
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { dev } from "$app/environment"; | ||
import { googleAuth } from "$lib/server/lucia"; | ||
|
||
export const GET = async ({ cookies, locals }) => { | ||
const session = await locals.auth.validate(); | ||
|
||
if (session) { | ||
return new Response(null, { | ||
status: 302, | ||
headers: { | ||
Location: "/", | ||
}, | ||
}); | ||
} | ||
const [url, state] = await googleAuth.getAuthorizationUrl(); | ||
|
||
// Store state. | ||
cookies.set("google_oauth_state", state, { | ||
httpOnly: true, | ||
secure: !dev, | ||
path: "/", | ||
maxAge: 30 * 24 * 60 * 60, | ||
}); | ||
|
||
return new Response(null, { | ||
status: 302, | ||
headers: { | ||
Location: url.toString(), | ||
}, | ||
}); | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
import { OAuthRequestError } from "@lucia-auth/oauth"; | ||
import type { GoogleUser } from "@lucia-auth/oauth/providers"; | ||
|
||
import { auth, googleAuth } from "$lib/server/lucia"; | ||
|
||
const getUser = async (googleUser: GoogleUser) => { | ||
if (!googleUser.email) { | ||
return null; | ||
} | ||
|
||
try { | ||
const dbUser = await auth.getUser(googleUser.email); | ||
if (dbUser) { | ||
return dbUser; | ||
} | ||
} catch (error) { | ||
/* If a user cannot be found, an error is raised and caught here. */ | ||
KevinWu098 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
console.log("User not found in database", error); | ||
} | ||
|
||
const token = crypto.randomUUID(); | ||
const user = await auth.createUser({ | ||
userId: googleUser.email.toLowerCase(), | ||
key: { | ||
providerId: "google", | ||
providerUserId: googleUser.email.toLowerCase(), | ||
password: null, | ||
}, | ||
attributes: { | ||
email: googleUser.email.toLowerCase(), | ||
firstName: googleUser.given_name ?? "", | ||
lastName: googleUser.family_name ?? "", | ||
// role: "USER", | ||
verified: false, | ||
receiveEmail: true, | ||
token: token, | ||
}, | ||
}); | ||
|
||
return user; | ||
}; | ||
|
||
export const GET = async ({ url, cookies, locals }) => { | ||
/** | ||
* Check for a session. if it exists, | ||
* redirect to a page of your liking. | ||
*/ | ||
const session = await locals.auth.validate(); | ||
if (session) { | ||
return new Response(null, { | ||
status: 302, | ||
headers: { | ||
Location: "/auth", | ||
}, | ||
}); | ||
} | ||
|
||
/** | ||
* Validate state of the request. | ||
*/ | ||
const storedState = cookies.get("google_oauth_state") ?? null; | ||
const state = url.searchParams.get("state"); | ||
const code = url.searchParams.get("code"); | ||
if (!storedState || !state || storedState !== state || !code) { | ||
return new Response(null, { | ||
status: 400, | ||
}); | ||
} | ||
|
||
try { | ||
const { googleUser } = await googleAuth.validateCallback(code); | ||
const user = await getUser(googleUser); | ||
|
||
if (!user) { | ||
/** | ||
* You should probably redirect the user to a page and show a | ||
* message that the account could not be created. | ||
* | ||
* This is a very rare case, but it can happen. | ||
*/ | ||
return new Response(null, { | ||
status: 500, | ||
}); | ||
} | ||
|
||
const session = await auth.createSession({ | ||
userId: user.userId, | ||
attributes: {}, | ||
}); | ||
|
||
locals.auth.setSession(session); | ||
|
||
return new Response(null, { | ||
status: 302, | ||
headers: { | ||
Location: "/auth", | ||
}, | ||
}); | ||
} catch (e) { | ||
console.log(e); | ||
|
||
// Invalid code. | ||
if (e instanceof OAuthRequestError) { | ||
return new Response(null, { | ||
status: 400, | ||
}); | ||
} | ||
|
||
// All other errors. | ||
return new Response(null, { | ||
status: 500, | ||
}); | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be outside of the try block
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a weird... quirk of Lucia (?) where
auth.getUser()
raises an error when passed a key not in the database.The try block allows for a "quiet" handling of the not found case. I've attempted to find an alternate solution, but this piece of code isn't particularly offensive to me.
I can hunt down an alternate solution if you'd pref.