mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-09-21 21:50:49 +02:00
feat: Auth and User System (#205)
* server-side JWT auth implementation * move oauth routes and strategies, fix bugs * backend modifications for wiring up the frontend login and reg forms * Add frontend data services for login and registration * Add login and registration forms * Implment auth context, functional client side auth * protect routes with jwt auth * finish local strategy (using local storage) * Start setting up google auth * disable token refresh, remove old auth middleware * refactor client, add ApiErrorBoundary context * disable google and facebook strategies * fix: fix presets not displaying specific to user * fix: fix issue with browser refresh * fix: casing issue with User.js (#11) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * fix: issue with api error watcher (#12) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * feat: add google auth social login * fix: make google login url dynamic based on dev/prod * fix: bug where UI is briefly displayed before redirecting to login * fix: fix cookie expires value for local auth * Update README.md * Update LOCAL_INSTALL structure * Add local testing instructions * Only load google strategy if client id and secret are provided * Update .env.example files with new params * fix issue with not redirecting to register form * only show google login button if value is set in .env * cleanup log messages * Add label to button for google login on login form * doc: fix client/server url values in .env.example * feat: add error message details to registration failure * Restore preventing paste on confirm password * auto-login user after registering * feat: forgot password (#24) * make login/reg pages look like openai's * add password reset data services * new form designs similar to openai, add password reset pages * add api's for password reset * email utils for password reset * remove bcrypt salt rounds from process.env * refactor: restructure api auth code, consolidate routes (#25) * add api's for password reset * remove bcrypt salt rounds from process.env * refactor: consolidate auth routes, use controller pattern * refactor: code cleanup * feat: migrate data to first user (#26) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes after refactor (#27) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: issue with auto-login when logging out then logging in with new browser window (#28) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: Update README and .env.example files with user system information (#29) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: update README and .env.example files * Fixup: LOCAL_INSTALL.md PS instructions (#200) (#30) Co-authored-by: alfredo-f <alfredo.fomitchenko@mail.polimi.it> * feat: send user with completion to protect against abuse (#31) * Fixup: LOCAL_INSTALL.md PS instructions (#200) * server-side JWT auth implementation * move oauth routes and strategies, fix bugs * backend modifications for wiring up the frontend login and reg forms * Add frontend data services for login and registration * Add login and registration forms * Implment auth context, functional client side auth * protect routes with jwt auth * finish local strategy (using local storage) * Start setting up google auth * disable token refresh, remove old auth middleware * refactor client, add ApiErrorBoundary context * disable google and facebook strategies * fix: fix presets not displaying specific to user * fix: fix issue with browser refresh * fix: casing issue with User.js (#11) * delete user.js to be renamed * fix: fix casing issue with User.js * comment out api error watcher temporarily * feat: add google auth social login * fix: make google login url dynamic based on dev/prod * fix: bug where UI is briefly displayed before redirecting to login * fix: fix cookie expires value for local auth * Only load google strategy if client id and secret are provided * Update .env.example files with new params * fix issue with not redirecting to register form * only show google login button if value is set in .env * cleanup log messages * Add label to button for google login on login form * doc: fix client/server url values in .env.example * feat: add error message details to registration failure * Restore preventing paste on confirm password * auto-login user after registering * feat: forgot password (#24) * make login/reg pages look like openai's * add password reset data services * new form designs similar to openai, add password reset pages * add api's for password reset * email utils for password reset * remove bcrypt salt rounds from process.env * refactor: restructure api auth code, consolidate routes (#25) * add api's for password reset * remove bcrypt salt rounds from process.env * refactor: consolidate auth routes, use controller pattern * refactor: code cleanup * feat: migrate data to first user (#26) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes after refactor (#27) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: issue with auto-login when logging out then logging in with new browser window (#28) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: Update README and .env.example files with user system information (#29) * refactor: use /api for auth routes * fix: use user id instead of username * feat: migrate data to first user on register * fix: fix social login routes * fix: fix issue with auto-login in new tab * doc: update README and .env.example files * Send user id to openai to protect against abuse * add meilisearch to gitignore * Remove webpack --------- Co-authored-by: alfredo-f <alfredo.fomitchenko@mail.polimi.it> --------- Co-authored-by: Danny Avila <110412045+danny-avila@users.noreply.github.com> Co-authored-by: Alfredo Fomitchenko <alfredo.fomitchenko@mail.polimi.it>
This commit is contained in:
parent
65543eb084
commit
dac19038a3
68 changed files with 3968 additions and 3394 deletions
7
.gitignore
vendored
7
.gitignore
vendored
|
@ -57,4 +57,9 @@ src/style - official.css
|
|||
/e2e/specs/.test-results/
|
||||
/e2e/playwright-report/
|
||||
/playwright/.cache/
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
|
||||
# meilisearch
|
||||
meilisearch
|
||||
data.ms/*
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ RUN npm ci
|
|||
COPY /client/ /client/
|
||||
# Set the memory limit for Node.js
|
||||
ENV NODE_OPTIONS="--max-old-space-size=2048"
|
||||
# Build webpack artifacts
|
||||
# Build artifacts
|
||||
RUN npm run build
|
||||
|
||||
FROM node:19-alpine AS node-api
|
||||
|
|
|
@ -18,7 +18,7 @@ COPY /api/ /app/api/
|
|||
# Set the memory limit for Node.js
|
||||
ENV NODE_OPTIONS="--max-old-space-size=2048"
|
||||
|
||||
# Build webpack artifacts for the client
|
||||
# Build artifacts for the client
|
||||
RUN cd /app/client && npm run build
|
||||
|
||||
# Create the necessary directory and copy the client side code to the api directory
|
||||
|
|
51
README.md
51
README.md
|
@ -149,10 +149,6 @@ Currently, this project is only functional with the `text-davinci-003` model.
|
|||
</details>
|
||||
|
||||
# Table of Contents
|
||||
- [ChatGPT Clone](#chatgpt-clone)
|
||||
- [All AI Conversations under One Roof.](#all-ai-conversations-under-one-roof)
|
||||
- [Features](#features)
|
||||
- [Updates](#updates)
|
||||
- [Table of Contents](#table-of-contents)
|
||||
- [Roadmap](#roadmap)
|
||||
- [Tech Stack](#tech-stack)
|
||||
|
@ -160,10 +156,12 @@ Currently, this project is only functional with the `text-davinci-003` model.
|
|||
- [Prerequisites](#prerequisites)
|
||||
- [Usage](#usage)
|
||||
- [Local](#local)
|
||||
- [**Automated Installer (Windows)**](#automated-installer-windows)
|
||||
- [**In-Depth Instructions**](#in-depth-instructions)
|
||||
- [Docker](#docker)
|
||||
- [Access Tokens](#access-tokens)
|
||||
- [Proxy](#proxy)
|
||||
- [User System](#user-system)
|
||||
- [User/Auth System](#userauth-system)
|
||||
- [Updating](#updating)
|
||||
- [Use Cases](#use-cases)
|
||||
- [Origin](#origin)
|
||||
|
@ -310,45 +308,30 @@ set in docker-compose.yml file, under services - api - environment
|
|||
|
||||
</details>
|
||||
|
||||
### User System
|
||||
### User/Auth System
|
||||
|
||||
By default, there is no user system enabled, so anyone can access your server.
|
||||
**First Time Setup**
|
||||
([danorlando](https://github.com/danorlando)) The first time you run the application, you should register a new account by clicking the "Sign up" link on the login page. The first account registered will be recieve an admin role. The admin account does not currently have extended functionality, but is valuable should you choose to create an admin dashboard for user management.
|
||||
|
||||
**This project is not designed to provide a complete and full-featured user system.** It's not high priority task and might never be provided.
|
||||
**Migrating Previous Conversations and Presets to new User Account**
|
||||
When the first account is registered, the application will automatically migrate any conversations and presets that you created before the user system was implemented to that account.
|
||||
|
||||
[wtlyu](https://github.com/wtlyu) provide a sample user system structure, that you can implement your own user system. It's simple and not a ready-for-use edition.
|
||||
IMPORTANT: if you use login for the first time with a social login account (eg. Google, facebook, etc.), the conversations and presets that you created before the user system was implemented will NOT be migrated to that account. You should register and login with a local account (email and password) for the first time.
|
||||
|
||||
(If you want to implement your user system, open this ↓)
|
||||
**OAuth2/Social Login**
|
||||
The application is setup to support OAuth2/Social Login with Google. All of the code is in place for Facebook login as well, but this has not been tested because the setup process with Facebook was honestly just too painful for me to deal with. I plan to add support for other OAuth2 providers including Github and Discord at a later time.
|
||||
|
||||
<details>
|
||||
<summary><strong>Implement your own user system </strong></summary>
|
||||
To enable Google login, you must create an application in the [Google Cloud Console](https://cloud.google.com) and provide the client ID and client secret in the [/api/.env](https://github.com/danny-avila/chatgpt-clone/blob/main/api/.env.example) file, then set `VITE_SHOW_GOOGLE_LOGIN_OPTION=true` in the [/client/.env](https://github.com/danny-avila/chatgpt-clone/blob/main/client/.env.example) file.
|
||||
|
||||
To enable the user system, set `ENABLE_USER_SYSTEM=1` in your `.env` file.
|
||||
|
||||
The sample structure is simple. It provide three basic endpoint:
|
||||
|
||||
1. `/auth/login` will redirect to your own login url. In the sample code, it's `/auth/your_login_page`.
|
||||
2. `/auth/logout` will redirect to your own logout url. In the sample code, it's `/auth/your_login_page/logout`.
|
||||
3. `/api/me` will return the userinfo: `{ username, display }`.
|
||||
1. `username` will be used in db, used to distinguish between users.
|
||||
2. `display` will be displayed in UI.
|
||||
|
||||
The only one thing that drive user system work is `req.session.user`. Once it's set, the client will be trusted. Set to `null` if logout.
|
||||
|
||||
Please refer to `/api/server/routes/authYourLogin.js` file. It's very clear and simple to tell you how to implement your user system.
|
||||
|
||||
Or you can ask chatGPT to write the code for you, here is one example to connect LDAP:
|
||||
|
||||
```
|
||||
Please write me an express module, that serve the login and logout endpoint as a router. The login and logout uri is '/' and '/logout'. Once loginned, save display name and username in session.user, as {display, username}. Then redirect to '/'. Please write the code using express and other lib, and storage any server configuration in a config variable. I want the user to be connected to my LDAP server.
|
||||
```
|
||||
|
||||
</details>
|
||||
**Email and Password Reset**
|
||||
Most of the code is in place for sending password reset emails, but is not yet feature-complete as I have not setup an email server to test it. Currently, submitting a password reset request will then display a link with the one-time reset token that can then be used to reset the password. Understanding that this is a considerable security hazard, email integration will be included in the next release.
|
||||
|
||||
***Warning***
|
||||
If you previously implemented your own user system using the original scaffolding that was provided, you will no longer see conversations and presets by switching to the new user system. This is because of a design flaw in the scaffolding implementation that was problematic for the inclusion of social login.
|
||||
|
||||
### Updating
|
||||
|
||||
- As the project is still a work-in-progress, you should pull the latest and run the steps over. Reset your browser cache/clear site data.
|
||||
- As the project is still a work-in-progress, you should pull the latest and run the steps over. Reset your browser cache/clear cookies and site data.
|
||||
|
||||
## Use Cases ##
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
##########################
|
||||
# Server configuration.
|
||||
# Server configuration:
|
||||
##########################
|
||||
|
||||
# The server will listen to localhost:3080 by default. You can change the target IP as you want.
|
||||
|
@ -7,15 +7,16 @@
|
|||
# or expose this from a Docker container, set host to 0.0.0.0 or your external IP interface.
|
||||
# Tips: Setting host to 0.0.0.0 means listening on all interfaces. It's not a real IP.
|
||||
# Use localhost:port rather than 0.0.0.0:port to access the server.
|
||||
# Set Node env to development if running in dev mode.
|
||||
HOST=localhost
|
||||
PORT=3080
|
||||
NODE_ENV=development
|
||||
NODE_ENV=production
|
||||
|
||||
# Change this to proxy any API request.
|
||||
# It's useful if your machine has difficulty calling the original API server.
|
||||
# PROXY=
|
||||
|
||||
# Change this to your MongoDB URI if different and I recommend appending chatgpt-clone
|
||||
# Change this to your MongoDB URI if different. I recommend appending chatgpt-clone.
|
||||
MONGO_URI=mongodb://127.0.0.1:27017/chatgpt-clone
|
||||
|
||||
##########################
|
||||
|
@ -44,7 +45,7 @@ OPENAI_MODELS=gpt-3.5-turbo,gpt-3.5-turbo-0301,text-davinci-003,gpt-4
|
|||
# BingAI Tokens: the "_U" cookies value from bing.com
|
||||
# Set to "user_provided" to allow the user to provide its token from the UI.
|
||||
# Leave it blank to disable this endpoint.
|
||||
BINGAI_TOKEN=user_provided
|
||||
BINGAI_TOKEN="user_provided"
|
||||
|
||||
# BingAI Host:
|
||||
# Necessary for some people in different countries, e.g. China (https://cn.bing.com)
|
||||
|
@ -60,7 +61,7 @@ BINGAI_TOKEN=user_provided
|
|||
# Exposes your access token to `CHATGPT_REVERSE_PROXY`
|
||||
# Set to "user_provided" to allow the user to provide its token from the UI.
|
||||
# Leave it blank to disable this endpoint
|
||||
CHATGPT_TOKEN=user_provided
|
||||
CHATGPT_TOKEN="user_provided"
|
||||
|
||||
# Identify the available models, separated by commas. The first will be default.
|
||||
# Leave it blank to use internal settings.
|
||||
|
@ -78,7 +79,7 @@ CHATGPT_MODELS=text-davinci-002-render-sha,text-davinci-002-render-paid,gpt-4
|
|||
# ENABLING SEARCH MESSAGES/CONVOS
|
||||
# Requires the installation of the free self-hosted Meilisearch or a paid Remote Plan (Remote not tested)
|
||||
# The easiest setup for this is through docker-compose, which takes care of it for you.
|
||||
SEARCH=TRUE
|
||||
SEARCH=false
|
||||
|
||||
# REQUIRED FOR SEARCH: MeiliSearch Host, mainly for the API server to connect to the search server.
|
||||
# Replace '0.0.0.0' with 'meilisearch' if serving MeiliSearch with docker-compose.
|
||||
|
@ -94,14 +95,35 @@ MEILI_HTTP_ADDR=0.0.0.0:7700
|
|||
# or if it is under 16 bytes. MeiliSearch will suggest a secure autogenerated master key.
|
||||
# Using docker, it seems recognized as production so use a secure key.
|
||||
# This is a ready made secure key for docker-compose, you can replace it with your own.
|
||||
MEILI_MASTER_KEY=JKMW-hGc7v_D1FkJVdbRSDNFLZcUv3S75yrxXP0SmcU
|
||||
MEILI_MASTER_KEY=DrhYf7zENyR6AlUCKmnz0eYASOQdl6zxH7s7MKFSfFCt
|
||||
|
||||
##########################
|
||||
# User System
|
||||
# User System:
|
||||
##########################
|
||||
|
||||
# ENABLING THE USER SYSTEM
|
||||
# This is not a ready to use user system.
|
||||
# Don't use it, unless you can write your own code.
|
||||
# Do not uncomment this unless you implemented your own user system
|
||||
# ENABLE_USER_SYSTEM=
|
||||
# Google:
|
||||
# Add your Google Client ID and Secret here, you must register an app with Google Cloud to get these values
|
||||
# https://cloud.google.com/
|
||||
GOOGLE_CLIENT_ID=
|
||||
GOOGLE_CLIENT_SECRET=
|
||||
GOOGLE_CALLBACK_URL=/oauth/google/callback
|
||||
|
||||
#JWT:
|
||||
JWT_SECRET_DEV=secret
|
||||
|
||||
# Add a secure secret for production if deploying to live domain.
|
||||
JWT_SECRET_PROD=secret
|
||||
|
||||
# Set the expiration delay for the secure cookie with the JWT token
|
||||
# Delay is in millisecond e.g. 7 days is 1000*60*60*24*7
|
||||
SESSION_EXPIRY=1000 * 60 * 60 * 24 * 7
|
||||
|
||||
# Site URLs:
|
||||
# Don't forget to set Node env to development in the Server configuration section above
|
||||
# if you want to run in dev mode
|
||||
CLIENT_URL_DEV=http://localhost:3090
|
||||
SERVER_URL_DEV=http://localhost:3080
|
||||
|
||||
# Change these values to domain if deploying:
|
||||
CLIENT_URL_PROD=http://localhost:3080
|
||||
SERVER_URL_PROD=http://localhost:3080
|
||||
|
|
|
@ -8,7 +8,8 @@ const browserClient = async ({
|
|||
model,
|
||||
token,
|
||||
onProgress,
|
||||
abortController
|
||||
abortController,
|
||||
userId
|
||||
}) => {
|
||||
const { ChatGPTBrowserClient } = await import('@waylaidwanderer/chatgpt-api');
|
||||
const store = {
|
||||
|
@ -21,8 +22,9 @@ const browserClient = async ({
|
|||
// Access token from https://chat.openai.com/api/auth/session
|
||||
accessToken: process.env.CHATGPT_TOKEN == 'user_provided' ? token : process.env.CHATGPT_TOKEN ?? null,
|
||||
model: model,
|
||||
// debug: true
|
||||
proxy: process.env.PROXY || null
|
||||
debug: false,
|
||||
proxy: process.env.PROXY || null,
|
||||
user: userId
|
||||
};
|
||||
|
||||
const client = new ChatGPTBrowserClient(clientOptions, store);
|
||||
|
|
|
@ -14,7 +14,8 @@ const askClient = async ({
|
|||
presence_penalty,
|
||||
frequency_penalty,
|
||||
onProgress,
|
||||
abortController
|
||||
abortController,
|
||||
userId
|
||||
}) => {
|
||||
const ChatGPTClient = (await import('@waylaidwanderer/chatgpt-api')).default;
|
||||
const store = {
|
||||
|
@ -36,7 +37,8 @@ const askClient = async ({
|
|||
chatGptLabel,
|
||||
promptPrefix,
|
||||
proxy: process.env.PROXY || null,
|
||||
debug: false
|
||||
debug: false,
|
||||
user: userId
|
||||
};
|
||||
|
||||
const client = new ChatGPTClient(process.env.OPENAI_KEY, clientOptions, store);
|
||||
|
|
5
api/middleware/requireJwtAuth.js
Normal file
5
api/middleware/requireJwtAuth.js
Normal file
|
@ -0,0 +1,5 @@
|
|||
const passport = require('passport');
|
||||
|
||||
const requireJwtAuth = passport.authenticate('jwt', { session: false });
|
||||
|
||||
module.exports = requireJwtAuth;
|
31
api/middleware/requireLocalAuth.js
Normal file
31
api/middleware/requireLocalAuth.js
Normal file
|
@ -0,0 +1,31 @@
|
|||
const passport = require('passport');
|
||||
const DebugControl = require('../utils/debug.js');
|
||||
|
||||
function log({ title, parameters }) {
|
||||
DebugControl.log.functionName(title);
|
||||
if (parameters) {
|
||||
DebugControl.log.parameters(parameters);
|
||||
}
|
||||
}
|
||||
|
||||
const requireLocalAuth = (req, res, next) => {
|
||||
passport.authenticate('local', (err, user, info) => {
|
||||
if (err) {
|
||||
log({
|
||||
title: '(requireLocalAuth) Error at passport.authenticate',
|
||||
parameters: [{ name: 'error', value: err }]
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
if (!user) {
|
||||
log({
|
||||
title: '(requireLocalAuth) Error: No user',
|
||||
});
|
||||
return res.status(422).send(info);
|
||||
}
|
||||
req.user = user;
|
||||
next();
|
||||
})(req, res, next);
|
||||
};
|
||||
|
||||
module.exports = requireLocalAuth;
|
|
@ -3,6 +3,7 @@ const Conversation = require('./schema/convoSchema');
|
|||
const { getMessages, deleteMessages } = require('./Message');
|
||||
|
||||
const getConvo = async (user, conversationId) => {
|
||||
console.log('getConvo -> userId', user);
|
||||
try {
|
||||
return await Conversation.findOne({ user, conversationId }).exec();
|
||||
} catch (error) {
|
||||
|
@ -39,7 +40,6 @@ module.exports = {
|
|||
.skip((pageNumber - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.exec();
|
||||
|
||||
return { conversations: convos, pages: totalPages, pageNumber, pageSize };
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
|
|
177
api/models/User.js
Normal file
177
api/models/User.js
Normal file
|
@ -0,0 +1,177 @@
|
|||
const mongoose = require('mongoose');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const Joi = require('joi');
|
||||
const DebugControl = require('../utils/debug.js');
|
||||
|
||||
function log({ title, parameters }) {
|
||||
DebugControl.log.functionName(title);
|
||||
DebugControl.log.parameters(parameters);
|
||||
}
|
||||
|
||||
const Session = mongoose.Schema({
|
||||
refreshToken: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
});
|
||||
|
||||
const userSchema = mongoose.Schema(
|
||||
{
|
||||
name: {
|
||||
type: String
|
||||
},
|
||||
username: {
|
||||
type: String,
|
||||
lowercase: true,
|
||||
required: [true, "can't be blank"],
|
||||
match: [/^[a-zA-Z0-9_]+$/, 'is invalid'],
|
||||
index: true
|
||||
},
|
||||
email: {
|
||||
type: String,
|
||||
required: [true, "can't be blank"],
|
||||
lowercase: true,
|
||||
unique: true,
|
||||
match: [/\S+@\S+\.\S+/, 'is invalid'],
|
||||
index: true
|
||||
},
|
||||
emailVerified: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
default: false
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
trim: true,
|
||||
minlength: 8,
|
||||
maxlength: 60
|
||||
},
|
||||
avatar: {
|
||||
type: String,
|
||||
required: false
|
||||
},
|
||||
provider: {
|
||||
type: String,
|
||||
required: true,
|
||||
default: 'local'
|
||||
},
|
||||
role: {
|
||||
type: String,
|
||||
default: 'USER'
|
||||
},
|
||||
googleId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true
|
||||
},
|
||||
facebookId: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true
|
||||
},
|
||||
refreshToken: {
|
||||
type: [Session]
|
||||
}
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
//Remove refreshToken from the response
|
||||
userSchema.set('toJSON', {
|
||||
transform: function (doc, ret, options) {
|
||||
delete ret.refreshToken;
|
||||
return ret;
|
||||
}
|
||||
});
|
||||
|
||||
userSchema.methods.toJSON = function () {
|
||||
return {
|
||||
id: this._id,
|
||||
provider: this.provider,
|
||||
email: this.email,
|
||||
name: this.name,
|
||||
username: this.username,
|
||||
avatar: this.avatar,
|
||||
role: this.role,
|
||||
emailVerified: this.emailVerified,
|
||||
createdAt: this.createdAt,
|
||||
updatedAt: this.updatedAt
|
||||
};
|
||||
};
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const secretOrKey = isProduction ? process.env.JWT_SECRET_PROD : process.env.JWT_SECRET_DEV;
|
||||
const refreshSecret = isProduction
|
||||
? process.env.REFRESH_TOKEN_SECRET_PROD
|
||||
: process.env.REFRESH_TOKEN_SECRET_DEV;
|
||||
|
||||
userSchema.methods.generateToken = function () {
|
||||
const token = jwt.sign(
|
||||
{
|
||||
id: this._id,
|
||||
username: this.username,
|
||||
provider: this.provider,
|
||||
email: this.email
|
||||
},
|
||||
secretOrKey,
|
||||
{ expiresIn: eval(process.env.SESSION_EXPIRY) }
|
||||
);
|
||||
return token;
|
||||
};
|
||||
|
||||
userSchema.methods.generateRefreshToken = function () {
|
||||
const refreshToken = jwt.sign(
|
||||
{
|
||||
id: this._id,
|
||||
username: this.username,
|
||||
provider: this.provider,
|
||||
email: this.email
|
||||
},
|
||||
refreshSecret,
|
||||
{ expiresIn: eval(process.env.REFRESH_TOKEN_EXPIRY) }
|
||||
);
|
||||
return refreshToken;
|
||||
};
|
||||
|
||||
userSchema.methods.comparePassword = function (candidatePassword, callback) {
|
||||
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
|
||||
if (err) return callback(err);
|
||||
callback(null, isMatch);
|
||||
});
|
||||
};
|
||||
|
||||
module.exports.hashPassword = async (password) => {
|
||||
|
||||
const hashedPassword = await new Promise((resolve, reject) => {
|
||||
bcrypt.hash(password, 10, function (err, hash) {
|
||||
if (err) reject(err);
|
||||
else resolve(hash);
|
||||
});
|
||||
});
|
||||
|
||||
return hashedPassword;
|
||||
};
|
||||
|
||||
module.exports.validateUser = (user) => {
|
||||
log({
|
||||
title: 'Validate User',
|
||||
parameters: [{ name: 'Validate User', value: user }]
|
||||
});
|
||||
const schema = {
|
||||
avatar: Joi.any(),
|
||||
name: Joi.string().min(2).max(80).required(),
|
||||
username: Joi.string()
|
||||
.min(2)
|
||||
.max(80)
|
||||
.regex(/^[a-zA-Z0-9_]+$/)
|
||||
.required(),
|
||||
password: Joi.string().min(8).max(60).allow('').allow(null)
|
||||
};
|
||||
|
||||
return Joi.validate(user, schema);
|
||||
};
|
||||
|
||||
const User = mongoose.model('User', userSchema);
|
||||
|
||||
module.exports = User;
|
22
api/models/schema/tokenSchema.js
Normal file
22
api/models/schema/tokenSchema.js
Normal file
|
@ -0,0 +1,22 @@
|
|||
const mongoose = require("mongoose");
|
||||
const Schema = mongoose.Schema;
|
||||
|
||||
const tokenSchema = new Schema({
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
required: true,
|
||||
ref: "user",
|
||||
},
|
||||
token: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
createdAt: {
|
||||
type: Date,
|
||||
required: true,
|
||||
default: Date.now,
|
||||
expires: 900,
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = mongoose.model("Token", tokenSchema);
|
1199
api/package-lock.json
generated
1199
api/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -23,19 +23,32 @@
|
|||
"@keyv/mongo": "^2.1.8",
|
||||
"@waylaidwanderer/chatgpt-api": "^1.35.0",
|
||||
"axios": "^1.3.4",
|
||||
"bcrypt": "^5.1.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cookie": "^0.5.0",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"cors": "^2.8.5",
|
||||
"crypto": "^1.0.1",
|
||||
"dotenv": "^16.0.3",
|
||||
"eslint": "^8.36.0",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.17.3",
|
||||
"handlebars": "^4.7.7",
|
||||
"html": "^1.0.0",
|
||||
"joi": "^14.3.1",
|
||||
"jsonwebtoken": "^9.0.0",
|
||||
"keyv": "^4.5.2",
|
||||
"keyv-file": "^0.2.0",
|
||||
"lodash": "^4.17.21",
|
||||
"meilisearch": "^0.31.1",
|
||||
"mongoose": "^6.9.0",
|
||||
"nodemailer": "^6.9.1",
|
||||
"openai": "^3.1.0",
|
||||
"passport": "^0.6.0",
|
||||
"passport-facebook": "^3.0.0",
|
||||
"passport-github": "^1.1.0",
|
||||
"passport-google-oauth20": "^2.0.0",
|
||||
"passport-jwt": "^4.0.1",
|
||||
"passport-local": "^1.0.0",
|
||||
"sanitize": "^2.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
180
api/server/controllers/auth.controller.js
Normal file
180
api/server/controllers/auth.controller.js
Normal file
|
@ -0,0 +1,180 @@
|
|||
const {
|
||||
loginUser,
|
||||
logoutUser,
|
||||
registerUser,
|
||||
requestPasswordReset,
|
||||
resetPassword,
|
||||
} = require("../services/auth.service");
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
const loginController = async (req, res) => {
|
||||
try {
|
||||
const token = req.user.generateToken();
|
||||
const user = await loginUser(req.user)
|
||||
if(user) {
|
||||
res.cookie('token', token, {
|
||||
expires: new Date(Date.now() + eval(process.env.SESSION_EXPIRY)),
|
||||
httpOnly: false,
|
||||
secure: isProduction
|
||||
});
|
||||
res.status(200).send({ token, user });
|
||||
}
|
||||
else {
|
||||
return res.status(400).json({ message: 'Invalid credentials' });
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.log(err);
|
||||
return res.status(500).json({ message: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const logoutController = async (req, res) => {
|
||||
const { signedCookies = {} } = req;
|
||||
const { refreshToken } = signedCookies;
|
||||
try {
|
||||
const logout = await logoutUser(req.user, refreshToken);
|
||||
console.log(logout)
|
||||
const { status, message } = logout;
|
||||
if (status === 200) {
|
||||
res.clearCookie('token');
|
||||
res.clearCookie('refreshToken');
|
||||
res.status(status).send({ message });
|
||||
}
|
||||
else {
|
||||
res.status(status).send({ message });
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.log(err);
|
||||
return res.status(500).json({ message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
const registrationController = async (req, res) => {
|
||||
try {
|
||||
const response = await registerUser(req.body);
|
||||
if (response.status === 200) {
|
||||
const { status, user } = response;
|
||||
const token = user.generateToken();
|
||||
//send token for automatic login
|
||||
res.cookie('token', token, {
|
||||
expires: new Date(Date.now() + eval(process.env.SESSION_EXPIRY)),
|
||||
httpOnly: false,
|
||||
secure: isProduction
|
||||
});
|
||||
res.status(status).send({ user });
|
||||
}
|
||||
else {
|
||||
const { status, message } = response;
|
||||
res.status(status).send({ message });
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
console.log(err);
|
||||
return res.status(500).json({ message: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const getUserController = async (req, res) => {
|
||||
return res.status(200).send(req.user);
|
||||
};
|
||||
|
||||
const resetPasswordRequestController = async (req, res) => {
|
||||
try {
|
||||
const resetService = await requestPasswordReset(
|
||||
req.body.email
|
||||
);
|
||||
if (resetService.link) {
|
||||
return res.status(200).json(resetService);
|
||||
}
|
||||
else {
|
||||
return res.status(400).json(resetService);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
return res.status(400).json({ message: e.message });
|
||||
}
|
||||
};
|
||||
|
||||
const resetPasswordController = async (req, res) => {
|
||||
try {
|
||||
const resetPasswordService = await resetPassword(
|
||||
req.body.userId,
|
||||
req.body.token,
|
||||
req.body.password
|
||||
);
|
||||
if(resetPasswordService instanceof Error) {
|
||||
return res.status(400).json(resetPasswordService);
|
||||
}
|
||||
else {
|
||||
return res.status(200).json(resetPasswordService);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.log(e);
|
||||
return res.status(400).json({ message: e.message });
|
||||
}
|
||||
};
|
||||
|
||||
const refreshController = async (req, res, next) => {
|
||||
const { signedCookies = {} } = req;
|
||||
const { refreshToken } = signedCookies;
|
||||
//TODO
|
||||
// if (refreshToken) {
|
||||
// try {
|
||||
// const payload = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET);
|
||||
// const userId = payload._id;
|
||||
// User.findOne({ _id: userId }).then(
|
||||
// (user) => {
|
||||
// if (user) {
|
||||
// // Find the refresh token against the user record in database
|
||||
// const tokenIndex = user.refreshToken.findIndex(item => item.refreshToken === refreshToken);
|
||||
|
||||
// if (tokenIndex === -1) {
|
||||
// res.statusCode = 401;
|
||||
// res.send('Unauthorized');
|
||||
// } else {
|
||||
// const token = req.user.generateToken();
|
||||
// // If the refresh token exists, then create new one and replace it.
|
||||
// const newRefreshToken = req.user.generateRefreshToken();
|
||||
// user.refreshToken[tokenIndex] = { refreshToken: newRefreshToken };
|
||||
// user.save((err) => {
|
||||
// if (err) {
|
||||
// res.statusCode = 500;
|
||||
// res.send(err);
|
||||
// } else {
|
||||
// // setTokenCookie(res, newRefreshToken);
|
||||
// const user = req.user.toJSON();
|
||||
// res.status(200).send({ token, user });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// } else {
|
||||
// res.statusCode = 401;
|
||||
// res.send('Unauthorized');
|
||||
// }
|
||||
// },
|
||||
// err => next(err)
|
||||
// );
|
||||
// } catch (err) {
|
||||
// res.statusCode = 401;
|
||||
// res.send('Unauthorized');
|
||||
// }
|
||||
// } else {
|
||||
// res.statusCode = 401;
|
||||
// res.send('Unauthorized');
|
||||
// }
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getUserController,
|
||||
loginController,
|
||||
logoutController,
|
||||
refreshController,
|
||||
registrationController,
|
||||
resetPasswordRequestController,
|
||||
resetPasswordController,
|
||||
};
|
|
@ -1,12 +1,12 @@
|
|||
const express = require('express');
|
||||
const session = require('express-session');
|
||||
const connectDb = require('../lib/db/connectDb');
|
||||
const migrateDb = require('../lib/db/migrateDb');
|
||||
const indexSync = require('../lib/db/indexSync');
|
||||
const path = require('path');
|
||||
const cors = require('cors');
|
||||
const routes = require('./routes');
|
||||
const errorController = require('./controllers/errorController');
|
||||
const errorController = require('./controllers/error.controller');
|
||||
const passport = require('passport');
|
||||
|
||||
const port = process.env.PORT || 3080;
|
||||
const host = process.env.HOST || 'localhost';
|
||||
|
@ -20,44 +20,38 @@ const projectPath = path.join(__dirname, '..', '..', 'client');
|
|||
|
||||
const app = express();
|
||||
app.use(errorController);
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.static(path.join(projectPath, 'dist')));
|
||||
app.set('trust proxy', 1); // trust first proxy
|
||||
app.use(
|
||||
session({
|
||||
secret: 'chatgpt-clone-random-secrect',
|
||||
resave: false,
|
||||
saveUninitialized: true,
|
||||
cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 } // 7 days
|
||||
})
|
||||
);
|
||||
|
||||
// ROUTES
|
||||
|
||||
/* chore: potential redirect error here, can only comment out this block;
|
||||
comment back in if using auth routes i guess */
|
||||
// app.get('/', routes.authenticatedOrRedirect, function (req, res) {
|
||||
// console.log(path.join(projectPath, 'public', 'index.html'));
|
||||
// res.sendFile(path.join(projectPath, 'public', 'index.html'));
|
||||
// });
|
||||
app.use(cors());
|
||||
|
||||
// OAUTH
|
||||
app.use(passport.initialize());
|
||||
require('../strategies/jwtStrategy');
|
||||
require('../strategies/localStrategy');
|
||||
if(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET) {
|
||||
require('../strategies/googleStrategy');
|
||||
}
|
||||
if(process.env.FACEBOOK_CLIENT_ID && process.env.FACEBOOK_CLIENT_SECRET) {
|
||||
require('../strategies/facebookStrategy');
|
||||
}
|
||||
app.use('/oauth', routes.oauth)
|
||||
// api endpoint
|
||||
app.use('/api/search', routes.authenticatedOr401, routes.search);
|
||||
app.use('/api/ask', routes.authenticatedOr401, routes.ask);
|
||||
app.use('/api/messages', routes.authenticatedOr401, routes.messages);
|
||||
app.use('/api/convos', routes.authenticatedOr401, routes.convos);
|
||||
app.use('/api/presets', routes.authenticatedOr401, routes.presets);
|
||||
app.use('/api/prompts', routes.authenticatedOr401, routes.prompts);
|
||||
app.use('/api/tokenizer', routes.authenticatedOr401, routes.tokenizer);
|
||||
app.use('/api/endpoints', routes.authenticatedOr401, routes.endpoints);
|
||||
app.use('/api/auth', routes.auth);
|
||||
app.use('/api/search', routes.search);
|
||||
app.use('/api/ask', routes.ask);
|
||||
app.use('/api/messages', routes.messages);
|
||||
app.use('/api/convos', routes.convos);
|
||||
app.use('/api/presets', routes.presets);
|
||||
app.use('/api/prompts', routes.prompts);
|
||||
app.use('/api/tokenizer', routes.tokenizer);
|
||||
app.use('/api/endpoints', routes.endpoints);
|
||||
|
||||
|
||||
// user system
|
||||
app.use('/auth', routes.auth);
|
||||
app.use('/api/me', routes.me);
|
||||
|
||||
// static files
|
||||
app.get('/*', routes.authenticatedOrRedirect, function (req, res) {
|
||||
app.get('/*', function (req, res) {
|
||||
res.sendFile(path.join(projectPath, 'dist', 'index.html'));
|
||||
});
|
||||
|
||||
|
@ -71,7 +65,7 @@ const projectPath = path.join(__dirname, '..', '..', 'client');
|
|||
})();
|
||||
|
||||
let messageCount = 0;
|
||||
process.on('uncaughtException', err => {
|
||||
process.on('uncaughtException', (err) => {
|
||||
if (!err.message.includes('fetch failed')) {
|
||||
console.error('There was an uncaught error:', err.message);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
const Keyv = require('keyv');
|
||||
const { KeyvFile } = require('keyv-file');
|
||||
const { saveMessage } = require('../../../models');
|
||||
|
||||
const addToCache = async ({ endpoint, endpointOption, userMessage, responseMessage }) => {
|
||||
try {
|
||||
|
|
|
@ -4,8 +4,9 @@ const router = express.Router();
|
|||
const { titleConvo, askBing } = require('../../../app');
|
||||
const { saveMessage, getConvoTitle, saveConvo, getConvo } = require('../../../models');
|
||||
const { handleError, sendMessage, createOnProgress, handleText } = require('./handlers');
|
||||
const requireJwtAuth = require('../../../middleware/requireJwtAuth');
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireJwtAuth, async (req, res) => {
|
||||
const {
|
||||
endpoint,
|
||||
text,
|
||||
|
@ -62,7 +63,7 @@ router.post('/', async (req, res) => {
|
|||
|
||||
if (!overrideParentMessageId) {
|
||||
await saveMessage(userMessage);
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
...userMessage,
|
||||
...endpointOption,
|
||||
conversationId,
|
||||
|
@ -205,7 +206,7 @@ const ask = async ({
|
|||
conversationUpdate.invocationId = response.invocationId;
|
||||
}
|
||||
|
||||
await saveConvo(req?.session?.user?.username, conversationUpdate);
|
||||
await saveConvo(req.user.id, conversationUpdate);
|
||||
conversationId = newConversationId;
|
||||
|
||||
// STEP3 update the user message
|
||||
|
@ -218,9 +219,9 @@ const ask = async ({
|
|||
userMessageId = newUserMassageId;
|
||||
|
||||
sendMessage(res, {
|
||||
title: await getConvoTitle(req?.session?.user?.username, conversationId),
|
||||
title: await getConvoTitle(req.user.id, conversationId),
|
||||
final: true,
|
||||
conversation: await getConvo(req?.session?.user?.username, conversationId),
|
||||
conversation: await getConvo(req.user.id, conversationId),
|
||||
requestMessage: userMessage,
|
||||
responseMessage: responseMessage
|
||||
});
|
||||
|
@ -229,7 +230,7 @@ const ask = async ({
|
|||
if (userParentMessageId == '00000000-0000-0000-0000-000000000000') {
|
||||
const title = await titleConvo({ endpoint: endpointOption?.endpoint, text, response: responseMessage });
|
||||
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId: conversationId,
|
||||
title
|
||||
});
|
||||
|
|
|
@ -5,8 +5,9 @@ const { getChatGPTBrowserModels } = require('../endpoints');
|
|||
const { browserClient } = require('../../../app/');
|
||||
const { saveMessage, getConvoTitle, saveConvo, getConvo } = require('../../../models');
|
||||
const { handleError, sendMessage, createOnProgress, handleText } = require('./handlers');
|
||||
const requireJwtAuth = require('../../../middleware/requireJwtAuth');
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireJwtAuth, async (req, res) => {
|
||||
const {
|
||||
endpoint,
|
||||
text,
|
||||
|
@ -49,7 +50,7 @@ router.post('/', async (req, res) => {
|
|||
|
||||
if (!overrideParentMessageId) {
|
||||
await saveMessage(userMessage);
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
...userMessage,
|
||||
...endpointOption,
|
||||
conversationId,
|
||||
|
@ -81,6 +82,7 @@ const ask = async ({
|
|||
res
|
||||
}) => {
|
||||
let { text, parentMessageId: userParentMessageId, messageId: userMessageId } = userMessage;
|
||||
const userId = req.user.id;
|
||||
|
||||
res.writeHead(200, {
|
||||
Connection: 'keep-alive',
|
||||
|
@ -121,7 +123,8 @@ const ask = async ({
|
|||
conversationId,
|
||||
...endpointOption,
|
||||
onProgress: progressCallback.call(null, { res, text }),
|
||||
abortController
|
||||
abortController,
|
||||
userId
|
||||
});
|
||||
|
||||
console.log('CLIENT RESPONSE', response);
|
||||
|
@ -168,7 +171,7 @@ const ask = async ({
|
|||
};
|
||||
}
|
||||
|
||||
await saveConvo(req?.session?.user?.username, conversationUpdate);
|
||||
await saveConvo(req.user.id, conversationUpdate);
|
||||
conversationId = newConversationId;
|
||||
|
||||
// STEP3 update the user message
|
||||
|
@ -181,9 +184,9 @@ const ask = async ({
|
|||
userMessageId = newUserMassageId;
|
||||
|
||||
sendMessage(res, {
|
||||
title: await getConvoTitle(req?.session?.user?.username, conversationId),
|
||||
title: await getConvoTitle(req.user.id, conversationId),
|
||||
final: true,
|
||||
conversation: await getConvo(req?.session?.user?.username, conversationId),
|
||||
conversation: await getConvo(req.user.id, conversationId),
|
||||
requestMessage: userMessage,
|
||||
responseMessage: responseMessage
|
||||
});
|
||||
|
@ -192,7 +195,7 @@ const ask = async ({
|
|||
if (userParentMessageId == '00000000-0000-0000-0000-000000000000') {
|
||||
// const title = await titleConvo({ endpoint: endpointOption?.endpoint, text, response: responseMessage });
|
||||
const title = await response.details.title;
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId: conversationId,
|
||||
title
|
||||
});
|
||||
|
|
|
@ -6,10 +6,11 @@ const { getOpenAIModels } = require('../endpoints');
|
|||
const { titleConvo, askClient } = require('../../../app/');
|
||||
const { saveMessage, getConvoTitle, saveConvo, getConvo } = require('../../../models');
|
||||
const { handleError, sendMessage, createOnProgress, handleText } = require('./handlers');
|
||||
const requireJwtAuth = require('../../../middleware/requireJwtAuth');
|
||||
|
||||
const abortControllers = new Map();
|
||||
|
||||
router.post('/abort', async (req, res) => {
|
||||
router.post('/abort', requireJwtAuth, async (req, res) => {
|
||||
const { abortKey } = req.body;
|
||||
console.log(`req.body`, req.body);
|
||||
if (!abortControllers.has(abortKey)) {
|
||||
|
@ -26,7 +27,7 @@ router.post('/abort', async (req, res) => {
|
|||
res.send(JSON.stringify(ret));
|
||||
});
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireJwtAuth, async (req, res) => {
|
||||
const {
|
||||
endpoint,
|
||||
text,
|
||||
|
@ -74,7 +75,7 @@ router.post('/', async (req, res) => {
|
|||
|
||||
if (!overrideParentMessageId) {
|
||||
await saveMessage(userMessage);
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
...userMessage,
|
||||
...endpointOption,
|
||||
conversationId,
|
||||
|
@ -106,7 +107,7 @@ const ask = async ({
|
|||
res
|
||||
}) => {
|
||||
let { text, parentMessageId: userParentMessageId, messageId: userMessageId } = userMessage;
|
||||
|
||||
const userId = req.user.id;
|
||||
let responseMessageId = crypto.randomUUID();
|
||||
|
||||
res.writeHead(200, {
|
||||
|
@ -159,9 +160,9 @@ const ask = async ({
|
|||
await addToCache({ endpoint: 'openAI', endpointOption, userMessage, responseMessage });
|
||||
|
||||
return {
|
||||
title: await getConvoTitle(req?.session?.user?.username, conversationId),
|
||||
title: await getConvoTitle(req.user.id, conversationId),
|
||||
final: true,
|
||||
conversation: await getConvo(req?.session?.user?.username, conversationId),
|
||||
conversation: await getConvo(req.user.id, conversationId),
|
||||
requestMessage: userMessage,
|
||||
responseMessage: responseMessage
|
||||
};
|
||||
|
@ -179,7 +180,8 @@ const ask = async ({
|
|||
text,
|
||||
parentMessageId: overrideParentMessageId || userMessageId
|
||||
}),
|
||||
abortController
|
||||
abortController,
|
||||
userId
|
||||
});
|
||||
|
||||
abortControllers.delete(abortKey);
|
||||
|
@ -225,7 +227,7 @@ const ask = async ({
|
|||
};
|
||||
}
|
||||
|
||||
await saveConvo(req?.session?.user?.username, conversationUpdate);
|
||||
await saveConvo(req.user.id, conversationUpdate);
|
||||
conversationId = newConversationId;
|
||||
|
||||
// STEP3 update the user message
|
||||
|
@ -238,9 +240,9 @@ const ask = async ({
|
|||
userMessageId = newUserMassageId;
|
||||
|
||||
sendMessage(res, {
|
||||
title: await getConvoTitle(req?.session?.user?.username, conversationId),
|
||||
title: await getConvoTitle(req.user.id, conversationId),
|
||||
final: true,
|
||||
conversation: await getConvo(req?.session?.user?.username, conversationId),
|
||||
conversation: await getConvo(req.user.id, conversationId),
|
||||
requestMessage: userMessage,
|
||||
responseMessage: responseMessage
|
||||
});
|
||||
|
@ -248,7 +250,7 @@ const ask = async ({
|
|||
|
||||
if (userParentMessageId == '00000000-0000-0000-0000-000000000000') {
|
||||
const title = await titleConvo({ endpoint: endpointOption?.endpoint, text, response: responseMessage });
|
||||
await saveConvo(req?.session?.user?.username, {
|
||||
await saveConvo(req.user.id, {
|
||||
conversationId: conversationId,
|
||||
title
|
||||
});
|
||||
|
|
|
@ -1,57 +1,25 @@
|
|||
const express = require('express');
|
||||
const {
|
||||
resetPasswordRequestController,
|
||||
resetPasswordController,
|
||||
getUserController,
|
||||
loginController,
|
||||
logoutController,
|
||||
refreshController,
|
||||
registrationController,
|
||||
} = require('../controllers/auth.controller');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
const requireLocalAuth = require('../../middleware/requireLocalAuth');
|
||||
|
||||
const router = express.Router();
|
||||
const authYourLogin = require('./authYourLogin');
|
||||
const userSystemEnabled = !!process.env.ENABLE_USER_SYSTEM || false;
|
||||
|
||||
router.get('/login', function (req, res) {
|
||||
if (userSystemEnabled) {
|
||||
res.redirect('/auth/your_login_page');
|
||||
} else {
|
||||
res.redirect('/');
|
||||
}
|
||||
});
|
||||
//Local
|
||||
router.get('/user', requireJwtAuth, getUserController);
|
||||
router.post('/logout', requireJwtAuth, logoutController);
|
||||
router.post('/login', requireLocalAuth, loginController);
|
||||
router.post('/refresh', requireJwtAuth, refreshController);
|
||||
router.post('/register', registrationController);
|
||||
router.post('/requestPasswordReset', resetPasswordRequestController);
|
||||
router.post('/resetPassword', resetPasswordController);
|
||||
|
||||
router.get('/logout', function (req, res) {
|
||||
// clear the session
|
||||
req.session.user = null;
|
||||
|
||||
req.session.save(function () {
|
||||
if (userSystemEnabled) {
|
||||
res.redirect('/auth/your_login_page/logout');
|
||||
} else {
|
||||
res.redirect('/');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const authenticatedOr401 = (req, res, next) => {
|
||||
if (userSystemEnabled) {
|
||||
const user = req?.session?.user;
|
||||
|
||||
if (user) {
|
||||
next();
|
||||
} else {
|
||||
res.status(401).end();
|
||||
}
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
};
|
||||
|
||||
const authenticatedOrRedirect = (req, res, next) => {
|
||||
if (userSystemEnabled) {
|
||||
const user = req?.session?.user;
|
||||
|
||||
if (user) {
|
||||
next();
|
||||
} else {
|
||||
res.redirect('/auth/login');
|
||||
}
|
||||
} else next();
|
||||
};
|
||||
|
||||
if (userSystemEnabled) {
|
||||
router.use('/your_login_page', authYourLogin);
|
||||
}
|
||||
|
||||
module.exports = { router, authenticatedOr401, authenticatedOrRedirect };
|
||||
module.exports = router;
|
||||
|
|
|
@ -1,44 +0,0 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
// WARNING!
|
||||
// THIS IS NOT A READY TO USE USER SYSTEM
|
||||
// PLEASE IMPLEMENT YOUR OWN USER SYSTEM
|
||||
|
||||
const userSystemEnabled = process.env.ENABLE_USER_SYSTEM || false;
|
||||
|
||||
// Logout
|
||||
router.get('/logout', (req, res) => {
|
||||
// Do anything you want
|
||||
console.warn('logout not implemented!');
|
||||
|
||||
// finish
|
||||
res.redirect('/');
|
||||
});
|
||||
|
||||
// Login
|
||||
router.get('/', async (req, res) => {
|
||||
// Do anything you want
|
||||
console.warn('login not implemented! Automatic passed as sample user');
|
||||
|
||||
// save the user info into session
|
||||
// username will be used in db
|
||||
// display will be used in UI
|
||||
if (userSystemEnabled) {
|
||||
req.session.user = {
|
||||
username: null, // was 'sample_user', but would break previous relationship with previous conversations before v0.1.0
|
||||
display: 'Sample User'
|
||||
};
|
||||
}
|
||||
|
||||
req.session.save(function (error) {
|
||||
if (error) {
|
||||
console.log(error);
|
||||
res.send(`<h1>Login Failed. An error occurred. Please see the server logs for details.</h1>`);
|
||||
} else {
|
||||
res.redirect('/');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
|
@ -1,24 +1,23 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { titleConvo } = require('../../app/');
|
||||
const { getConvo, saveConvo, getConvoTitle } = require('../../models');
|
||||
const { getConvo, saveConvo } = require('../../models');
|
||||
const { getConvosByPage, deleteConvos } = require('../../models/Conversation');
|
||||
const { getMessages } = require('../../models/Message');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
router.get('/', requireJwtAuth, async (req, res) => {
|
||||
const pageNumber = req.query.pageNumber || 1;
|
||||
res.status(200).send(await getConvosByPage(req?.session?.user?.username, pageNumber));
|
||||
res.status(200).send(await getConvosByPage(req.user.id, pageNumber));
|
||||
});
|
||||
|
||||
router.get('/:conversationId', async (req, res) => {
|
||||
router.get('/:conversationId', requireJwtAuth, async (req, res) => {
|
||||
const { conversationId } = req.params;
|
||||
const convo = await getConvo(req?.session?.user?.username, conversationId);
|
||||
const convo = await getConvo(req.user.id, conversationId);
|
||||
|
||||
if (convo) res.status(200).send(convo.toObject());
|
||||
else res.status(404).end();
|
||||
});
|
||||
|
||||
router.post('/clear', async (req, res) => {
|
||||
router.post('/clear', requireJwtAuth, async (req, res) => {
|
||||
let filter = {};
|
||||
const { conversationId, source } = req.body.arg;
|
||||
if (conversationId) {
|
||||
|
@ -32,7 +31,7 @@ router.post('/clear', async (req, res) => {
|
|||
}
|
||||
|
||||
try {
|
||||
const dbResponse = await deleteConvos(req?.session?.user?.username, filter);
|
||||
const dbResponse = await deleteConvos(req.user.id, filter);
|
||||
res.status(201).send(dbResponse);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
@ -40,11 +39,11 @@ router.post('/clear', async (req, res) => {
|
|||
}
|
||||
});
|
||||
|
||||
router.post('/update', async (req, res) => {
|
||||
router.post('/update', requireJwtAuth, async (req, res) => {
|
||||
const update = req.body.arg;
|
||||
|
||||
try {
|
||||
const dbResponse = await saveConvo(req?.session?.user?.username, update);
|
||||
const dbResponse = await saveConvo(req.user.id, update);
|
||||
res.status(201).send(dbResponse);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
|
|
|
@ -5,9 +5,9 @@ const presets = require('./presets');
|
|||
const prompts = require('./prompts');
|
||||
const search = require('./search');
|
||||
const tokenizer = require('./tokenizer');
|
||||
const me = require('./me');
|
||||
const auth = require('./auth');
|
||||
const oauth = require('./oauth');
|
||||
const { router: endpoints } = require('./endpoints');
|
||||
const { router: auth, authenticatedOr401, authenticatedOrRedirect } = require('./auth');
|
||||
|
||||
module.exports = {
|
||||
search,
|
||||
|
@ -17,9 +17,7 @@ module.exports = {
|
|||
presets,
|
||||
prompts,
|
||||
auth,
|
||||
oauth,
|
||||
tokenizer,
|
||||
me,
|
||||
endpoints,
|
||||
authenticatedOr401,
|
||||
authenticatedOrRedirect
|
||||
};
|
||||
|
|
|
@ -1,16 +0,0 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const userSystemEnabled = !!process.env.ENABLE_USER_SYSTEM || false;
|
||||
|
||||
router.get('/', function (req, res) {
|
||||
if (userSystemEnabled) {
|
||||
const user = req?.session?.user;
|
||||
|
||||
if (user) res.send(JSON.stringify({ username: user?.username, display: user?.display }));
|
||||
else res.send(JSON.stringify(null));
|
||||
} else {
|
||||
res.send(JSON.stringify({ username: 'anonymous_user', display: 'Anonymous User' }));
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
|
@ -1,8 +1,9 @@
|
|||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { getMessages } = require('../../models/Message');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
|
||||
router.get('/:conversationId', async (req, res) => {
|
||||
router.get('/:conversationId', requireJwtAuth, async (req, res) => {
|
||||
const { conversationId } = req.params;
|
||||
res.status(200).send(await getMessages({ conversationId }));
|
||||
});
|
||||
|
|
64
api/server/routes/oauth.js
Normal file
64
api/server/routes/oauth.js
Normal file
|
@ -0,0 +1,64 @@
|
|||
const passport = require('passport');
|
||||
const express = require('express');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const clientUrl = isProduction ? process.env.CLIENT_URL_PROD : process.env.CLIENT_URL_DEV;
|
||||
|
||||
// Social
|
||||
router.get(
|
||||
'/google',
|
||||
passport.authenticate('google', {
|
||||
scope: ['openid', 'profile', 'email'],
|
||||
session: false
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/google/callback',
|
||||
passport.authenticate('google', {
|
||||
failureRedirect: `${clientUrl}/login`,
|
||||
failureMessage: true,
|
||||
session: false,
|
||||
scope: ['openid', 'profile', 'email']
|
||||
}),
|
||||
(req, res) => {
|
||||
const token = req.user.generateToken();
|
||||
res.cookie('token', token, {
|
||||
expires: new Date(Date.now() + eval(process.env.SESSION_EXPIRY)),
|
||||
httpOnly: false,
|
||||
secure: isProduction
|
||||
});
|
||||
res.redirect(clientUrl);
|
||||
}
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/facebook',
|
||||
passport.authenticate('facebook', {
|
||||
scope: ['public_profile', 'email'],
|
||||
session: false
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/facebook/callback',
|
||||
passport.authenticate('facebook', {
|
||||
failureRedirect: `${clientUrl}/login`,
|
||||
failureMessage: true,
|
||||
session: false,
|
||||
scope: ['public_profile', 'email']
|
||||
}),
|
||||
(req, res) => {
|
||||
const token = req.user.generateToken();
|
||||
res.cookie('token', token, {
|
||||
expires: new Date(Date.now() + eval(process.env.SESSION_EXPIRY)),
|
||||
httpOnly: false,
|
||||
secure: isProduction
|
||||
});
|
||||
res.redirect(clientUrl);
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = router;
|
|
@ -2,23 +2,24 @@ const express = require('express');
|
|||
const router = express.Router();
|
||||
const { getPresets, savePreset, deletePresets } = require('../../models');
|
||||
const crypto = require('crypto');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
const presets = (await getPresets(req?.session?.user?.username)).map((preset) => {
|
||||
router.get('/', requireJwtAuth, async (req, res) => {
|
||||
const presets = (await getPresets(req.user.id)).map((preset) => {
|
||||
return preset.toObject();
|
||||
});
|
||||
res.status(200).send(presets);
|
||||
});
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireJwtAuth, async (req, res) => {
|
||||
const update = req.body || {};
|
||||
|
||||
update.presetId = update?.presetId || crypto.randomUUID();
|
||||
|
||||
try {
|
||||
await savePreset(req?.session?.user?.username, update);
|
||||
await savePreset(req.user.id, update);
|
||||
|
||||
const presets = (await getPresets(req?.session?.user?.username)).map((preset) => {
|
||||
const presets = (await getPresets(req.user.id)).map((preset) => {
|
||||
return preset.toObject();
|
||||
});
|
||||
res.status(201).send(presets);
|
||||
|
@ -28,7 +29,7 @@ router.post('/', async (req, res) => {
|
|||
}
|
||||
});
|
||||
|
||||
router.post('/delete', async (req, res) => {
|
||||
router.post('/delete', requireJwtAuth, async (req, res) => {
|
||||
let filter = {};
|
||||
const { presetId } = req.body.arg || {};
|
||||
|
||||
|
@ -37,9 +38,9 @@ router.post('/delete', async (req, res) => {
|
|||
console.log('delete preset filter', filter);
|
||||
|
||||
try {
|
||||
await deletePresets(req?.session?.user?.username, filter);
|
||||
await deletePresets(req.user.id, filter);
|
||||
|
||||
const presets = (await getPresets(req?.session?.user?.username)).map(preset => preset.toObject());
|
||||
const presets = (await getPresets(req.user.id)).map(preset => preset.toObject());
|
||||
|
||||
// console.log('delete preset response', presets);
|
||||
res.status(201).send(presets);
|
||||
|
|
|
@ -5,6 +5,8 @@ const { Message } = require('../../models/Message');
|
|||
const { Conversation, getConvosQueried } = require('../../models/Conversation');
|
||||
const { reduceHits } = require('../../lib/utils/reduceHits');
|
||||
const { cleanUpPrimaryKeyValue } = require('../../lib/utils/misc');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
router.get('/sync', async function (req, res) {
|
||||
|
@ -13,9 +15,9 @@ router.get('/sync', async function (req, res) {
|
|||
res.send('synced');
|
||||
});
|
||||
|
||||
router.get('/', async function (req, res) {
|
||||
router.get('/', requireJwtAuth, async function (req, res) {
|
||||
try {
|
||||
let user = req?.session?.user?.username;
|
||||
let user = req.user.id;
|
||||
user = user ?? null;
|
||||
const { q } = req.query;
|
||||
const pageNumber = req.query.pageNumber || 1;
|
||||
|
|
|
@ -4,8 +4,9 @@ const { Tiktoken } = require('@dqbd/tiktoken/lite');
|
|||
const { load } = require('@dqbd/tiktoken/load');
|
||||
const registry = require('@dqbd/tiktoken/registry.json');
|
||||
const models = require('@dqbd/tiktoken/model_to_encoding.json');
|
||||
const requireJwtAuth = require('../../middleware/requireJwtAuth');
|
||||
|
||||
router.post('/', async (req, res) => {
|
||||
router.post('/', requireJwtAuth, async (req, res) => {
|
||||
try {
|
||||
const { arg } = req.body;
|
||||
|
||||
|
|
197
api/server/services/auth.service.js
Normal file
197
api/server/services/auth.service.js
Normal file
|
@ -0,0 +1,197 @@
|
|||
const User = require('../../models/User');
|
||||
const Token = require('../../models/schema/tokenSchema');
|
||||
const sendEmail = require('../../utils/sendEmail');
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const DebugControl = require('../../utils/debug.js');
|
||||
const Joi = require('joi');
|
||||
const { registerSchema } = require('../../strategies/validators');
|
||||
const migrateDataToFirstUser = require('../../utils/migrateDataToFirstUser');
|
||||
|
||||
function log({ title, parameters }) {
|
||||
DebugControl.log.functionName(title);
|
||||
DebugControl.log.parameters(parameters);
|
||||
}
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const clientUrl = isProduction ? process.env.CLIENT_URL_PROD : process.env.CLIENT_URL_DEV;
|
||||
|
||||
const loginUser = async (user) => {
|
||||
// const refreshToken = req.user.generateRefreshToken();
|
||||
const dbUser = await User.findById(user._id);
|
||||
//todo: save refresh token
|
||||
|
||||
return dbUser;
|
||||
};
|
||||
|
||||
const logoutUser = async (user, refreshToken) => {
|
||||
User.findById(user._id).then((user) => {
|
||||
const tokenIndex = user.refreshToken.findIndex(item => item.refreshToken === refreshToken);
|
||||
|
||||
if (tokenIndex !== -1) {
|
||||
user.refreshToken.id(user.refreshToken[tokenIndex]._id).remove();
|
||||
}
|
||||
|
||||
user.save((err) => {
|
||||
if (err) {
|
||||
return { status: 500, message: err.message };
|
||||
} else {
|
||||
//res.clearCookie('refreshToken', COOKIE_OPTIONS);
|
||||
// removeTokenCookie(res);
|
||||
return { status: 200, message: 'Logout successful' };
|
||||
}
|
||||
});
|
||||
});
|
||||
return { status: 200, message: 'Logout successful' };
|
||||
};
|
||||
|
||||
const registerUser = async (user) => {
|
||||
let response = {};
|
||||
const { error } = Joi.validate(user, registerSchema);
|
||||
if (error) {
|
||||
log({
|
||||
title: 'Route: register - Joi Validation Error',
|
||||
parameters: [
|
||||
{ name: 'Request params:', value: user },
|
||||
{ name: 'Validation error:', value: error.details }
|
||||
]
|
||||
});
|
||||
response = { status: 422, message: error.details[0].message };
|
||||
return response;
|
||||
}
|
||||
|
||||
const { email, password, name, username } = user;
|
||||
|
||||
try {
|
||||
const existingUser = await User.findOne({ email });
|
||||
|
||||
if (existingUser) {
|
||||
log({
|
||||
title: 'Register User - Email in use',
|
||||
parameters: [
|
||||
{ name: 'Request params:', value: user },
|
||||
{ name: 'Existing user:', value: existingUser }
|
||||
]
|
||||
});
|
||||
response = { status: 422, message: 'Email is in use' };
|
||||
return response;
|
||||
}
|
||||
|
||||
//determine if this is the first registered user (not counting anonymous_user)
|
||||
const isFirstRegisteredUser = await User.countDocuments({}) === 0;
|
||||
|
||||
try {
|
||||
const newUser = await new User({
|
||||
provider: 'local',
|
||||
email,
|
||||
password,
|
||||
username,
|
||||
name,
|
||||
avatar: null,
|
||||
role: isFirstRegisteredUser ? 'ADMIN' : 'USER',
|
||||
});
|
||||
|
||||
// todo: implement refresh token
|
||||
// const refreshToken = newUser.generateRefreshToken();
|
||||
// newUser.refreshToken.push({ refreshToken });
|
||||
bcrypt.genSalt(10, (err, salt) => {
|
||||
bcrypt.hash(newUser.password, salt, (errh, hash) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
}
|
||||
// set pasword to hash
|
||||
newUser.password = hash;
|
||||
newUser.save();
|
||||
});
|
||||
});
|
||||
console.log('newUser', newUser)
|
||||
if (isFirstRegisteredUser) {
|
||||
migrateDataToFirstUser(newUser);
|
||||
// console.log(migrate);
|
||||
}
|
||||
response = { status: 200, user: newUser };
|
||||
return response;
|
||||
} catch (err) {
|
||||
response = { status: 500, message: err.message };
|
||||
return response;
|
||||
}
|
||||
} catch (err) {
|
||||
response = { status: 500, message: err.message };
|
||||
return response;
|
||||
}
|
||||
};
|
||||
|
||||
const requestPasswordReset = async (email) => {
|
||||
const user = await User.findOne({ email });
|
||||
if (!user) {
|
||||
return new Error('Email does not exist');
|
||||
}
|
||||
|
||||
let token = await Token.findOne({ userId: user._id });
|
||||
if (token) await token.deleteOne();
|
||||
|
||||
let resetToken = crypto.randomBytes(32).toString('hex');
|
||||
const hash = await bcrypt.hash(resetToken, 10);
|
||||
|
||||
await new Token({
|
||||
userId: user._id,
|
||||
token: hash,
|
||||
createdAt: Date.now()
|
||||
}).save();
|
||||
|
||||
const link = `${clientUrl}/reset-password?token=${resetToken}&userId=${user._id}`;
|
||||
|
||||
sendEmail(
|
||||
user.email,
|
||||
'Password Reset Request',
|
||||
{
|
||||
name: user.name,
|
||||
link: link
|
||||
},
|
||||
'./template/requestResetPassword.handlebars'
|
||||
);
|
||||
return { link };
|
||||
};
|
||||
|
||||
const resetPassword = async (userId, token, password) => {
|
||||
let passwordResetToken = await Token.findOne({ userId });
|
||||
|
||||
if (!passwordResetToken) {
|
||||
return new Error('Invalid or expired password reset token');
|
||||
}
|
||||
|
||||
const isValid = await bcrypt.compare(token, passwordResetToken.token);
|
||||
|
||||
if (!isValid) {
|
||||
return new Error('Invalid or expired password reset token');
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
|
||||
await User.updateOne({ _id: userId }, { $set: { password: hash } }, { new: true });
|
||||
|
||||
const user = await User.findById({ _id: userId });
|
||||
|
||||
sendEmail(
|
||||
user.email,
|
||||
'Password Reset Successfnodeully',
|
||||
{
|
||||
name: user.name
|
||||
},
|
||||
'./template/resetPassword.handlebars'
|
||||
);
|
||||
|
||||
await passwordResetToken.deleteOne();
|
||||
|
||||
return { message: 'Password reset was successful' };
|
||||
};
|
||||
|
||||
|
||||
module.exports = {
|
||||
// signup,
|
||||
registerUser,
|
||||
loginUser,
|
||||
logoutUser,
|
||||
requestPasswordReset,
|
||||
resetPassword,
|
||||
};
|
60
api/strategies/facebookStrategy.js
Normal file
60
api/strategies/facebookStrategy.js
Normal file
|
@ -0,0 +1,60 @@
|
|||
const passport = require('passport');
|
||||
const FacebookStrategy = require('passport-facebook').Strategy;
|
||||
const User = require('../models/User');
|
||||
|
||||
const serverUrl =
|
||||
process.env.NODE_ENV === 'production' ? process.env.SERVER_URL_PROD : process.env.SERVER_URL_DEV;
|
||||
|
||||
// facebook strategy
|
||||
const facebookLogin = new FacebookStrategy(
|
||||
{
|
||||
clientID: process.env.FACEBOOK_APP_ID,
|
||||
clientSecret: process.env.FACEBOOK_SECRET,
|
||||
callbackURL: `${serverUrl}${process.env.FACEBOOK_CALLBACK_URL}`,
|
||||
proxy: true,
|
||||
// profileFields: [
|
||||
// 'id',
|
||||
// 'email',
|
||||
// 'gender',
|
||||
// 'profileUrl',
|
||||
// 'displayName',
|
||||
// 'locale',
|
||||
// 'name',
|
||||
// 'timezone',
|
||||
// 'updated_time',
|
||||
// 'verified',
|
||||
// 'picture.type(large)'
|
||||
// ]
|
||||
},
|
||||
async (accessToken, refreshToken, profile, done) => {
|
||||
console.log('facebookLogin => profile', profile);
|
||||
try {
|
||||
const oldUser = await User.findOne({ email: profile.emails[0].value });
|
||||
|
||||
if (oldUser) {
|
||||
console.log('FACEBOOK LOGIN => found user', oldUser);
|
||||
return done(null, oldUser);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
// register user
|
||||
try {
|
||||
const newUser = await new User({
|
||||
provider: 'facebook',
|
||||
facebookId: profile.id,
|
||||
username: profile.name.givenName + profile.name.familyName,
|
||||
email: profile.emails[0].value,
|
||||
name: profile.displayName,
|
||||
avatar: profile.photos[0].value
|
||||
}).save();
|
||||
|
||||
done(null, newUser);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
passport.use(facebookLogin);
|
44
api/strategies/googleStrategy.js
Normal file
44
api/strategies/googleStrategy.js
Normal file
|
@ -0,0 +1,44 @@
|
|||
const passport = require('passport');
|
||||
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
|
||||
|
||||
const User = require('../models/User');
|
||||
|
||||
const serverUrl =
|
||||
process.env.NODE_ENV === 'production' ? process.env.SERVER_URL_PROD : process.env.SERVER_URL_DEV;
|
||||
|
||||
// google strategy
|
||||
const googleLogin = new GoogleStrategy(
|
||||
{
|
||||
clientID: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
callbackURL: `${serverUrl}${process.env.GOOGLE_CALLBACK_URL}`,
|
||||
proxy: true
|
||||
},
|
||||
async (accessToken, refreshToken, profile, cb) => {
|
||||
try {
|
||||
const oldUser = await User.findOne({ email: profile.emails[0].value });
|
||||
if (oldUser) {
|
||||
return cb(null, oldUser);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
try {
|
||||
const newUser = await new User({
|
||||
provider: 'google',
|
||||
googleId: profile.id,
|
||||
username: profile.name.givenName + profile.name.familyName,
|
||||
email: profile.emails[0].value,
|
||||
emailVerified: profile.emails[0].verified,
|
||||
name: `${profile.name.givenName} ${profile.name.familyName}`,
|
||||
avatar: profile.photos[0].value
|
||||
}).save();
|
||||
cb(null, newUser);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
passport.use(googleLogin);
|
29
api/strategies/jwtStrategy.js
Normal file
29
api/strategies/jwtStrategy.js
Normal file
|
@ -0,0 +1,29 @@
|
|||
const passport = require('passport');
|
||||
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
|
||||
const User = require('../models/User');
|
||||
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
const secretOrKey = isProduction ? process.env.JWT_SECRET_PROD : process.env.JWT_SECRET_DEV;
|
||||
|
||||
// JWT strategy
|
||||
const jwtLogin = new JwtStrategy(
|
||||
{
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
secretOrKey
|
||||
},
|
||||
async (payload, done) => {
|
||||
try {
|
||||
const user = await User.findById(payload.id);
|
||||
if (user) {
|
||||
done(null, user);
|
||||
} else {
|
||||
console.log('JwtStrategy => no user found');
|
||||
done(null, false);
|
||||
}
|
||||
} catch (err) {
|
||||
done(err, false);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
passport.use(jwtLogin);
|
68
api/strategies/localStrategy.js
Normal file
68
api/strategies/localStrategy.js
Normal file
|
@ -0,0 +1,68 @@
|
|||
const passport = require('passport');
|
||||
const PassportLocalStrategy = require('passport-local').Strategy;
|
||||
const Joi = require('joi');
|
||||
|
||||
const User = require('../models/User');
|
||||
const { loginSchema } = require('./validators');
|
||||
const DebugControl = require('../utils/debug.js');
|
||||
|
||||
const passportLogin = new PassportLocalStrategy(
|
||||
{
|
||||
usernameField: 'email',
|
||||
passwordField: 'password',
|
||||
session: false,
|
||||
passReqToCallback: true
|
||||
},
|
||||
async (req, email, password, done) => {
|
||||
const { error } = Joi.validate(req.body, loginSchema);
|
||||
if (error) {
|
||||
log({
|
||||
title: 'Passport Local Strategy - Validation Error',
|
||||
parameters: [{ name: 'req.body', value: req.body }]
|
||||
});
|
||||
return done(null, false, { message: error.details[0].message });
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await User.findOne({ email: email.trim() });
|
||||
if (!user) {
|
||||
log({
|
||||
title: 'Passport Local Strategy - User Not Found',
|
||||
parameters: [{ name: 'email', value: email }]
|
||||
});
|
||||
return done(null, false, { message: 'Email does not exists.' });
|
||||
}
|
||||
|
||||
user.comparePassword(password, function (err, isMatch) {
|
||||
if (err) {
|
||||
log({
|
||||
title: 'Passport Local Strategy - Compare password error',
|
||||
parameters: [{ name: 'error', value: err }]
|
||||
});
|
||||
return done(err);
|
||||
}
|
||||
if (!isMatch) {
|
||||
log({
|
||||
title: 'Passport Local Strategy - Password does not match',
|
||||
parameters: [{ name: 'isMatch', value: isMatch }]
|
||||
});
|
||||
return done(null, false, { message: 'Incorrect password.' });
|
||||
}
|
||||
|
||||
return done(null, user);
|
||||
});
|
||||
} catch (err) {
|
||||
return done(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
passport.use(passportLogin);
|
||||
|
||||
function log({ title, parameters }) {
|
||||
DebugControl.log.functionName(title);
|
||||
if (parameters) {
|
||||
DebugControl.log.parameters(parameters);
|
||||
}
|
||||
}
|
||||
|
24
api/strategies/validators.js
Normal file
24
api/strategies/validators.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
const Joi = require('joi');
|
||||
|
||||
const loginSchema = Joi.object().keys({
|
||||
email: Joi.string().trim().email().required(),
|
||||
password: Joi.string().trim().min(6).max(20).required()
|
||||
});
|
||||
|
||||
const registerSchema = Joi.object().keys({
|
||||
name: Joi.string().trim().min(2).max(30).required(),
|
||||
username: Joi.string()
|
||||
.trim()
|
||||
.min(2)
|
||||
.max(20)
|
||||
.regex(/^[a-zA-Z0-9_]+$/)
|
||||
.required(),
|
||||
email: Joi.string().trim().email().required(),
|
||||
password: Joi.string().trim().min(6).max(20).required(),
|
||||
confirm_password: Joi.string().trim().min(6).max(20).required()
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
loginSchema,
|
||||
registerSchema
|
||||
};
|
46
api/utils/debug.js
Normal file
46
api/utils/debug.js
Normal file
|
@ -0,0 +1,46 @@
|
|||
const levels = {
|
||||
NONE: 0,
|
||||
LOW: 1,
|
||||
MEDIUM: 2,
|
||||
HIGH: 3
|
||||
};
|
||||
|
||||
let level = levels.HIGH;
|
||||
|
||||
module.exports = {
|
||||
levels,
|
||||
setLevel: (l) => (level = l),
|
||||
log: {
|
||||
parameters: (parameters) => {
|
||||
if (levels.HIGH > level) return;
|
||||
console.group();
|
||||
parameters.forEach((p) => console.log(`${p.name}:`, p.value));
|
||||
console.groupEnd();
|
||||
},
|
||||
functionName: (name) => {
|
||||
if (levels.MEDIUM > level) return;
|
||||
console.log(`\nEXECUTING: ${name}\n`);
|
||||
},
|
||||
flow: (flow) => {
|
||||
if (levels.LOW > level) return;
|
||||
console.log(`\n\n\nBEGIN FLOW: ${flow}\n\n\n`);
|
||||
},
|
||||
variable: ({ name, value }) => {
|
||||
if (levels.HIGH > level) return;
|
||||
console.group();
|
||||
console.group();
|
||||
console.log(`VARIABLE ${name}:`, value);
|
||||
console.groupEnd();
|
||||
console.groupEnd();
|
||||
},
|
||||
request: () => (req, res, next) => {
|
||||
if (levels.HIGH > level) return next();
|
||||
console.log('Hit URL', req.url, 'with following:');
|
||||
console.group();
|
||||
console.log('Query:', req.query);
|
||||
console.log('Body:', req.body);
|
||||
console.groupEnd();
|
||||
return next();
|
||||
}
|
||||
}
|
||||
};
|
11
api/utils/emails/passwordReset.handlebars
Normal file
11
api/utils/emails/passwordReset.handlebars
Normal file
|
@ -0,0 +1,11 @@
|
|||
<html>
|
||||
<head>
|
||||
<style>
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>Hi {{name}},</p>
|
||||
<p>Your password has been changed successfully.</p>
|
||||
</body>
|
||||
</html>
|
13
api/utils/emails/requestPasswordReset.handlebars
Normal file
13
api/utils/emails/requestPasswordReset.handlebars
Normal file
|
@ -0,0 +1,13 @@
|
|||
<html>
|
||||
<head>
|
||||
<style>
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>Hi {{name}},</p>
|
||||
<h1>You have requested to reset your password.</h1>
|
||||
<p> Please click the link below to reset your password.</p>
|
||||
<a href="{{link}}">Reset Password</a>
|
||||
</body>
|
||||
</html>
|
30
api/utils/migrateDataToFirstUser.js
Normal file
30
api/utils/migrateDataToFirstUser.js
Normal file
|
@ -0,0 +1,30 @@
|
|||
const Conversation = require('../models/schema/convoSchema');
|
||||
const Preset = require('../models/schema/presetSchema');
|
||||
|
||||
const migrateConversations = async (userId) => {
|
||||
try {
|
||||
return await Conversation.updateMany({ user: null }, { $set: { user: userId }}).exec();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return { message: 'Error saving conversation' };
|
||||
}
|
||||
}
|
||||
|
||||
const migratePresets = async (userId) => {
|
||||
try {
|
||||
return await Preset.updateMany({ user: null }, { $set: { user: userId }}).exec();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return { message: 'Error saving conversation' };
|
||||
}
|
||||
}
|
||||
|
||||
const migrateDataToFirstUser = async (user) => {
|
||||
const conversations = await migrateConversations(user.id);
|
||||
console.log(conversations);
|
||||
const presets = await migratePresets(user.id);
|
||||
console.log(presets);
|
||||
}
|
||||
|
||||
|
||||
module.exports = migrateDataToFirstUser;
|
54
api/utils/sendEmail.js
Normal file
54
api/utils/sendEmail.js
Normal file
|
@ -0,0 +1,54 @@
|
|||
const nodemailer = require("nodemailer");
|
||||
const handlebars = require("handlebars");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const sendEmail = async (email, subject, payload, template) => {
|
||||
try {
|
||||
// create reusable transporter object using the default SMTP transport
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: process.env.EMAIL_HOST,
|
||||
port: 465,
|
||||
auth: {
|
||||
user: process.env.EMAIL_USERNAME,
|
||||
pass: process.env.EMAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
const source = fs.readFileSync(path.join(__dirname, template), "utf8");
|
||||
const compiledTemplate = handlebars.compile(source);
|
||||
const options = () => {
|
||||
return {
|
||||
from: process.env.FROM_EMAIL,
|
||||
to: email,
|
||||
subject: subject,
|
||||
html: compiledTemplate(payload),
|
||||
};
|
||||
};
|
||||
|
||||
// Send email
|
||||
transporter.sendMail(options(), (error, info) => {
|
||||
if (error) {
|
||||
return error;
|
||||
} else {
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
Example:
|
||||
sendEmail(
|
||||
"youremail@gmail.com,
|
||||
"Email subject",
|
||||
{ name: "Eze" },
|
||||
"./templates/layouts/main.handlebars"
|
||||
);
|
||||
*/
|
||||
|
||||
module.exports = sendEmail;
|
16
client/.env.example
Normal file
16
client/.env.example
Normal file
|
@ -0,0 +1,16 @@
|
|||
###########################
|
||||
# Server URL configuration:
|
||||
###########################
|
||||
|
||||
# The social login domain uses this to redirect to localhost:3080 when you run the app in dev mode with Vite.
|
||||
# Use your domain name as the Prod URL when you deploy the app to a live domain.
|
||||
# Please note that:
|
||||
# Social login features will not work if you run the build version on port 3080 locally after modifying the Prod URL
|
||||
VITE_SERVER_URL_DEV=http://localhost:3080
|
||||
VITE_SERVER_URL_PROD=http://localhost:3080
|
||||
|
||||
# Enable Social Login
|
||||
# This enables/disables the Login with Google button on the login page.
|
||||
# Set to true if you have registered the app with google cloud services
|
||||
# and have set the GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in the /api/.env file
|
||||
VITE_SHOW_GOOGLE_LOGIN_OPTION=false
|
3053
client/package-lock.json
generated
3053
client/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -6,8 +6,7 @@
|
|||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite",
|
||||
"preview-prod": "vite preview",
|
||||
"build-dev": "Webpack . --watch"
|
||||
"preview-prod": "vite preview"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
@ -21,6 +20,11 @@
|
|||
},
|
||||
"homepage": "https://github.com/danny-avila/chatgpt-clone#readme",
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^6.4.0",
|
||||
"@fortawesome/free-brands-svg-icons": "^6.4.0",
|
||||
"@fortawesome/free-regular-svg-icons": "^6.4.0",
|
||||
"@fortawesome/free-solid-svg-icons": "^6.4.0",
|
||||
"@fortawesome/react-fontawesome": "^0.2.0",
|
||||
"@headlessui/react": "^1.7.13",
|
||||
"@radix-ui/react-alert-dialog": "^1.0.2",
|
||||
"@radix-ui/react-checkbox": "^1.0.3",
|
||||
|
@ -30,6 +34,7 @@
|
|||
"@radix-ui/react-label": "^2.0.0",
|
||||
"@radix-ui/react-slider": "^1.1.1",
|
||||
"@radix-ui/react-tabs": "^1.0.3",
|
||||
"@tailwindcss/forms": "^0.5.3",
|
||||
"@tanstack/react-query": "^4.28.0",
|
||||
"@types/jest": "^29.5.0",
|
||||
"@types/node": "^18.15.10",
|
||||
|
@ -51,6 +56,7 @@
|
|||
"rc-input-number": "^7.4.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "^7.43.9",
|
||||
"react-lazy-load": "^4.0.1",
|
||||
"react-markdown": "^8.0.6",
|
||||
"react-router-dom": "^6.9.0",
|
||||
|
@ -108,9 +114,6 @@
|
|||
"ts-loader": "^9.4.2",
|
||||
"typescript": "^4.9.5",
|
||||
"vite": "^4.2.1",
|
||||
"vite-plugin-html": "^3.2.0",
|
||||
"webpack": "^5.77.0",
|
||||
"webpack-cli": "^5.0.1",
|
||||
"webpack-dev-server": "^4.11.1"
|
||||
"vite-plugin-html": "^3.2.0"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,94 +1,93 @@
|
|||
import { useEffect } from 'react';
|
||||
import { createBrowserRouter, RouterProvider, Navigate } from 'react-router-dom';
|
||||
import { createBrowserRouter, RouterProvider, Navigate, Outlet } from 'react-router-dom';
|
||||
import Root from './routes/Root';
|
||||
import Chat from './routes/Chat';
|
||||
import Search from './routes/Search';
|
||||
import store from './store';
|
||||
import { useRecoilState, useSetRecoilState } from 'recoil';
|
||||
import { ScreenshotProvider } from './utils/screenshotContext.jsx';
|
||||
import { useGetSearchEnabledQuery, useGetUserQuery, useGetEndpointsQuery, useGetPresetsQuery} from '~/data-provider';
|
||||
import {ReactQueryDevtools} from '@tanstack/react-query-devtools';
|
||||
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
||||
import { Login, Registration, RequestPasswordReset, ResetPassword } from './components/Auth';
|
||||
import { AuthContextProvider } from './hooks/AuthContext';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { QueryClient, QueryClientProvider, QueryCache } from '@tanstack/react-query';
|
||||
import { ThemeProvider } from './hooks/ThemeContext';
|
||||
import { useApiErrorBoundary } from './hooks/ApiErrorBoundaryContext';
|
||||
import ApiErrorWatcher from './components/Auth/ApiErrorWatcher';
|
||||
|
||||
const AuthLayout = () => (
|
||||
<AuthContextProvider>
|
||||
<Outlet />
|
||||
<ApiErrorWatcher />
|
||||
</AuthContextProvider>
|
||||
);
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: '/',
|
||||
element: <Root />,
|
||||
path: 'register',
|
||||
element: <Registration />
|
||||
},
|
||||
{
|
||||
path: 'forgot-password',
|
||||
element: <RequestPasswordReset />
|
||||
},
|
||||
{
|
||||
path: 'reset-password',
|
||||
element: <ResetPassword />
|
||||
},
|
||||
{
|
||||
element: <AuthLayout />,
|
||||
children: [
|
||||
{
|
||||
index: true,
|
||||
element: (
|
||||
<Navigate
|
||||
to="/chat/new"
|
||||
replace={true}
|
||||
/>
|
||||
)
|
||||
path: 'login',
|
||||
element: <Login />
|
||||
},
|
||||
{
|
||||
path: 'chat/:conversationId?',
|
||||
element: <Chat />
|
||||
},
|
||||
{
|
||||
path: 'search/:query?',
|
||||
element: <Search />
|
||||
path: '/',
|
||||
element: <Root />,
|
||||
children: [
|
||||
{
|
||||
index: true,
|
||||
element: (
|
||||
<Navigate
|
||||
to="/chat/new"
|
||||
replace={true}
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
path: 'chat/:conversationId?',
|
||||
element: <Chat />
|
||||
},
|
||||
{
|
||||
path: 'search/:query?',
|
||||
element: <Search />
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]);
|
||||
|
||||
const App = () => {
|
||||
const [user, setUser] = useRecoilState(store.user);
|
||||
const setIsSearchEnabled = useSetRecoilState(store.isSearchEnabled);
|
||||
const setEndpointsConfig = useSetRecoilState(store.endpointsConfig);
|
||||
const setPresets = useSetRecoilState(store.presets);
|
||||
const { setError } = useApiErrorBoundary();
|
||||
|
||||
const searchEnabledQuery = useGetSearchEnabledQuery();
|
||||
const userQuery = useGetUserQuery();
|
||||
const endpointsQuery = useGetEndpointsQuery();
|
||||
const presetsQuery = useGetPresetsQuery();
|
||||
const queryClient = new QueryClient({
|
||||
queryCache: new QueryCache({
|
||||
onError: error => {
|
||||
if (error?.response?.status === 401) {
|
||||
setError(error);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if(endpointsQuery.data) {
|
||||
setEndpointsConfig(endpointsQuery.data);
|
||||
} else if(endpointsQuery.isError) {
|
||||
console.error("Failed to get endpoints", endpointsQuery.error);
|
||||
window.location.href = '/auth/login';
|
||||
}
|
||||
}, [endpointsQuery.data, endpointsQuery.isError]);
|
||||
|
||||
useEffect(() => {
|
||||
if(presetsQuery.data) {
|
||||
setPresets(presetsQuery.data);
|
||||
} else if(presetsQuery.isError) {
|
||||
console.error("Failed to get presets", presetsQuery.error);
|
||||
window.location.href = '/auth/login';
|
||||
}
|
||||
}, [presetsQuery.data, presetsQuery.isError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchEnabledQuery.data) {
|
||||
setIsSearchEnabled(searchEnabledQuery.data);
|
||||
} else if(searchEnabledQuery.isError) {
|
||||
console.error("Failed to get search enabled", searchEnabledQuery.error);
|
||||
}
|
||||
}, [searchEnabledQuery.data, searchEnabledQuery.isError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (userQuery.data) {
|
||||
setUser(userQuery.data);
|
||||
} else if(userQuery.isError) {
|
||||
console.error("Failed to get user", userQuery.error);
|
||||
window.location.href = '/auth/login';
|
||||
}
|
||||
}, [userQuery.data, userQuery.isError]);
|
||||
|
||||
if (user)
|
||||
return (
|
||||
<>
|
||||
<RouterProvider router={router} />
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</>
|
||||
);
|
||||
else return <div className="flex h-screen"></div>;
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RecoilRoot>
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</ThemeProvider>
|
||||
</RecoilRoot>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default () => (
|
||||
|
|
18
client/src/components/Auth/ApiErrorWatcher.tsx
Normal file
18
client/src/components/Auth/ApiErrorWatcher.tsx
Normal file
|
@ -0,0 +1,18 @@
|
|||
import React from 'react';
|
||||
import { useApiErrorBoundary } from '~/hooks/ApiErrorBoundaryContext';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const ApiErrorWatcher = () => {
|
||||
const { error } = useApiErrorBoundary();
|
||||
const navigate = useNavigate();
|
||||
React.useEffect(() => {
|
||||
if (error?.response?.status === 500) {
|
||||
// do something with error
|
||||
// navigate('/login');
|
||||
}
|
||||
}, [error, navigate]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default ApiErrorWatcher;
|
184
client/src/components/Auth/Login.tsx
Normal file
184
client/src/components/Auth/Login.tsx
Normal file
|
@ -0,0 +1,184 @@
|
|||
import { useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { TLoginUser } from "~/data-provider";
|
||||
import { useAuthContext } from "~/hooks/AuthContext";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
function Login() {
|
||||
const { login, error, isAuthenticated } = useAuthContext();
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<TLoginUser>();
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
navigate("/chat/new");
|
||||
}
|
||||
}, [isAuthenticated, navigate])
|
||||
|
||||
|
||||
const SERVER_URL = import.meta.env.DEV
|
||||
? import.meta.env.VITE_SERVER_URL_DEV
|
||||
: import.meta.env.VITE_SERVER_URL_PROD;
|
||||
const showGoogleLogin =
|
||||
import.meta.env.VITE_SHOW_GOOGLE_LOGIN_OPTION === "true";
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center pt-6 justify-center sm:pt-0 bg-white">
|
||||
<div className="mt-6 overflow-hidden bg-white px-6 py-4 sm:max-w-md sm:rounded-lg w-96">
|
||||
<h1 className="text-center text-3xl font-semibold mb-4">Welcome back</h1>
|
||||
{error && (
|
||||
<div
|
||||
className="mt-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
Unable to login with the information provided. Please check your
|
||||
credentials and try again.
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="mt-6"
|
||||
aria-label="Login form"
|
||||
method="POST"
|
||||
onSubmit={handleSubmit((data) => login(data))}
|
||||
>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
autoComplete="email"
|
||||
aria-label="Email"
|
||||
{...register("email", {
|
||||
required: "Email is required",
|
||||
minLength: {
|
||||
value: 3,
|
||||
message: "Email must be at least 6 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 120,
|
||||
message: "Email should not be longer than 120 characters",
|
||||
},
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message: "You must enter a valid email address",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.email}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="absolute text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Email address
|
||||
</label>
|
||||
</div>
|
||||
{errors.email && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.email.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
aria-label="Password"
|
||||
{...register("password", {
|
||||
required: "Password is required",
|
||||
minLength: {
|
||||
value: 8,
|
||||
message: "Password must be at least 8 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 40,
|
||||
message: "Password must be less than 40 characters",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.password}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="absolute text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.password && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.password.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<a
|
||||
href="/forgot-password"
|
||||
className="text-sm text-green-500 hover:underline"
|
||||
>
|
||||
Forgot Password?
|
||||
</a>
|
||||
<div className="mt-6">
|
||||
<button
|
||||
aria-label="Sign in"
|
||||
type="submit"
|
||||
className="w-full transform rounded-sm bg-green-500 px-4 py-3 tracking-wide text-white transition-colors duration-200 hover:bg-green-600 focus:bg-green-600 focus:outline-none"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<p className="my-4 text-center text-sm font-light text-gray-700">
|
||||
{" "}
|
||||
Don't have an account?{" "}
|
||||
<a
|
||||
href="/register"
|
||||
className="p-1 text-green-500 hover:underline"
|
||||
>
|
||||
Sign up
|
||||
</a>
|
||||
</p>
|
||||
{showGoogleLogin && (
|
||||
<>
|
||||
<div className="relative mt-6 flex w-full items-center justify-center border border-t uppercase">
|
||||
<div className="absolute text-xs bg-white px-3">Or</div>
|
||||
</div>
|
||||
<div className="mt-4 flex gap-x-2">
|
||||
<a
|
||||
aria-label="Login with Google"
|
||||
className="flex w-full items-center justify-left space-x-3 rounded-md border border-gray-300 py-3 px-5 focus:ring-2 focus:ring-violet-600 focus:ring-offset-1 hover:bg-gray-50"
|
||||
href={`${SERVER_URL}/oauth/google`}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" id="google" className="w-5 h-5"><path fill="#fbbb00" d="M113.47 309.408 95.648 375.94l-65.139 1.378C11.042 341.211 0 299.9 0 256c0-42.451 10.324-82.483 28.624-117.732h.014L86.63 148.9l25.404 57.644c-5.317 15.501-8.215 32.141-8.215 49.456.002 18.792 3.406 36.797 9.651 53.408z"></path><path fill="#518ef8" d="M507.527 208.176C510.467 223.662 512 239.655 512 256c0 18.328-1.927 36.206-5.598 53.451-12.462 58.683-45.025 109.925-90.134 146.187l-.014-.014-73.044-3.727-10.338-64.535c29.932-17.554 53.324-45.025 65.646-77.911h-136.89V208.176h245.899z"></path><path fill="#28b446" d="m416.253 455.624.014.014C372.396 490.901 316.666 512 256 512c-97.491 0-182.252-54.491-225.491-134.681l82.961-67.91c21.619 57.698 77.278 98.771 142.53 98.771 28.047 0 54.323-7.582 76.87-20.818l83.383 68.262z"></path><path fill="#f14336" d="m419.404 58.936-82.933 67.896C313.136 112.246 285.552 103.82 256 103.82c-66.729 0-123.429 42.957-143.965 102.724l-83.397-68.276h-.014C71.23 56.123 157.06 0 256 0c62.115 0 119.068 22.126 163.404 58.936z"></path></svg>
|
||||
<p>Login with Google</p>
|
||||
</a>
|
||||
|
||||
{/* <a
|
||||
aria-label="Login with Facebook"
|
||||
className="flex w-full items-center justify-center rounded-md border border-gray-600 p-2 focus:ring-2 focus:ring-violet-600 focus:ring-offset-1"
|
||||
href="http://localhost:3080/auth/facebook">
|
||||
<FontAwesomeIcon
|
||||
icon={faFacebook}
|
||||
size={'lg'}
|
||||
/>
|
||||
</a> */}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Login;
|
315
client/src/components/Auth/Registration.tsx
Normal file
315
client/src/components/Auth/Registration.tsx
Normal file
|
@ -0,0 +1,315 @@
|
|||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useRegisterUserMutation, TRegisterUser } from "~/data-provider";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faFacebook } from "@fortawesome/free-brands-svg-icons";
|
||||
import { faGoogle } from "@fortawesome/free-brands-svg-icons";
|
||||
|
||||
function Registration() {
|
||||
const SERVER_URL = import.meta.env.DEV
|
||||
? import.meta.env.VITE_SERVER_URL_DEV
|
||||
: import.meta.env.VITE_SERVER_URL_PROD;
|
||||
const showGoogleLogin =
|
||||
import.meta.env.VITE_SHOW_GOOGLE_LOGIN_OPTION === "true";
|
||||
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
register,
|
||||
watch,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<TRegisterUser>({ mode: "onChange" });
|
||||
const [error, setError] = useState<boolean>(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string>("");
|
||||
const registerUser = useRegisterUserMutation();
|
||||
|
||||
const password = watch("password");
|
||||
|
||||
const onRegisterUserFormSubmit = (data: TRegisterUser) => {
|
||||
registerUser.mutate(data, {
|
||||
onSuccess: () => {
|
||||
navigate("/chat/new");
|
||||
},
|
||||
onError: (error) => {
|
||||
setError(true);
|
||||
if (error.response?.data?.message) {
|
||||
setErrorMessage(error.response?.data?.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center pt-6 justify-center sm:pt-0 bg-white">
|
||||
<div className="mt-6 overflow-hidden bg-white px-6 py-4 sm:max-w-md sm:rounded-lg w-96">
|
||||
<h1 className="text-center text-3xl font-semibold mb-4">
|
||||
Create your account
|
||||
</h1>
|
||||
{error && (
|
||||
<div
|
||||
className="mt-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
There was an error attempting to register your account. Please try
|
||||
again. {errorMessage}
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="mt-6"
|
||||
aria-label="Registration form"
|
||||
method="POST"
|
||||
onSubmit={handleSubmit((data) => onRegisterUserFormSubmit(data))}
|
||||
>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
id="name"
|
||||
type="text"
|
||||
autoComplete="name"
|
||||
aria-label="Name"
|
||||
// uncomment to prevent pasting in confirm field
|
||||
onPaste={(e) => {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
}}
|
||||
{...register("name", {
|
||||
required: "Name is required",
|
||||
minLength: {
|
||||
value: 3,
|
||||
message: "Name must be at least 3 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 80,
|
||||
message: "Name must be less than 80 characters",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.name}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="name"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Full Name
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.name && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.name.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
aria-label="Username"
|
||||
{...register("username", {
|
||||
required: "Username is required",
|
||||
minLength: {
|
||||
value: 3,
|
||||
message: "Username must be at least 3 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 20,
|
||||
message: "Username must be less than 20 characters",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.username}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
autoComplete="off"
|
||||
></input>
|
||||
<label
|
||||
htmlFor="username"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Username
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.username && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.username.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
autoComplete="email"
|
||||
aria-label="Email"
|
||||
{...register("email", {
|
||||
required: "Email is required",
|
||||
minLength: {
|
||||
value: 3,
|
||||
message: "Email must be at least 6 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 120,
|
||||
message: "Email should not be longer than 120 characters",
|
||||
},
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message: "You must enter a valid email address",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.email}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
</div>
|
||||
{errors.email && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.email.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
aria-label="Password"
|
||||
{...register("password", {
|
||||
required: "Password is required",
|
||||
minLength: {
|
||||
value: 8,
|
||||
message: "Password must be at least 8 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 40,
|
||||
message: "Password must be less than 40 characters",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.password}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.password && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.password.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
id="confirm_password"
|
||||
aria-label="Confirm Password"
|
||||
// uncomment to prevent pasting in confirm field
|
||||
onPaste={(e) => {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
}}
|
||||
{...register("confirm_password", {
|
||||
validate: (value) =>
|
||||
value === password || "Passwords do not match",
|
||||
})}
|
||||
aria-invalid={!!errors.confirm_password}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="confirm_password"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Confirm Password
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.confirm_password && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.confirm_password.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<button
|
||||
disabled={
|
||||
!!errors.email ||
|
||||
!!errors.name ||
|
||||
!!errors.password ||
|
||||
!!errors.username ||
|
||||
!!errors.confirm_password
|
||||
}
|
||||
type="submit"
|
||||
aria-label="Submit registration"
|
||||
className="w-full transform rounded-sm bg-green-500 px-4 py-3 tracking-wide text-white transition-colors duration-200 hover:bg-green-600 focus:bg-green-600 focus:outline-none"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<p className="my-4 text-center text-sm font-light text-gray-700">
|
||||
{" "}
|
||||
Already have an account?{" "}
|
||||
<a
|
||||
href="/login"
|
||||
className="font-medium text-green-500 p-1 hover:underline"
|
||||
>
|
||||
Login
|
||||
</a>
|
||||
</p>
|
||||
{showGoogleLogin && (
|
||||
<>
|
||||
<div className="relative mt-6 flex w-full items-center justify-center border border-t uppercase">
|
||||
<div className="absolute text-xs bg-white px-3">Or</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex gap-x-2">
|
||||
<a
|
||||
aria-label="Login with Google"
|
||||
href={`${SERVER_URL}/oauth/google`}
|
||||
className="flex w-full items-center justify-left space-x-3 rounded-md border border-gray-300 py-3 px-5 focus:ring-2 focus:ring-violet-600 focus:ring-offset-1 hover:bg-gray-50"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" id="google" className="w-5 h-5"><path fill="#fbbb00" d="M113.47 309.408 95.648 375.94l-65.139 1.378C11.042 341.211 0 299.9 0 256c0-42.451 10.324-82.483 28.624-117.732h.014L86.63 148.9l25.404 57.644c-5.317 15.501-8.215 32.141-8.215 49.456.002 18.792 3.406 36.797 9.651 53.408z"></path><path fill="#518ef8" d="M507.527 208.176C510.467 223.662 512 239.655 512 256c0 18.328-1.927 36.206-5.598 53.451-12.462 58.683-45.025 109.925-90.134 146.187l-.014-.014-73.044-3.727-10.338-64.535c29.932-17.554 53.324-45.025 65.646-77.911h-136.89V208.176h245.899z"></path><path fill="#28b446" d="m416.253 455.624.014.014C372.396 490.901 316.666 512 256 512c-97.491 0-182.252-54.491-225.491-134.681l82.961-67.91c21.619 57.698 77.278 98.771 142.53 98.771 28.047 0 54.323-7.582 76.87-20.818l83.383 68.262z"></path><path fill="#f14336" d="m419.404 58.936-82.933 67.896C313.136 112.246 285.552 103.82 256 103.82c-66.729 0-123.429 42.957-143.965 102.724l-83.397-68.276h-.014C71.23 56.123 157.06 0 256 0c62.115 0 119.068 22.126 163.404 58.936z"></path></svg>
|
||||
<p>Login with Google</p>
|
||||
</a>
|
||||
{/* <button
|
||||
aria-label="Login with Facebook"
|
||||
role="button"
|
||||
className="flex w-full items-center justify-center space-x-3 rounded-md border p-4 focus:ring-2 focus:ring-violet-400 focus:ring-offset-1 dark:border-gray-400"
|
||||
>
|
||||
<FontAwesomeIcon
|
||||
icon={faFacebook}
|
||||
size={'lg'}
|
||||
/>
|
||||
<p>Login with Facebook</p>
|
||||
</button> */}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Registration;
|
115
client/src/components/Auth/RequestPasswordReset.tsx
Normal file
115
client/src/components/Auth/RequestPasswordReset.tsx
Normal file
|
@ -0,0 +1,115 @@
|
|||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useRequestPasswordResetMutation, TRequestPasswordReset } from "~/data-provider";
|
||||
|
||||
function RequestPasswordReset() {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<TRequestPasswordReset>();
|
||||
const requestPasswordReset = useRequestPasswordResetMutation();
|
||||
const [success, setSuccess] = useState<boolean>(false);
|
||||
const [requestError, setRequestError] = useState<boolean>(false);
|
||||
const [resetLink, setResetLink] = useState<string>("");
|
||||
|
||||
const onSubmit = (data: TRequestPasswordReset) => {
|
||||
requestPasswordReset.mutate(data, {
|
||||
onSuccess: (data) => {
|
||||
setSuccess(true);
|
||||
setResetLink(data.link);
|
||||
},
|
||||
onError: () => {
|
||||
setRequestError(true);
|
||||
setTimeout(() => {
|
||||
setRequestError(false);
|
||||
}, 5000);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center pt-6 justify-center sm:pt-0 bg-white">
|
||||
<div className="mt-6 overflow-hidden bg-white px-6 py-4 sm:max-w-md sm:rounded-lg w-96">
|
||||
<h1 className="text-center text-3xl font-semibold mb-4">
|
||||
Reset your password
|
||||
</h1>
|
||||
{success && (
|
||||
<div
|
||||
className="mt-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
Click <a className="text-green-600 hover:underline" href={resetLink}>HERE</a> to reset your password.
|
||||
{/* An email has been sent with instructions on how to reset your password. */}
|
||||
</div>
|
||||
)}
|
||||
{requestError && (
|
||||
<div
|
||||
className="mt-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
There was a problem resetting your password. There was no user found with the email address provided. Please try again.
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="mt-6"
|
||||
aria-label="Password reset form"
|
||||
method="POST"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
autoComplete="off"
|
||||
aria-label="Email"
|
||||
{...register("email", {
|
||||
required: "Email is required",
|
||||
minLength: {
|
||||
value: 3,
|
||||
message: "Email must be at least 6 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 120,
|
||||
message: "Email should not be longer than 120 characters",
|
||||
},
|
||||
pattern: {
|
||||
value: /\S+@\S+\.\S+/,
|
||||
message: "You must enter a valid email address",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.email}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="absolute text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Email address
|
||||
</label>
|
||||
</div>
|
||||
{errors.email && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.email.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={ !!errors.email }
|
||||
className="w-full py-2 px-4 border border-transparent rounded-sm shadow-sm text-sm font-medium text-white bg-green-500 hover:bg-green-600 focus:outline-none active:bg-green-500"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RequestPasswordReset;
|
176
client/src/components/Auth/ResetPassword.tsx
Normal file
176
client/src/components/Auth/ResetPassword.tsx
Normal file
|
@ -0,0 +1,176 @@
|
|||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import {useResetPasswordMutation, TResetPassword} from "~/data-provider";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
|
||||
function ResetPassword() {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useForm<TResetPassword>();
|
||||
const resetPassword = useResetPasswordMutation();
|
||||
const [resetError, setResetError] = useState<boolean>(false);
|
||||
const [params] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const password = watch("password");
|
||||
|
||||
const onSubmit = (data: TResetPassword) => {
|
||||
resetPassword.mutate(data, {
|
||||
onError: () => {
|
||||
setResetError(true);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (resetPassword.isSuccess) {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center pt-6 justify-center sm:pt-0 bg-white">
|
||||
<div className="mt-6 overflow-hidden bg-white px-6 py-4 sm:max-w-md sm:rounded-lg w-96">
|
||||
<h1 className="text-center text-3xl font-semibold mb-4">
|
||||
Password Reset Success
|
||||
</h1>
|
||||
<div
|
||||
className="mt-4 bg-green-100 border border-green-400 text-center mb-8 text-green-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
You may now login with your new password.
|
||||
</div>
|
||||
<button
|
||||
onClick={() => navigate("/login")}
|
||||
aria-label="Sign in"
|
||||
className="w-full transform rounded-sm bg-green-500 px-4 py-3 tracking-wide text-white transition-colors duration-200 hover:bg-green-600 focus:bg-green-600 focus:outline-none"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
else {
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col items-center pt-6 justify-center sm:pt-0 bg-white">
|
||||
<div className="mt-6 overflow-hidden bg-white px-6 py-4 sm:max-w-md sm:rounded-lg w-96">
|
||||
<h1 className="text-center text-3xl font-semibold mb-4">
|
||||
Reset your password
|
||||
</h1>
|
||||
{resetError && (
|
||||
<div
|
||||
className="mt-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
|
||||
role="alert"
|
||||
>
|
||||
This password reset token is no longer valid. <a className="font-semibold hover:underline text-green-600" href="/forgot-password">Click here</a> to try again.
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
className="mt-6"
|
||||
aria-label="Password reset form"
|
||||
method="POST"
|
||||
onSubmit={handleSubmit(onSubmit)}
|
||||
>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input type="hidden" id="token" value={params.get("token")} {...register("token", { required: "Unable to process: No valid reset token" })} />
|
||||
<input type="hidden" id="userId" value={params.get("userId")} {...register("userId", { required: "Unable to process: No valid user id" })} />
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
aria-label="Password"
|
||||
{...register("password", {
|
||||
required: "Password is required",
|
||||
minLength: {
|
||||
value: 8,
|
||||
message: "Password must be at least 8 characters",
|
||||
},
|
||||
maxLength: {
|
||||
value: 40,
|
||||
message: "Password must be less than 40 characters",
|
||||
},
|
||||
})}
|
||||
aria-invalid={!!errors.password}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{errors.password && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.password.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="password"
|
||||
id="confirm_password"
|
||||
aria-label="Confirm Password"
|
||||
// uncomment to prevent pasting in confirm field
|
||||
onPaste={(e) => {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
}}
|
||||
{...register("confirm_password", {
|
||||
validate: (value) =>
|
||||
value === password || "Passwords do not match",
|
||||
})}
|
||||
aria-invalid={!!errors.confirm_password}
|
||||
className="block rounded-t-md px-2.5 pb-2.5 pt-5 w-full text-sm text-gray-900 bg-gray-50 border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-green-500 peer"
|
||||
placeholder=" "
|
||||
></input>
|
||||
<label
|
||||
htmlFor="confirm_password"
|
||||
className="absolute text-sm text-gray-500 duration-300 transform -translate-y-4 scale-75 top-4 z-10 origin-[0] left-2.5 peer-focus:text-green-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-4"
|
||||
>
|
||||
Confirm Password
|
||||
</label>
|
||||
</div>
|
||||
{errors.confirm_password && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.confirm_password.message}
|
||||
</span>
|
||||
)}
|
||||
{errors.token && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.token.message}
|
||||
</span>
|
||||
)}
|
||||
{errors.userId && (
|
||||
<span role="alert" className="mt-1 text-sm text-red-600">
|
||||
{/* @ts-ignore */}
|
||||
{errors.userId.message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<button
|
||||
disabled={
|
||||
!!errors.password ||
|
||||
!!errors.confirm_password
|
||||
}
|
||||
type="submit"
|
||||
aria-label="Submit registration"
|
||||
className="w-full transform rounded-sm bg-green-500 px-4 py-3 tracking-wide text-white transition-colors duration-200 hover:bg-green-600 focus:bg-green-600 focus:outline-none"
|
||||
>
|
||||
Continue
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
export default ResetPassword;
|
4
client/src/components/Auth/index.ts
Normal file
4
client/src/components/Auth/index.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
export { default as Login } from './Login';
|
||||
export { default as Registration } from './Registration';
|
||||
export { default as RequestPasswordReset } from './RequestPasswordReset';
|
||||
export { default as ResetPassword } from './ResetPassword';
|
|
@ -4,6 +4,7 @@ import { SSE } from '~/data-provider/sse.mjs';
|
|||
import createPayload from '~/data-provider/createPayload';
|
||||
import { useAbortRequestWithMessage } from '~/data-provider';
|
||||
import store from '~/store';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
|
||||
export default function MessageHandler() {
|
||||
const submission = useRecoilValue(store.submission);
|
||||
|
@ -11,6 +12,7 @@ export default function MessageHandler() {
|
|||
const setMessages = useSetRecoilState(store.messages);
|
||||
const setConversation = useSetRecoilState(store.conversation);
|
||||
const resetLatestMessage = useResetRecoilState(store.latestMessage);
|
||||
const { token } = useAuthContext();
|
||||
|
||||
const { refreshConversations } = store.useConversations();
|
||||
|
||||
|
@ -158,7 +160,8 @@ export default function MessageHandler() {
|
|||
fetch(`/api/ask/${endpoint}/abort`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
abortKey: conversationId
|
||||
|
@ -187,7 +190,7 @@ export default function MessageHandler() {
|
|||
|
||||
const events = new SSE(server, {
|
||||
payload: JSON.stringify(payload),
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`}
|
||||
});
|
||||
|
||||
events.onmessage = e => {
|
||||
|
|
|
@ -1,22 +1,22 @@
|
|||
import React from 'react';
|
||||
import LogOutIcon from '../svg/LogOutIcon';
|
||||
import { useRecoilValue } from 'recoil';
|
||||
import store from '~/store';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
|
||||
export default function Logout() {
|
||||
const user = useRecoilValue(store.user);
|
||||
const { user, logout } = useAuthContext();
|
||||
|
||||
const clickHandler = () => {
|
||||
window.location.href = '/auth/logout';
|
||||
const handleLogout = () => {
|
||||
logout()
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
className="flex cursor-pointer items-center gap-3 rounded-md py-3 px-3 text-sm text-white transition-colors duration-200 hover:bg-gray-500/10"
|
||||
onClick={clickHandler}
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOutIcon />
|
||||
{user?.display || user?.username || 'USER'}
|
||||
{user?.username || 'USER'}
|
||||
<small>Log out</small>
|
||||
</button>
|
||||
);
|
||||
|
|
|
@ -8,10 +8,11 @@ import { useRecoilValue, useSetRecoilState } from 'recoil';
|
|||
import { useGetConversationsQuery, useSearchQuery } from '~/data-provider';
|
||||
import useDebounce from '~/hooks/useDebounce';
|
||||
import store from '~/store';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
|
||||
export default function Nav({ navVisible, setNavVisible }) {
|
||||
const [isHovering, setIsHovering] = useState(false);
|
||||
|
||||
const { isAuthenticated } = useAuthContext();
|
||||
const containerRef = useRef(null);
|
||||
const scrollPositionRef = useRef(null);
|
||||
|
||||
|
@ -22,7 +23,7 @@ export default function Nav({ navVisible, setNavVisible }) {
|
|||
const [pages, setPages] = useState(1);
|
||||
|
||||
// data provider
|
||||
const getConversationsQuery = useGetConversationsQuery(pageNumber);
|
||||
const getConversationsQuery = useGetConversationsQuery(pageNumber, { enabled: isAuthenticated });
|
||||
|
||||
// search
|
||||
const searchQuery = useRecoilValue(store.searchQuery);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
export const user = () => {
|
||||
return `/api/me`;
|
||||
return `/api/auth/user`;
|
||||
};
|
||||
|
||||
export const messages = (id: string) => {
|
||||
|
@ -49,3 +49,35 @@ export const aiEndpoints = () => {
|
|||
export const tokenizer = () => {
|
||||
return `/api/tokenizer`;
|
||||
}
|
||||
|
||||
export const login = () => {
|
||||
return '/api/auth/login';
|
||||
}
|
||||
|
||||
export const logout = () => {
|
||||
return '/api/auth/logout';
|
||||
}
|
||||
|
||||
export const register = () => {
|
||||
return '/api/auth/register';
|
||||
}
|
||||
|
||||
export const loginFacebook = () => {
|
||||
return '/api/auth/facebook';
|
||||
}
|
||||
|
||||
export const loginGoogle = () => {
|
||||
return '/api/auth/google';
|
||||
}
|
||||
|
||||
export const refreshToken = () => {
|
||||
return '/api/auth/refresh';
|
||||
}
|
||||
|
||||
export const requestPasswordReset = () => {
|
||||
return '/api/auth/requestPasswordReset';
|
||||
}
|
||||
|
||||
export const resetPassword = () => {
|
||||
return '/api/auth/resetPassword';
|
||||
}
|
|
@ -67,4 +67,32 @@ export const getAIEndpoints = () => {
|
|||
|
||||
export const updateTokenCount = (text: string) => {
|
||||
return request.post(endpoints.tokenizer(), {arg: text});
|
||||
}
|
||||
|
||||
export const login = (payload: t.TLoginUser) => {
|
||||
return request.post(endpoints.login(), payload);
|
||||
}
|
||||
|
||||
export const logout = () => {
|
||||
return request.post(endpoints.logout());
|
||||
}
|
||||
|
||||
export const register = (payload: t.TRegisterUser) => {
|
||||
return request.post(endpoints.register(), payload);
|
||||
}
|
||||
|
||||
export const refreshToken = () => {
|
||||
return request.post(endpoints.refreshToken());
|
||||
}
|
||||
|
||||
export const getLoginGoogle = () => {
|
||||
return request.get(endpoints.loginGoogle());
|
||||
}
|
||||
|
||||
export const requestPasswordReset = (payload: t.TRequestPasswordReset) => {
|
||||
return request.post(endpoints.requestPasswordReset(), payload);
|
||||
}
|
||||
|
||||
export const resetPassword = (payload: t.TResetPassword) => {
|
||||
return request.post(endpoints.resetPassword(), payload);
|
||||
}
|
|
@ -8,6 +8,7 @@ import {
|
|||
} from "@tanstack/react-query";
|
||||
import * as t from "./types";
|
||||
import * as dataService from "./data-service";
|
||||
import axios from 'axios';
|
||||
|
||||
export enum QueryKeys {
|
||||
messages = "messsages",
|
||||
|
@ -25,11 +26,13 @@ export const useAbortRequestWithMessage = (): UseMutationResult<void, Error, { e
|
|||
return useMutation(({ endpoint, abortKey, message }) => dataService.abortRequestWithMessage(endpoint, abortKey, message));
|
||||
};
|
||||
|
||||
export const useGetUserQuery = (): QueryObserverResult<t.TUser> => {
|
||||
export const useGetUserQuery = (config?: UseQueryOptions<t.TUser>): QueryObserverResult<t.TUser> => {
|
||||
return useQuery<t.TUser>([QueryKeys.user], () => dataService.getUser(), {
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
retry: false,
|
||||
...config,
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -120,11 +123,13 @@ export const useClearConversationsMutation = (): UseMutationResult<unknown> => {
|
|||
});
|
||||
};
|
||||
|
||||
export const useGetConversationsQuery = (pageNumber: string): QueryObserverResult<t.TConversation[]> => {
|
||||
return useQuery([QueryKeys.allConversations, pageNumber], () =>
|
||||
export const useGetConversationsQuery = (pageNumber: string, config?: UseQueryOptions<t.TConversation[]>): QueryObserverResult<t.TConversation[]> => {
|
||||
return useQuery<t.TConversation[]>([QueryKeys.allConversations, pageNumber], () =>
|
||||
dataService.getConversations(pageNumber), {
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
retry: 1,
|
||||
...config,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
@ -176,11 +181,12 @@ export const useUpdatePresetMutation = (): UseMutationResult<t.TPreset[], unknow
|
|||
);
|
||||
};
|
||||
|
||||
export const useGetPresetsQuery = (): QueryObserverResult<t.TPreset[], unknown> => {
|
||||
return useQuery([QueryKeys.presets], () => dataService.getPresets(), {
|
||||
export const useGetPresetsQuery = (config?: UseQueryOptions<t.TPreset[]>): QueryObserverResult<t.TPreset[], unknown> => {
|
||||
return useQuery<t.TPreset[]>([QueryKeys.presets], () => dataService.getPresets(), {
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchOnMount: false,
|
||||
...config,
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -223,4 +229,52 @@ export const useUpdateTokenCountMutation = (): UseMutationResult<t.TUpdateTokenC
|
|||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export const useLoginUserMutation = (): UseMutationResult<t.TLoginUserResponse, unknown, t.TLoginUserRequest, unknown> => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation(
|
||||
(payload: t.TLoginUserRequest) =>
|
||||
dataService.login(payload),
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries([QueryKeys.user]);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export const useRegisterUserMutation = (): UseMutationResult<t.TRegisterUserResponse, unknown, t.TRegisterUser, unknown> => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation(
|
||||
(payload: t.TRegisterUser) =>
|
||||
dataService.register(payload),
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries([QueryKeys.user]);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export const useLogoutUserMutation = (): UseMutationResult<unknown> => {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation(() => dataService.logout(), {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries([QueryKeys.user]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const useRefreshTokenMutation = (): UseMutationResult<t.TRefreshTokenResponse, unknown, unknown, unknown> => {
|
||||
return useMutation(() => dataService.refreshToken(), {
|
||||
});
|
||||
}
|
||||
|
||||
export const useRequestPasswordResetMutation = (): UseMutationResult<unknown> => {
|
||||
return useMutation((payload: t.TRequestPasswordReset) => dataService.requestPasswordReset(payload));
|
||||
}
|
||||
|
||||
export const useResetPasswordMutation = (): UseMutationResult<unknown> => {
|
||||
return useMutation((payload: t.TResetPassword) => dataService.resetPassword(payload));
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
import axios, { AxiosRequestConfig } from "axios";
|
||||
|
||||
async function _get<T>(url: string, options?: AxiosRequestConfig): Promise<T> {
|
||||
const response = await axios.get(url, { withCredentials: true, ...options});
|
||||
const response = await axios.get(url, { ...options});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
|
|
|
@ -98,8 +98,14 @@ export type TPreset = {
|
|||
}
|
||||
|
||||
export type TUser = {
|
||||
id: string,
|
||||
username: string,
|
||||
display: string
|
||||
email: string,
|
||||
name: string,
|
||||
avatar: string,
|
||||
role: string,
|
||||
createdAt: string,
|
||||
updatedAt: string,
|
||||
};
|
||||
|
||||
export type TGetConversationsResponse = {
|
||||
|
@ -160,4 +166,31 @@ export type TMessageTreeNode = {}
|
|||
|
||||
export type TSearchMessage = {}
|
||||
|
||||
export type TSearchMessageTreeNode = {}
|
||||
export type TSearchMessageTreeNode = {}
|
||||
|
||||
export type TRegisterUser = {
|
||||
name: string,
|
||||
email: string,
|
||||
username: string,
|
||||
password: string,
|
||||
}
|
||||
|
||||
export type TLoginUser = {
|
||||
email: string,
|
||||
password: string,
|
||||
}
|
||||
|
||||
export type TLoginResponse = {
|
||||
token: string,
|
||||
user: TUser
|
||||
}
|
||||
|
||||
export type TRequestPasswordReset = {
|
||||
email: string,
|
||||
}
|
||||
|
||||
export type TResetPassword = {
|
||||
userId: string,
|
||||
token: string,
|
||||
password: string,
|
||||
}
|
33
client/src/hooks/ApiErrorBoundaryContext.tsx
Normal file
33
client/src/hooks/ApiErrorBoundaryContext.tsx
Normal file
|
@ -0,0 +1,33 @@
|
|||
import React, { useState } from 'react';
|
||||
|
||||
export type ApiError = {
|
||||
error: any,
|
||||
setError: (error: any) => void
|
||||
};
|
||||
|
||||
const ApiErrorBoundaryContext = React.createContext<ApiError | undefined>(undefined);
|
||||
|
||||
export const ApiErrorBoundaryProvider = ({
|
||||
value,
|
||||
children
|
||||
}: {
|
||||
value?: ApiError,
|
||||
children: React.ReactNode
|
||||
}) => {
|
||||
const [error, setError] = useState(false);
|
||||
return (
|
||||
<ApiErrorBoundaryContext.Provider value={value ? value : { error, setError }}>
|
||||
{children}
|
||||
</ApiErrorBoundaryContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useApiErrorBoundary = () => {
|
||||
const context = React.useContext(ApiErrorBoundaryContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useApiErrorBoundary must be used inside ApiErrorBoundaryProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
175
client/src/hooks/AuthContext.tsx
Normal file
175
client/src/hooks/AuthContext.tsx
Normal file
|
@ -0,0 +1,175 @@
|
|||
import { useState, useCallback, useEffect, useMemo, ReactNode, createContext, useContext } from 'react';
|
||||
import {
|
||||
TUser,
|
||||
TLoginResponse,
|
||||
setTokenHeader,
|
||||
useLoginUserMutation,
|
||||
useLogoutUserMutation,
|
||||
useGetUserQuery,
|
||||
useRefreshTokenMutation,
|
||||
TLoginUser
|
||||
} from '~/data-provider';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import store from '~/store';
|
||||
|
||||
export type TAuthContext = {
|
||||
user: TUser | undefined,
|
||||
token: string | undefined,
|
||||
isAuthenticated: boolean,
|
||||
isLoading: boolean,
|
||||
error: string | undefined,
|
||||
login: (data: TLoginUser) => void,
|
||||
logout: () => void
|
||||
};
|
||||
|
||||
export type TUserContext = {
|
||||
user?: TUser | undefined,
|
||||
token: string | undefined,
|
||||
isAuthenticated: boolean,
|
||||
redirect?: string
|
||||
};
|
||||
|
||||
const AuthContext = createContext <TAuthContext | undefined>(undefined);
|
||||
|
||||
const AuthContextProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [user, setUser] = useState<TUser | undefined>(undefined);
|
||||
const [token, setToken] = useState <string | undefined>(undefined);
|
||||
const [error, setError] = useState <string | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const loginUser = useLoginUserMutation();
|
||||
const logoutUser = useLogoutUserMutation();
|
||||
const userQuery = useGetUserQuery({ enabled: !!token });
|
||||
const refreshToken = useRefreshTokenMutation();
|
||||
|
||||
const location = useLocation();
|
||||
|
||||
const { newConversation } = store.useConversation();
|
||||
|
||||
const setUserContext = (userContext: TUserContext) => {
|
||||
const { token, isAuthenticated, user, redirect } = userContext;
|
||||
if(user) {
|
||||
setUser(user);
|
||||
}
|
||||
setToken(token);
|
||||
setTokenHeader(token);
|
||||
setIsAuthenticated(isAuthenticated);
|
||||
if (redirect) {
|
||||
navigate(redirect);
|
||||
}
|
||||
};
|
||||
|
||||
const getCookieValue = key => {
|
||||
let keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
|
||||
return keyValue ? keyValue[2] : null;
|
||||
};
|
||||
|
||||
const login = (data: TLoginUser) => {
|
||||
loginUser.mutate(data, {
|
||||
onSuccess: (data: TLoginResponse) => {
|
||||
const { user, token } = data;
|
||||
setUserContext({ token, isAuthenticated: true, user, redirect: '/chat/new' });
|
||||
},
|
||||
onError: error => {
|
||||
setError(error.message);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
document.cookie.split(';').forEach(c => {
|
||||
document.cookie = c
|
||||
.replace(/^ +/, '')
|
||||
.replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
|
||||
});
|
||||
logoutUser.mutate(undefined, {
|
||||
onSuccess: () => {
|
||||
setUserContext({ token: undefined, isAuthenticated: false, user: undefined, redirect: '/login' });
|
||||
},
|
||||
onError: error => {
|
||||
setError(error.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (userQuery.data) {
|
||||
setUser(userQuery.data);
|
||||
}
|
||||
else if (userQuery.isError) {
|
||||
setError(userQuery.error.message);
|
||||
navigate('/login');
|
||||
}
|
||||
if (error && isAuthenticated) {
|
||||
setError(undefined);
|
||||
}
|
||||
if (!token || !isAuthenticated) {
|
||||
const tokenFromCookie = getCookieValue('token');
|
||||
if (tokenFromCookie) {
|
||||
// debugger;
|
||||
setUserContext({ token: tokenFromCookie, isAuthenticated: true, user: userQuery.data, redirect: '/chat/new' })
|
||||
}
|
||||
else {
|
||||
navigate('/login');
|
||||
}
|
||||
}
|
||||
}, [token, isAuthenticated, userQuery.data, userQuery.isError]);
|
||||
|
||||
// const silentRefresh = useCallback(() => {
|
||||
// refreshToken.mutate(undefined, {
|
||||
// onSuccess: (data: TLoginResponse) => {
|
||||
// const { user, token } = data;
|
||||
// setUserContext({ token, isAuthenticated: true, user });
|
||||
// },
|
||||
// onError: error => {
|
||||
// setError(error.message);
|
||||
// }
|
||||
// });
|
||||
// setTimeout(silentRefresh, 5 * 60 * 1000);
|
||||
// }, [setUserContext]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loginUser.isLoading || logoutUser.isLoading) {
|
||||
setIsLoading(true);
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [loginUser.isLoading, logoutUser.isLoading]);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (token)
|
||||
// silentRefresh();
|
||||
// }, [token, silentRefresh]);
|
||||
|
||||
// Make the provider update only when it should
|
||||
const memoedValue = useMemo(
|
||||
() => ({
|
||||
user,
|
||||
token,
|
||||
isAuthenticated,
|
||||
isLoading,
|
||||
error,
|
||||
login,
|
||||
logout
|
||||
}),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[user, isLoading, error, isAuthenticated, token]
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={memoedValue}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
|
||||
const useAuthContext = () => {
|
||||
const context = useContext(AuthContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuthContext should be used inside AuthProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export { AuthContextProvider, useAuthContext };
|
|
@ -1,22 +1,15 @@
|
|||
import { createRoot } from 'react-dom/client';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ThemeProvider } from './hooks/ThemeContext';
|
||||
import App from './App';
|
||||
import './style.css';
|
||||
import './mobile.css';
|
||||
import { ApiErrorBoundaryProvider } from './hooks/ApiErrorBoundaryContext';
|
||||
|
||||
const container = document.getElementById('root');
|
||||
const root = createRoot(container);
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
root.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<RecoilRoot>
|
||||
<ThemeProvider>
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</RecoilRoot>
|
||||
</QueryClientProvider>
|
||||
<ApiErrorBoundaryProvider>
|
||||
<App />
|
||||
</ApiErrorBoundaryProvider>
|
||||
);
|
||||
|
|
|
@ -1,13 +1,49 @@
|
|||
import React, { useEffect, useState } from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
|
||||
import MessageHandler from '../components/MessageHandler';
|
||||
import Nav from '../components/Nav';
|
||||
import MobileNav from '../components/Nav/MobileNav';
|
||||
|
||||
import { useGetSearchEnabledQuery, useGetEndpointsQuery, useGetPresetsQuery } from '~/data-provider';
|
||||
import store from '~/store';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { useAuthContext } from '~/hooks/AuthContext';
|
||||
export default function Root() {
|
||||
const [navVisible, setNavVisible] = useState(false);
|
||||
|
||||
const setIsSearchEnabled = useSetRecoilState(store.isSearchEnabled);
|
||||
const setEndpointsConfig = useSetRecoilState(store.endpointsConfig);
|
||||
const setPresets = useSetRecoilState(store.presets);
|
||||
const { user } = useAuthContext();
|
||||
|
||||
const searchEnabledQuery = useGetSearchEnabledQuery();
|
||||
const endpointsQuery = useGetEndpointsQuery();
|
||||
const presetsQuery = useGetPresetsQuery({ enabled: !!user });
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (endpointsQuery.data) {
|
||||
setEndpointsConfig(endpointsQuery.data);
|
||||
} else if (endpointsQuery.isError) {
|
||||
console.error('Failed to get endpoints', endpointsQuery.error);
|
||||
}
|
||||
}, [endpointsQuery.data, endpointsQuery.isError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (presetsQuery.data) {
|
||||
setPresets(presetsQuery.data);
|
||||
} else if (presetsQuery.isError) {
|
||||
console.error('Failed to get presets', presetsQuery.error);
|
||||
}
|
||||
}, [presetsQuery.data, presetsQuery.isError]);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchEnabledQuery.data) {
|
||||
setIsSearchEnabled(searchEnabledQuery.data);
|
||||
} else if (searchEnabledQuery.isError) {
|
||||
console.error('Failed to get search enabled', searchEnabledQuery.error);
|
||||
}
|
||||
}, [searchEnabledQuery.data, searchEnabledQuery.isError]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-screen">
|
||||
|
@ -22,7 +58,6 @@ export default function Root() {
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MessageHandler />
|
||||
</>
|
||||
);
|
||||
|
|
|
@ -1,23 +0,0 @@
|
|||
import axios from 'axios';
|
||||
|
||||
export default async function fetchData() {
|
||||
try {
|
||||
const response = await axios.get('/api/me', {
|
||||
timeout: 1000,
|
||||
withCredentials: true
|
||||
});
|
||||
const user = response.data;
|
||||
if (user) {
|
||||
// dispatch(setUser(user));
|
||||
// callback(user);
|
||||
return user;
|
||||
} else {
|
||||
console.log('Not login!');
|
||||
window.location.href = '/auth/login';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.log('Not login!');
|
||||
window.location.href = '/auth/login';
|
||||
}
|
||||
}
|
|
@ -39,7 +39,19 @@ module.exports = {
|
|||
'700': '#40414f', // Replacing .dark .dark:bg-gray-700 and .dark .dark:hover:bg-gray-700:hover
|
||||
'800': '#343541', // Replacing .dark .dark:bg-gray-800, .bg-gray-800, and .dark .dark:hover:bg-gray-800\/90
|
||||
'900': '#202123' // Replacing .dark .dark:bg-gray-900, .bg-gray-900, and .dark .dark:hover:bg-gray-900:hover
|
||||
}
|
||||
},
|
||||
green: {
|
||||
50: "#f1f9f7",
|
||||
100: "#def2ed",
|
||||
200: "#a6e5d6",
|
||||
300: "#6dc8b9",
|
||||
400: "#41a79d",
|
||||
500: "#10a37f",
|
||||
600: "#126e6b",
|
||||
700: "#0a4f53",
|
||||
800: "#06373e",
|
||||
900: "#031f29",
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
|
@ -17,23 +17,27 @@ export default defineConfig({
|
|||
'/auth': {
|
||||
target: 'http://localhost:3080',
|
||||
changeOrigin: true
|
||||
},
|
||||
'/oauth': {
|
||||
target: 'http://localhost:3080',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: [react(), sourcemapExclude({ excludeNodeModules: true }),],
|
||||
plugins: [react(), sourcemapExclude({excludeNodeModules: true})],
|
||||
publicDir: './public',
|
||||
build: {
|
||||
sourcemap: true,
|
||||
outDir: './dist',
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: (id) => {
|
||||
if (id.includes("node_modules")) {
|
||||
return "vendor";
|
||||
manualChunks: id => {
|
||||
if (id.includes('node_modules')) {
|
||||
return 'vendor';
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
|
|
|
@ -1,111 +0,0 @@
|
|||
const path = require('path');
|
||||
// const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
|
||||
/*We are basically telling webpack to take index.js from entry. Then check for all file extensions in resolve.
|
||||
After that apply all the rules in module.rules and produce the output and place it in main.js in the public folder.*/
|
||||
|
||||
module.exports = {
|
||||
/** "mode"
|
||||
* the environment - development, production, none. tells webpack
|
||||
* to use its built-in optimizations accordingly. default is production
|
||||
*/
|
||||
mode: 'development',
|
||||
// cache: false,
|
||||
/** "entry"
|
||||
* the entry point
|
||||
*/
|
||||
entry: './index.js',
|
||||
output: {
|
||||
/** "path"
|
||||
* the folder path of the output file
|
||||
*/
|
||||
path: path.resolve(__dirname, 'public'),
|
||||
/** "filename"
|
||||
* the name of the output file
|
||||
*/
|
||||
filename: 'main.js',
|
||||
sourceMapFilename: '[name].js.map'
|
||||
},
|
||||
devtool: 'source-map',
|
||||
/** "target"
|
||||
* setting "node" as target app (server side), and setting it as "web" is
|
||||
* for browser (client side). Default is "web"
|
||||
*/
|
||||
target: 'web',
|
||||
devServer: {
|
||||
/** "port"
|
||||
* port of dev server
|
||||
*/
|
||||
port: '9500',
|
||||
/** "static"
|
||||
* This property tells Webpack what static file it should serve
|
||||
*/
|
||||
static: ['./public'],
|
||||
/** "open"
|
||||
* opens the browser after server is successfully started
|
||||
*/
|
||||
open: true,
|
||||
/** "hot"
|
||||
* enabling and disabling HMR. takes "true", "false" and "only".
|
||||
* "only" is used if enable Hot Module Replacement without page
|
||||
* refresh as a fallback in case of build failures
|
||||
*/
|
||||
hot: true,
|
||||
/** "liveReload"
|
||||
* disable live reload on the browser. "hot" must be set to false for this to work
|
||||
*/
|
||||
liveReload: true
|
||||
},
|
||||
resolve: {
|
||||
/** "extensions"
|
||||
* If multiple files share the same name but have different extensions, webpack will
|
||||
* resolve the one with the extension listed first in the array and skip the rest.
|
||||
* This is what enables users to leave off the extension when importing
|
||||
*/
|
||||
extensions: ['.js', '.jsx', '.json'],
|
||||
fallback: {
|
||||
url: require.resolve('url/'),
|
||||
fs: false,
|
||||
tls: false,
|
||||
net: false,
|
||||
path: false,
|
||||
zlib: false,
|
||||
http: false,
|
||||
https: false,
|
||||
stream: false,
|
||||
crypto: false,
|
||||
'crypto-browserify': require.resolve('crypto-browserify') //if you want to use this module also don't forget npm i crypto-browserify
|
||||
}
|
||||
},
|
||||
module: {
|
||||
/** "rules"
|
||||
* This says - "Hey webpack compiler, when you come across a path that resolves to a '.js or .jsx'
|
||||
* file inside of a require()/import statement, use the babel-loader to transform it before you
|
||||
* add it to the bundle. And in this process, kindly make sure to exclude node_modules folder from
|
||||
* being searched"
|
||||
*/
|
||||
rules: [
|
||||
{
|
||||
test: /\.(js|jsx)$/, //kind of file extension this rule should look for and apply in test
|
||||
exclude: /node_modules/, //folder to be excluded
|
||||
use: 'babel-loader' //loader which we are going to use
|
||||
},
|
||||
{
|
||||
test: /\.css$/i,
|
||||
include: path.resolve(__dirname, 'src'),
|
||||
use: ['style-loader', 'css-loader', 'postcss-loader']
|
||||
},
|
||||
{ // source: https://stackoverflow.com/questions/61767538/devtools-failed-to-load-sourcemap-for-webpack-node-modules-js-map-http-e
|
||||
test: /\.js$/,
|
||||
enforce: 'pre',
|
||||
use: ['source-map-loader'],
|
||||
},
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
]
|
||||
}
|
||||
// plugins: [new HtmlWebpackPlugin()],
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue