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: support login & session authentication via OAuth 2.0 (Auth0) #1143

Merged
merged 15 commits into from
Feb 8, 2024
Merged

โœจ feat: support login & session authentication via OAuth 2.0 (Auth0) #1143

merged 15 commits into from
Feb 8, 2024

Conversation

CloudPassenger
Copy link
Contributor

๐Ÿ’ป ๅ˜ๆ›ด็ฑปๅž‹ | Change Type

  • โœจ feat
  • ๐Ÿ› fix
  • โ™ป๏ธ refactor
  • ๐Ÿ’„ style
  • ๐Ÿ”จ chore
  • โšก๏ธ perf
  • ๐Ÿ“ docs

๐Ÿ”€ ๅ˜ๆ›ด่ฏดๆ˜Ž | Description of Change

This Pull Request introduces a new feature that supports login and session authentication using OAuth 2.0 with Auth0 as the provider. The implementation leverages NextAuth.js version 5 to handle authentication both on the server-side (Edge Runtime) and the client-side (Client Components). The current setup allows for a simple OAuth 2.0 authentication flow that is specifically tailored to work with Auth0.

Key changes include:

  • Integration of NextAuth.js for handling OAuth 2.0 authentication.
  • Display of error messages on the chat interface when the user is not logged in.
  • Addition of login, logout, and user information display (currently showing the user's email) at the bottom of the settings page.
    Configuration of the OAuth feature through environment variables AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, and AUTH0_ISSUER.
  • With these changes, users will be able to authenticate securely and seamlessly, enhancing the overall user experience of the application.

feat_oauth_1
feat_oauth_2

๐Ÿ“ ่กฅๅ……ไฟกๆฏ | Additional Information

This Pull Request is a significant step towards implementing robust user authentication within the application. While the current scope is limited to Auth0, the groundwork has been set for potential expansion to support other OAuth providers in the future. The addition of user authentication opens up new possibilities for personalized user experiences and secure access control.

For developers looking to test or deploy this feature, it's essential to configure the necessary environment variables with their Auth0 credentials. Further documentation or guides on setting up and using Auth0 with NextAuth.js might be beneficial for those unfamiliar with the process.

This contribution aims to provide a secure and user-friendly authentication mechanism, and I look forward to feedback and suggestions for improvement.

Copy link

vercel bot commented Jan 24, 2024

@CloudPassenger is attempting to deploy a commit to the LobeHub Team on Vercel.

A member of the Team first needs to authorize it.

@lobehubbot
Copy link
Member

๐Ÿ‘ @CloudPassenger

Thank you for raising your pull request and contributing to our Community
Please make sure you have followed our contributing guidelines. We will review it as soon as possible.
If you encounter any problems, please feel free to connect with us.
้žๅธธๆ„Ÿ่ฐขๆ‚จๆๅ‡บๆ‹‰ๅ–่ฏทๆฑ‚ๅนถไธบๆˆ‘ไปฌ็š„็คพๅŒบๅšๅ‡บ่ดก็Œฎ๏ผŒ่ฏท็กฎไฟๆ‚จๅทฒ็ป้ตๅพชไบ†ๆˆ‘ไปฌ็š„่ดก็ŒฎๆŒ‡ๅ—๏ผŒๆˆ‘ไปฌไผšๅฐฝๅฟซๅฎกๆŸฅๅฎƒใ€‚
ๅฆ‚ๆžœๆ‚จ้‡ๅˆฐไปปไฝ•้—ฎ้ข˜๏ผŒ่ฏท้šๆ—ถไธŽๆˆ‘ไปฌ่”็ณปใ€‚

@arvinxx
Copy link
Contributor

arvinxx commented Jan 24, 2024

It's amazing! Actually we won't plan to support OAuth before ๐Ÿ˜… ( like #331 ใ€#496).

But as you have open a pull request to implement it, I think we can discuss about it.

Let me take a look of your code at first. ๐Ÿ‘

@arvinxx arvinxx changed the title feat: support login & session authentication via OAuth 2.0 (Auth0) โœจ feat: support login & session authentication via OAuth 2.0 (Auth0) Jan 24, 2024
Copy link
Contributor

@arvinxx arvinxx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems not a very heavy task, and the code is clean ๐Ÿ‘

But I request to think of these issues:

  1. By default, we won't want to show the SSO OAuth in the UI. Because our first customers are the C , not the B. So please make a set of ENVs to make this feature optional enabled, and it should be disabled by default.
  2. Please wirite done some doucments about this feature, it should include:
    • Add an guide of how to enable SSO OAuth in the docs/Deployment folder to help self hosting users know how to use the SSO OAuth feature in their companies with Docker or Vercel/zeabur/SealOS.
    • Update the usage of these environment variables to the Environment-Variable and Chinese Version ็Žฏๅขƒๅ˜้‡.
    • Add a develop guide of this feature to introduce how to maintain this feature or to improve it (for example, how it work, how to test and so on ). We need a guide for the community to make this feature more maintainable.
  3. as for the implement, I think the auth of openai/... is not clean as I expect.Maybe there can be a more biz auth function to just wrapper the router function with noting need to change with type or params. Let's take a challange of it.

.eslintrc.js Outdated Show resolved Hide resolved
package.json Outdated Show resolved Hide resolved
src/app/api/openai/chat/route.ts Outdated Show resolved Hide resolved
src/app/api/openai/createBizOpenAI/index.ts Outdated Show resolved Hide resolved
src/features/Conversation/Error/InvalidAccess.tsx Outdated Show resolved Hide resolved
src/app/api/next-auth.ts Outdated Show resolved Hide resolved
Copy link

vercel bot commented Jan 24, 2024

The latest updates on your projects. Learn more about Vercel for Git โ†—๏ธŽ

Name Status Preview Comments Updated (UTC)
lobe-chat โœ… Ready (Inspect) Visit Preview ๐Ÿ’ฌ Add feedback Feb 5, 2024 0:37am

Copy link

codecov bot commented Jan 24, 2024

Codecov Report

Attention: 5 lines in your changes are missing coverage. Please review.

Comparison is base (4b6663b) 86.37% compared to head (604cbd7) 86.35%.
Report is 5 commits behind head on main.

Files Patch % Lines
src/const/fetch.ts 40.00% 3 Missing โš ๏ธ
src/app/api/auth.ts 71.42% 2 Missing โš ๏ธ
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1143      +/-   ##
==========================================
- Coverage   86.37%   86.35%   -0.02%     
==========================================
  Files         214      214              
  Lines       10540    10557      +17     
  Branches     1140     1140              
==========================================
+ Hits         9104     9117      +13     
- Misses       1436     1440       +4     

โ˜” View full report in Codecov by Sentry.
๐Ÿ“ข Have feedback on the report? Share it here.

@CloudPassenger
Copy link
Contributor Author

It seems not a very heavy task, and the code is clean ๐Ÿ‘

But I request to think of these issues:

  1. By default, we won't want to show the SSO OAuth in the UI. Because our first customers are the C , not the B. So please make a set of ENVs to make this feature optional enabled, and it should be disabled by default.

  2. Please wirite done some doucments about this feature, it should include:

    • Add an guide of how to enable SSO OAuth in the docs/Deployment folder to help self hosting users know how to use the SSO OAuth feature in their companies with Docker or Vercel/zeabur/SealOS.
    • Update the usage of these environment variables to the Environment-Variable and Chinese Version ็Žฏๅขƒๅ˜้‡.
    • Add a develop guide of this feature to introduce how to maintain this feature or to improve it (for example, how it work, how to test and so on ). We need a guide for the community to make this feature more maintainable.
  3. as for the implement, I think the auth of openai/... is not clean as I expect.Maybe there can be a more biz auth function to just wrapper the router function with noting need to change with type or params. Let's take a challange of it.

Thank you for your kind review. I will follow the instructions and make changes as soon as possible.

@arvinxx
Copy link
Contributor

arvinxx commented Jan 25, 2024

@CloudPassenger fell free to ask anything about implement~ ๐Ÿ˜

CloudPassenger and others added 2 commits January 25, 2024 12:43
- clean up code under /api/openai
- update middleware.ts to use custom middleware
- clean up unnessary type definitions
@CloudPassenger
Copy link
Contributor Author

Hi, based on your reviews I made some changes and refractor the code

  1. UI: Added a variable to control the display of OAuth-related UI components.
  2. Middleware: Replaced the auth wrapper at the routing level with a custom middleware that adds a custom request header for authentication, aligning with the Access Code authentication pattern. Moved relevant authentication logic into getOpenAIAuthFromRequest and checkAuth functions for better encapsulation.
  3. Code Cleanup: Simplified the next-auth implementation by removing unnecessary types and relocating code to the oauth directory. The reason I chose the beta is that Auth.js was only fully Edge compatible in v5.

Issue:
In the process of refactoring the code, I found a problem: Client-side rendered error dialogs InvalidAccess.tsx cannot access server-side environment variables ๐Ÿ™
And there are also no relevant parameters to pass in the render function. So I'm stuck with a variable exposed to the client: NEXT_PUBLIC_ENABLE_OAUTH to control whether it is displayed or not. There may be a better way to do this, but with fewer changes to the code, this is the only way to go for now.

Upon further code review, I will supplement this PR with the requested documentation, including deployment guides, environment variable usage, and a development guide for maintaining and improving the SSO OAuth feature.

Copy link
Contributor

@arvinxx arvinxx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A more clean implement! ๐Ÿ‘ And I think we can make it better.

As you said, there is some problem with client side/ server side envs.

And we have met simmilar problem as before, and here is my thought:

  1. defined a totally server ENV in the src/config/server.ts like ENABLE_OAUTH_SSO ,
  2. update the code at api/config/route.ts , https://github.com/lobehub/lobe-chat/blob/main/src/app/api/config/route.ts#L9 , this api will send the ENVs from server to client. And we have a request method to get data from server when LobeChat init.
  3. make a selector in here:
const  enabledOAuthSSO =  (s: GlobalStore): boolean => s.serverConfig.enabledOAuthSSO || false;

export const globalSelectors = {
  enabledOAuthSSO
}
  1. and use the selectors to make condition:
const isEnabledOAuth = useGlobalStore(globalSelectors.enabledOAuthSSO)

you can refer to #773 for more example.

src/app/api/oauth/next-auth.ts Outdated Show resolved Hide resolved

// TODO: Verify more auth conditions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's this TODO means ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would have thought that some code could have been added to set user permissions (e.g. only allow certain email suffixes to log in). But after thinking about it, the best solution would be to control organisation permissions on the provider of OAuth 2.0 like Auth0.

src/features/Conversation/Error/InvalidAccess.tsx Outdated Show resolved Hide resolved
src/config/server.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@arvinxx arvinxx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now It's ok for this feature, I think it's good enougth to merge it ๐Ÿ˜„. Please rebase the master to resolve the conflict and then add some documents about it~

src/app/api/oauth/next-auth.ts Outdated Show resolved Hide resolved
src/config/server.ts Outdated Show resolved Hide resolved
src/features/Conversation/Error/InvalidAccess.tsx Outdated Show resolved Hide resolved
@CloudPassenger
Copy link
Contributor Author

Hi,

Sorry to my late reply. I was so busy last week that I didn't follow up on this Pull Request. I saw tons of updated in these few days.

I've updated the code according to your instructions, adapted the new API structure, and written a short note about environment variables.

I hope you can review it again. And wish you a happy Spring Festival!

@arvinxx
Copy link
Contributor

arvinxx commented Feb 5, 2024

@CloudPassenger Good update! And happy Spring Festival!

I think your code is as clean as possible. It's time to step into next part: documents.

Here are three more things to think:

  1. The Env document is OK. There is a small issue need to be discussed: do you think is a good idea to use ENABLE_OAUTH_SSO as the SSO feature flag? or just use !!AUTH0_CLIENT_ID?
  2. I think there should be a guide for the user to enable Auth0 OAuth SSO. (Actually I don't know about this)
  3. There also should be a guide for the developer to know how to debug this feature in dev mode.

docs: Add authentication setup guides for LobeChat
```

Added detailed documentation for setting up the authentication services in LobeChat, with a focus on integrating Auth0. This includes guides for creating an Auth0 application, adding users, and configuring environment variables. Advanced topics cover connecting to existing single sign-on services and setting up social logins. This effort enhances the platform's security and provides clear instructions for enterprise users on authentication procedures.
@CloudPassenger
Copy link
Contributor Author

Hi,

Thank you for your feedback. I wrote the instructions for deployment and I am working in progress for the documents for developers.

I've given your question some serious thought, and I think for now it's better to use the ENABLE_OAUTH_SSO environment variable alone to enable/disable the feature.

While only Auth0 is currently adapted (personally, because it's being used within my organisation), Auth.js does support for use with multiple providers at the same time.

Other developers can easily adapt the single sign-on authentication methods they need, such as enterprise management platforms like Okta, which is not supported by Auth0, based on the capabilities of Auth.js. So they can use different providers for different group of tenants (staff, temporary users, etc.)

Regardless of which provider is used, I think it would be more intuitive to use a single environment variable to enable/disable functionality.

docs: Add authentication integration guide with Auth.js

Adds a comprehensive guide on integrating a new authentication provider
using Auth.js in both English and Chinese documentation. The guide
includes pre-requisites, step-by-step code integration, server
configuration updates, frontend changes, and environment variable setup.
```

The changes introduce a new guide in the documentation for integrating new authentication providers using Auth.js. The guide is provided in both English and Chinese, ensuring broad accessibility. It covers the necessary pre-requisites, detailed instructions for adding the core authentication code, updating server configuration, modifying frontend components, and setting up the required environment variables. This will aid developers in implementing authentication features using Auth.js in the LobeChat application.
@CloudPassenger
Copy link
Contributor Author

The integration guide for developers is updated ๐Ÿš€

Copy link
Contributor

@arvinxx arvinxx left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work! ๐Ÿ‘ I'm glad to merge this PR.

@arvinxx arvinxx merged commit 0609690 into lobehub:main Feb 8, 2024
2 of 5 checks passed
@lobehubbot
Copy link
Member

โค๏ธ Great PR @CloudPassenger โค๏ธ

The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our discord and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.
้กน็›ฎ็š„ๆˆ้•ฟ็ฆปไธๅผ€็”จๆˆทๅ้ฆˆๅ’Œ่ดก็Œฎ๏ผŒๆ„Ÿ่ฐขๆ‚จ็š„่ดก็Œฎ! ๅฆ‚ๆžœๆ‚จๅฏน LobeHub ๅผ€ๅ‘่€…็คพๅŒบๆ„Ÿๅ…ด่ถฃ๏ผŒ่ฏทๅŠ ๅ…ฅๆˆ‘ไปฌ็š„ discord๏ผŒ็„ถๅŽ็งไฟก @arvinxx ๆˆ– @canisminor1990ใ€‚ไป–ไปฌไผš้‚€่ฏทๆ‚จๅŠ ๅ…ฅๆˆ‘ไปฌ็š„็งๅฏ†ๅผ€ๅ‘่€…้ข‘้“ใ€‚ๆˆ‘ไปฌๅฐ†ไผš่ฎจ่ฎบๅ…ณไบŽ Lobe Chat ็š„ๅผ€ๅ‘๏ผŒๅˆ†ไบซๅ’Œ่ฎจ่ฎบๅ…จ็ƒ่Œƒๅ›ดๅ†…็š„ AI ๆถˆๆฏใ€‚

github-actions bot pushed a commit that referenced this pull request Feb 8, 2024
## [Version 0.125.0](v0.124.3...v0.125.0)
<sup>Released on **2024-02-08**</sup>

#### โœจ Features

- **misc**: Support login & session authentication via OAuth 2.0 (Auth0).

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### What's improved

* **misc**: Support login & session authentication via OAuth 2.0 (Auth0), closes [#1143](#1143) ([0609690](0609690))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
@lobehubbot
Copy link
Member

๐ŸŽ‰ This PR is included in version 0.125.0 ๐ŸŽ‰

The release is available on:

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€

github-actions bot pushed a commit to bentwnghk/lobe-chat that referenced this pull request Feb 8, 2024
## [Version&nbsp;1.7.0](v1.6.1...v1.7.0)
<sup>Released on **2024-02-08**</sup>

#### โœจ Features

- **misc**: Support login & session authentication via OAuth 2.0 (Auth0).

#### ๐Ÿ› Bug Fixes

- **misc**: Fix OAuthForm.tsx.

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### What's improved

* **misc**: Support login & session authentication via OAuth 2.0 (Auth0), closes [lobehub#1143](https://github.com/bentwnghk/lobe-chat/issues/1143) ([0609690](0609690))

#### What's fixed

* **misc**: Fix OAuthForm.tsx ([a1edfdd](a1edfdd))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
@arvinxx arvinxx mentioned this pull request Apr 1, 2024
7 tasks
miroshar-success added a commit to miroshar-success/OpenAI_Integraion_platform that referenced this pull request Apr 5, 2024
## [Version&nbsp;0.125.0](lobehub/lobe-chat@v0.124.3...v0.125.0)
<sup>Released on **2024-02-08**</sup>

#### โœจ Features

- **misc**: Support login & session authentication via OAuth 2.0 (Auth0).

<br/>

<details>
<summary><kbd>Improvements and Fixes</kbd></summary>

#### What's improved

* **misc**: Support login & session authentication via OAuth 2.0 (Auth0), closes [#1143](lobehub/lobe-chat#1143) ([0609690](lobehub/lobe-chat@0609690))

</details>

<div align="right">

[![](https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square)](#readme-top)

</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants