From a09649004465f85aac1e445444cf95c400c3d23a Mon Sep 17 00:00:00 2001 From: Mark1 <3292578+0ahz@users.noreply.github.com> Date: Sat, 2 Nov 2024 17:52:39 +0800 Subject: [PATCH] feat: add social-provider Gitlab (#386) --- docs/components/sidebar-content.tsx | 17 +++ docs/content/docs/authentication/gitlab.mdx | 48 +++++++ .../src/social-providers/gitlab.ts | 124 ++++++++++++++++++ .../better-auth/src/social-providers/index.ts | 3 + 4 files changed, 192 insertions(+) create mode 100644 docs/content/docs/authentication/gitlab.mdx create mode 100644 packages/better-auth/src/social-providers/gitlab.ts diff --git a/docs/components/sidebar-content.tsx b/docs/components/sidebar-content.tsx index ba0e8da4..d001d8a1 100644 --- a/docs/components/sidebar-content.tsx +++ b/docs/components/sidebar-content.tsx @@ -548,6 +548,23 @@ export const contents: Content[] = [ ), }, + { + title: "Gitlab", + href: "/docs/authentication/gitlab", + icon: () => ( + + + + ), + }, ], }, { diff --git a/docs/content/docs/authentication/gitlab.mdx b/docs/content/docs/authentication/gitlab.mdx new file mode 100644 index 00000000..b0e90e07 --- /dev/null +++ b/docs/content/docs/authentication/gitlab.mdx @@ -0,0 +1,48 @@ +--- +title: Gitlab +description: Gitlab Provider +--- + + + + ### Get your Gitlab credentials + To use Gitlab sign in, you need a client ID and client secret. [GitLab OAuth documentation](https://docs.gitlab.com/ee/api/oauth2.html). + + Make sure to set the redirect URL to `http://localhost:3000/api/auth/callback/gitlab` for local development. For production, you should set it to the URL of your application. If you change the base path of the auth routes, you should update the redirect URL accordingly. + + + + ### Configure the provider + To configure the provider, you need to import the provider and pass it to the `socialProviders` option of the auth instance. + + ```ts title="auth.ts" + import { betterAuth } from "better-auth" + + export const auth = betterAuth({ + socialProviders: { // [!code highlight] + gitlab: { // [!code highlight] + clientId: process.env.GITLAB_CLIENT_ID as string, // [!code highlight] + clientSecret: process.env.GITLAB_CLIENT_SECRET as string, // [!code highlight] + issuer: process.env.GITLAB_ISSUER as string, // [!code highlight] + }, // [!code highlight] + }, // [!code highlight] + }) + ``` + + + ### Signin with Gitlab + To signin with Gitlab, you can use the `signIn.social` function provided by the client. The `signIn` function takes an object with the following properties: + - `provider`: The provider to use. It should be set to `gitlab`. + + ```ts title="client.ts" + import { createAuthClient } from "better-auth/client" + const client = createAuthClient() + + const signin = async () => { + const data = await client.signIn.social({ + provider: "gitlab" + }) + } + ``` + + diff --git a/packages/better-auth/src/social-providers/gitlab.ts b/packages/better-auth/src/social-providers/gitlab.ts new file mode 100644 index 00000000..01476e65 --- /dev/null +++ b/packages/better-auth/src/social-providers/gitlab.ts @@ -0,0 +1,124 @@ +import { betterFetch } from "@better-fetch/fetch"; +import type { OAuthProvider, ProviderOptions } from "../oauth2"; +import { createAuthorizationURL, validateAuthorizationCode } from "../oauth2"; + +export interface GitlabProfile extends Record { + id: number; + username: string; + email: string; + name: string; + state: string; + avatar_url: string; + web_url: string; + created_at: string; + bio: string; + location?: string; + public_email: string; + skype: string; + linkedin: string; + twitter: string; + website_url: string; + organization: string; + job_title: string; + pronouns: string; + bot: boolean; + work_information?: string; + followers: number; + following: number; + local_time: string; + last_sign_in_at: string; + confirmed_at: string; + theme_id: number; + last_activity_on: string; + color_scheme_id: number; + projects_limit: number; + current_sign_in_at: string; + identities: Array<{ + provider: string; + extern_uid: string; + }>; + can_create_group: boolean; + can_create_project: boolean; + two_factor_enabled: boolean; + external: boolean; + private_profile: boolean; + commit_email: string; + shared_runners_minutes_limit: number; + extra_shared_runners_minutes_limit: number; +} + +export interface GitlabOptions extends ProviderOptions { + issuer?: string; +} + +const cleanDoubleSlashes = (input: string = "") => { + return input + .split("://") + .map((str) => str.replace(/\/{2,}/g, "/")) + .join("://"); +}; + +const issuerToEndpoints = (issuer?: string) => { + let baseUrl = issuer || "https://gitlab.com"; + return { + authorizationEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/authorize`), + tokenEndpoint: cleanDoubleSlashes(`${baseUrl}/oauth/token`), + userinfoEndpoint: cleanDoubleSlashes(`${baseUrl}/api/v4/user`), + }; +}; + +export const gitlab = (options: GitlabOptions) => { + const { authorizationEndpoint, tokenEndpoint, userinfoEndpoint } = + issuerToEndpoints(options.issuer); + const issuerId = "gitlab"; + const issuerName = "Gitlab"; + return { + id: issuerId, + name: issuerName, + createAuthorizationURL: async ({ + state, + scopes, + codeVerifier, + redirectURI, + }) => { + const _scopes = scopes || ["read_user"]; + options.scope && _scopes.push(...options.scope); + return await createAuthorizationURL({ + id: issuerId, + options, + authorizationEndpoint, + scopes: _scopes, + state, + redirectURI, + codeVerifier, + }); + }, + validateAuthorizationCode: async ({ code, redirectURI }) => { + return validateAuthorizationCode({ + code, + redirectURI: options.redirectURI || redirectURI, + options, + tokenEndpoint, + }); + }, + async getUserInfo(token) { + const { data: profile, error } = await betterFetch( + userinfoEndpoint, + { headers: { authorization: `Bearer ${token.accessToken}` } }, + ); + if (error || profile.state !== "active" || profile.locked) { + return null; + } + return { + user: { + id: profile.id.toString(), + name: profile.name ?? profile.username, + email: profile.email, + image: profile.avatar_url, + emailVerified: true, + }, + data: profile, + }; + }, + } satisfies OAuthProvider; +}; diff --git a/packages/better-auth/src/social-providers/index.ts b/packages/better-auth/src/social-providers/index.ts index 1beaa2b8..b25a8119 100644 --- a/packages/better-auth/src/social-providers/index.ts +++ b/packages/better-auth/src/social-providers/index.ts @@ -10,6 +10,7 @@ import { twitch } from "./twitch"; import { twitter } from "./twitter"; import { dropbox } from "./dropbox"; import { linkedin } from "./linkedin"; +import { gitlab } from "./gitlab"; export const socialProviders = { apple, @@ -23,6 +24,7 @@ export const socialProviders = { twitter, dropbox, linkedin, + gitlab, }; export const socialProviderList = Object.keys(socialProviders) as [ @@ -49,5 +51,6 @@ export * from "./facebook"; export * from "./twitter"; export * from "./dropbox"; export * from "./linkedin"; +export * from "./gitlab"; export type SocialProviderList = typeof socialProviderList;