Skip to content
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: save gh email when login #25

Merged
merged 5 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions drizzle/0001_crazy_eternals.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE user ADD `email` text;
186 changes: 186 additions & 0 deletions drizzle/meta/0001_snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
{
"version": "5",
"dialect": "sqlite",
"id": "1752cbef-1ce6-4863-bcef-5ffad31ac535",
"prevId": "842060cb-8a3f-4721-aeb8-909365440ca3",
"tables": {
"user": {
"name": "user",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"picture": {
"name": "picture",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
},
"user_auth": {
"name": "user_auth",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"provider": {
"name": "provider",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "CURRENT_TIMESTAMP"
}
},
"indexes": {
"user_auth_provider_provider_id_unique": {
"name": "user_auth_provider_provider_id_unique",
"columns": [
"provider",
"provider_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
},
"user_session": {
"name": "user_session",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"auth_id": {
"name": "auth_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"expires_at": {
"name": "expires_at",
"type": "blob",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"user_session_expire_idx": {
"name": "user_session_expire_idx",
"columns": [
"expires_at"
],
"isUnique": false
},
"user_session_auth_id_idx": {
"name": "user_session_auth_id_idx",
"columns": [
"auth_id"
],
"isUnique": false
}
},
"foreignKeys": {
"user_session_user_id_user_id_fk": {
"name": "user_session_user_id_user_id_fk",
"tableFrom": "user_session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
}
},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
}
}
7 changes: 7 additions & 0 deletions drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
"when": 1710049140295,
"tag": "0000_solid_scream",
"breakpoints": true
},
{
"idx": 1,
"version": "5",
"when": 1710401496821,
"tag": "0001_crazy_eternals",
"breakpoints": true
}
]
}
30 changes: 26 additions & 4 deletions src/app/login/github/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export async function GET(request: Request): Promise<Response> {
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const headerStore = headers();
const GITHUB_API_URL = "https://api.github.com";

const storedState = cookies().get("github_oauth_state")?.value ?? null;
if (!code || !state || !storedState || state !== storedState) {
Expand All @@ -19,14 +20,25 @@ export async function GET(request: Request): Promise<Response> {
}

try {
const tokens = await github.validateAuthorizationCode(code);
const githubUserResponse = await fetch("https://api.github.com/user", {
const token = await github.validateAuthorizationCode(code);
const githubUserResponse = await fetch(`${GITHUB_API_URL}/user`, {
headers: {
Authorization: `Bearer ${tokens.accessToken}`,
Authorization: `Bearer ${token.accessToken}`,
},
});
const githubUser: GitHubUser = await githubUserResponse.json();

if (githubUser.email === null) {
const resp = await fetch(`${GITHUB_API_URL}/user/emails`, {
headers: {
Authorization: `Bearer ${token.accessToken}`,
},
});
const githubEmails: GitHubEmail[] = await resp.json();
githubUser.email =
githubEmails.find((email) => email.primary)?.email || null;
}

// Replace this with your own DB client.
const existingUser = await db.query.user_oauth.findFirst({
where: (field, op) =>
Expand Down Expand Up @@ -61,7 +73,9 @@ export async function GET(request: Request): Promise<Response> {
const userId = generateId(15);
const authId = generateId(15);

await db.insert(user).values({ id: userId, name: githubUser.login });
await db
.insert(user)
.values({ id: userId, name: githubUser.login, email: githubUser.email });
await db.insert(user_oauth).values({
id: authId,
provider: "GITHUB",
Expand Down Expand Up @@ -106,4 +120,12 @@ export async function GET(request: Request): Promise<Response> {
interface GitHubUser {
id: string;
login: string;
email: string | null;
}

interface GitHubEmail {
email: string;
primary: boolean;
verified: boolean;
visibility: "public" | "private";
}
4 changes: 3 additions & 1 deletion src/app/login/github/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { cookies } from "next/headers";

export async function GET(): Promise<Response> {
const state = generateState();
const url = await github.createAuthorizationURL(state);
const url = await github.createAuthorizationURL(state, {
scopes: ["user:email"],
});

cookies().set("github_oauth_state", state, {
path: "/",
Expand Down
1 change: 1 addition & 0 deletions src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const user = sqliteTable("user", {
createdAt: text("created_at")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
email: text("email"),
});

export const user_session = sqliteTable(
Expand Down
Loading