├── .gitignore
├── .vscode
└── launch.json
├── client
└── googledocs
│ ├── README.md
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
│ ├── src
│ ├── App.css
│ ├── App.js
│ ├── components
│ │ ├── atoms
│ │ │ ├── create-document-button
│ │ │ │ ├── create-document-btn.tsx
│ │ │ │ └── index.ts
│ │ │ ├── document-card
│ │ │ │ ├── document-card.tsx
│ │ │ │ └── index.ts
│ │ │ ├── document-menu-button
│ │ │ │ ├── document-menu-button.tsx
│ │ │ │ └── index.ts
│ │ │ ├── document-searchbar
│ │ │ │ ├── document-searchbar.tsx
│ │ │ │ └── index.ts
│ │ │ ├── errors
│ │ │ │ ├── errors.tsx
│ │ │ │ └── index.ts
│ │ │ ├── font-select
│ │ │ │ ├── font-select.tsx
│ │ │ │ └── index.ts
│ │ │ ├── icon-button
│ │ │ │ ├── icon-button.tsx
│ │ │ │ └── index.ts
│ │ │ ├── logo
│ │ │ │ ├── index.ts
│ │ │ │ └── logo.tsx
│ │ │ ├── modal
│ │ │ │ ├── index.ts
│ │ │ │ └── modal.tsx
│ │ │ ├── spinner
│ │ │ │ ├── index.ts
│ │ │ │ └── spinner.tsx
│ │ │ ├── text-field
│ │ │ │ ├── index.ts
│ │ │ │ └── text-field.tsx
│ │ │ ├── toast
│ │ │ │ ├── index.ts
│ │ │ │ └── toast.tsx
│ │ │ └── user-dropdown
│ │ │ │ ├── index.ts
│ │ │ │ └── user-dropdown.tsx
│ │ ├── molecules
│ │ │ ├── auth-route
│ │ │ │ ├── auth-route.tsx
│ │ │ │ └── index.ts
│ │ │ ├── document-menu-bar
│ │ │ │ ├── document-menu-bar.tsx
│ │ │ │ └── index.ts
│ │ │ ├── documents-list
│ │ │ │ ├── documents-list.tsx
│ │ │ │ └── index.ts
│ │ │ ├── editor-toolbar
│ │ │ │ ├── editor-toolbar.tsx
│ │ │ │ └── index.ts
│ │ │ ├── share-document-modal
│ │ │ │ ├── index.ts
│ │ │ │ └── share-document-modal.tsx
│ │ │ └── shared-users
│ │ │ │ ├── index.ts
│ │ │ │ └── shared-users.tsx
│ │ └── organisms
│ │ │ ├── document-create-header
│ │ │ ├── document-create-header.tsx
│ │ │ └── index.ts
│ │ │ ├── document-editor
│ │ │ ├── document-editor.tsx
│ │ │ └── index.ts
│ │ │ ├── document-header
│ │ │ ├── document-header.tsx
│ │ │ └── index.ts
│ │ │ └── toast-manager
│ │ │ ├── index.ts
│ │ │ └── toast-manager.tsx
│ ├── contexts
│ │ ├── auth-context.tsx
│ │ ├── document-context.tsx
│ │ ├── editor-context.tsx
│ │ └── toast-context.tsx
│ ├── hooks
│ │ ├── use-auth.tsx
│ │ ├── use-document.tsx
│ │ ├── use-documents.tsx
│ │ ├── use-local-storage.tsx
│ │ ├── use-random-background.tsx
│ │ └── use-window-size.tsx
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ ├── pages
│ │ ├── document
│ │ │ ├── create.tsx
│ │ │ └── index.tsx
│ │ ├── login
│ │ │ └── index.tsx
│ │ ├── register
│ │ │ └── index.tsx
│ │ └── user
│ │ │ └── verify-email.tsx
│ ├── services
│ │ ├── api.ts
│ │ ├── auth-service.ts
│ │ ├── document-service.ts
│ │ └── document-user-service.ts
│ ├── types
│ │ ├── enums
│ │ │ ├── permission-enum.ts
│ │ │ └── socket-events-enum.ts
│ │ └── interfaces
│ │ │ ├── action.ts
│ │ │ ├── document-user.ts
│ │ │ ├── document.ts
│ │ │ ├── input.ts
│ │ │ ├── toast.ts
│ │ │ └── token.ts
│ └── utils
│ │ └── constants.ts
│ ├── tailwind.config.js
│ └── tsconfig.json
└── server
├── .env.development
├── package-lock.json
├── package.json
├── src
├── config
│ ├── db.config.ts
│ ├── env.config.ts
│ └── smtp.config.ts
├── controllers
│ ├── auth
│ │ └── auth.controller.ts
│ ├── document
│ │ ├── document.controller.ts
│ │ └── share
│ │ │ └── share.controller.ts
│ └── user
│ │ └── user.controller.ts
├── db
│ └── models
│ │ ├── document-user.model.ts
│ │ ├── document.model.ts
│ │ ├── index.ts
│ │ ├── refresh-token.model.ts
│ │ ├── role.model.ts
│ │ ├── user-role.model.ts
│ │ └── user.model.ts
├── index.ts
├── middleware
│ ├── auth.ts
│ ├── catch-async.ts
│ └── error-handler.ts
├── responses
│ └── index.ts
├── routes
│ ├── auth.route.ts
│ ├── document.route.ts
│ ├── index.ts
│ └── user.route.ts
├── server.ts
├── services
│ ├── document.service.ts
│ ├── mail.service.ts
│ └── user.service.ts
├── types
│ ├── enums
│ │ ├── permission-enum.ts
│ │ ├── role-enum.ts
│ │ └── socket-events-enum.ts
│ └── interfaces
│ │ ├── environment.d.ts
│ │ ├── express
│ │ └── index.d.ts
│ │ └── global.d.ts
└── validators
│ ├── auth.validator.ts
│ ├── document.validator.ts
│ ├── share.validator.ts
│ └── user.validator.ts
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | server/node_modules/*
2 | client/node_modules/*
3 | node_modules/*
4 | dist
5 | node_modules
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "msedge",
9 | "request": "launch",
10 | "name": "Launch Edge against localhost",
11 | "url": "http://localhost:8080",
12 | "webRoot": "${workspaceFolder}/server/"
13 | }
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/client/googledocs/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
13 |
14 | The page will reload when you make changes.\
15 | You may also see any lint errors in the console.
16 |
17 | ### `npm test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `npm run build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `npm run eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!**
35 |
36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
39 |
40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `npm run build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/client/googledocs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "googledocs",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@heroicons/react": "^1.0.5",
7 | "@testing-library/jest-dom": "^5.17.0",
8 | "@testing-library/react": "^13.4.0",
9 | "@testing-library/user-event": "^13.5.0",
10 | "@types/jest": "^29.5.3",
11 | "@types/node": "^20.4.10",
12 | "@types/react": "^18.2.20",
13 | "@types/react-dom": "^18.2.7",
14 | "axios": "^1.4.0",
15 | "draft-js": "^0.11.7",
16 | "inputmask": "^5.0.8",
17 | "jwt-decode": "^3.1.2",
18 | "react": "^18.2.0",
19 | "react-dom": "^18.2.0",
20 | "react-router-dom": "^6.15.0",
21 | "react-scripts": "5.0.1",
22 | "react-transition-group": "^4.4.5",
23 | "socket.io-client": "^4.7.2",
24 | "typescript": "^5.1.6",
25 | "uuid": "^9.0.0",
26 | "validator": "^13.11.0",
27 | "web-vitals": "^2.1.4"
28 | },
29 | "scripts": {
30 | "start": "react-scripts start",
31 | "build": "react-scripts build",
32 | "test": "react-scripts test",
33 | "eject": "react-scripts eject"
34 | },
35 | "eslintConfig": {
36 | "extends": [
37 | "react-app",
38 | "react-app/jest"
39 | ]
40 | },
41 | "browserslist": {
42 | "production": [
43 | ">0.2%",
44 | "not dead",
45 | "not op_mini all"
46 | ],
47 | "development": [
48 | "last 1 chrome version",
49 | "last 1 firefox version",
50 | "last 1 safari version"
51 | ]
52 | },
53 | "devDependencies": {
54 | "tailwindcss": "^3.3.3"
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/client/googledocs/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/3069f795387d0afc17062e2ad9d7e97588029ee8/client/googledocs/public/favicon.ico
--------------------------------------------------------------------------------
/client/googledocs/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/client/googledocs/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/3069f795387d0afc17062e2ad9d7e97588029ee8/client/googledocs/public/logo192.png
--------------------------------------------------------------------------------
/client/googledocs/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/3069f795387d0afc17062e2ad9d7e97588029ee8/client/googledocs/public/logo512.png
--------------------------------------------------------------------------------
/client/googledocs/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/client/googledocs/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/client/googledocs/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/client/googledocs/src/App.js:
--------------------------------------------------------------------------------
1 | import "./App.css";
2 |
3 | function App() {
4 | return (
5 |
6 | Google Docs Frontend Application
7 |
8 | );
9 | }
10 |
11 | export default App;
12 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/create-document-button/create-document-btn.tsx:
--------------------------------------------------------------------------------
1 | import { lazy, useContext, useState } from "react";
2 | import { ToastContext } from "../../../contexts/toast-context";
3 | import useAuth from "../../../hooks/use-auth";
4 | import { useNavigate } from "react-router-dom";
5 | import DocumentService from "../../../services/document-service";
6 | import DocumentInterface from "../../../types/interfaces/document";
7 | import { PlusIcon } from "@heroicons/react/outline";
8 | import Spinner from "../spinner/spinner";
9 |
10 | const CreateDocumentButton = () => {
11 | const { error } = useContext(ToastContext);
12 | const { accessToken } = useAuth();
13 | const [loading, setLoading] = useState(false);
14 | const navigate = useNavigate();
15 |
16 | const handleDocumentCreateBtnClick = async () => {
17 | if (accessToken === null) return;
18 |
19 | setLoading(true);
20 |
21 | try {
22 | const response = await DocumentService.create(accessToken);
23 | const { id } = response.data as DocumentInterface;
24 |
25 | navigate(`/document/${id}`);
26 | } catch (err) {
27 | error("Unable to create a new document. Please try again");
28 | } finally {
29 | setLoading(false);
30 | }
31 | };
32 |
33 | return (
34 |
35 |
36 |
Start a new document
37 |
38 |
39 |
49 |
Blank
50 |
51 |
52 |
53 |
54 | );
55 | };
56 |
57 | export default CreateDocumentButton;
58 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/create-document-button/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./create-document-btn";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-card/document-card.tsx:
--------------------------------------------------------------------------------
1 | import { useNavigate } from "react-router-dom";
2 | import useAuth from "../../../hooks/use-auth";
3 | import DocumentInterface from "../../../types/interfaces/document";
4 | import { MouseEvent } from "react";
5 | import DocumentMenuButton from "../document-menu-button/document-menu-button";
6 |
7 | interface DocumentCardProps {
8 | document: DocumentInterface;
9 | setDocuments: Function;
10 | }
11 |
12 | const DocumentCard = ({ document, setDocuments }: DocumentCardProps) => {
13 | const { userId } = useAuth();
14 | const navigate = useNavigate();
15 |
16 | const handleDocumentBtnClick = (
17 | event: MouseEvent,
18 | documentId: number
19 | ) => {
20 | const classList = (event.target as HTMLDivElement).classList;
21 | if (
22 | !classList.contains(`document-menu-btn-${documentId}`) &&
23 | !classList.contains("document-menu")
24 | ) {
25 | navigate(`/document/${documentId}`);
26 | }
27 | };
28 |
29 | const skeleton = (
30 | <>
31 | {Array.from({ length: 18 }, (x, i) => i).map((i) => {
32 | return (
33 |
38 | );
39 | })}
40 | >
41 | );
42 |
43 | return (
44 | handleDocumentBtnClick(event, document.id)}
46 | key={document.id}
47 | className="text-left cursor-pointer"
48 | >
49 |
50 |
51 | {skeleton}
52 |
53 |
54 |
{document.title}
55 |
56 |
57 |
71 |
72 | {new Date(document.updatedAt).toLocaleDateString("en-US", {
73 | month: "short",
74 | day: "numeric",
75 | year: "numeric",
76 | })}
77 |
78 |
79 | {document.userId === userId && (
80 |
84 | )}
85 |
86 |
87 |
88 |
89 | );
90 | };
91 |
92 | export default DocumentCard;
93 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-card/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-card";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-menu-button/document-menu-button.tsx:
--------------------------------------------------------------------------------
1 | import { FocusEvent, useContext, useRef, useState } from "react";
2 | import useAuth from "../../../hooks/use-auth";
3 | import { ToastContext } from "../../../contexts/toast-context";
4 | import DocumentService from "../../../services/document-service";
5 | import DocumentInterface from "../../../types/interfaces/document";
6 | import { CSSTransition } from "react-transition-group";
7 |
8 | interface DocumentMenuButtonProps {
9 | documentId: number;
10 | setDocuments: Function;
11 | }
12 |
13 | const DocumentMenuButton = ({
14 | documentId,
15 | setDocuments,
16 | }: DocumentMenuButtonProps) => {
17 | const { accessToken } = useAuth();
18 |
19 | const [loading, setLoading] = useState(false);
20 | const dropdownRef = useRef(null);
21 | const [showDropdown, setShowDropdown] = useState(false);
22 | const { error } = useContext(ToastContext);
23 |
24 | const handleDeleteBtnClick = async () => {
25 | if (accessToken === null) return;
26 |
27 | setLoading(true);
28 |
29 | try {
30 | await DocumentService.delete(accessToken, documentId);
31 | setDocuments((allDocuments: Array) =>
32 | allDocuments.filter((document) => document.id !== documentId)
33 | );
34 | } catch (err) {
35 | error("Unable to delete document. Please try again.");
36 | } finally {
37 | setLoading(false);
38 | }
39 | };
40 |
41 | const handleMenuBtnBlur = (event: FocusEvent) => {
42 | const classList = (event.target as HTMLButtonElement).classList;
43 |
44 | if (!classList.contains("document-menu")) {
45 | setShowDropdown(false);
46 | }
47 | };
48 |
49 | return (
50 |
53 |
74 |
85 | (!loading ? handleDeleteBtnClick() : () => {})}
87 | className="w-full text-black hover:bg-gray-100 text-sm px-6 py-1 text-left document-menu"
88 | >
89 | Delete
90 |
91 |
92 | }
93 | />
94 |
95 | );
96 | };
97 |
98 | export default DocumentMenuButton;
99 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-menu-button/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-menu-button";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-searchbar/document-searchbar.tsx:
--------------------------------------------------------------------------------
1 | import { SearchIcon } from "@heroicons/react/outline";
2 | import { useState } from "react";
3 |
4 | const DocumentSearchBar = () => {
5 | const [isFocused, setIsFocused] = useState(false);
6 |
7 | return (
8 |
13 |
14 |
15 |
16 |
setIsFocused(true)}
18 | onBlur={() => setIsFocused(false)}
19 | type="text"
20 | className={`${
21 | isFocused ? "bg-white" : "bg-gray-100"
22 | }w-full h-full pr-4 font-medium`}
23 | placeholder="Search"
24 | name=""
25 | id=""
26 | />
27 |
28 | );
29 | };
30 |
31 | export default DocumentSearchBar;
32 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/document-searchbar/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-searchbar";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/errors/errors.tsx:
--------------------------------------------------------------------------------
1 | interface ErrorsProps {
2 | errors: Array;
3 | }
4 |
5 | const Errors = ({ errors }: ErrorsProps) => {
6 | return errors.length ? (
7 |
8 | {errors.map((error) => {
9 | return (
10 |
11 | {error}
12 |
13 | );
14 | })}
15 |
16 | ) : (
17 | <>>
18 | );
19 | };
20 |
21 | export default Errors;
22 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/errors/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./errors";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/font-select/font-select.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useRef, useState } from "react";
2 | import { EditorContext } from "../../../contexts/editor-context";
3 | import { ChevronDownIcon } from "@heroicons/react/outline";
4 | import { CSSTransition } from "react-transition-group";
5 | import { FONTS } from ".";
6 |
7 | const FontSelect = () => {
8 | const [showTooltip, setShowTooltip] = useState(false);
9 | const [showDropdown, setShowDropdown] = useState(false);
10 | const { currentFont, setCurrentFont } = useContext(EditorContext);
11 | const dropdownRef = useRef(null);
12 |
13 | return (
14 | setShowDropdown(false)}
16 | className="relative flex justify-center items-center"
17 | >
18 |
27 | {showTooltip && !showDropdown && (
28 |
29 |
30 |
31 | Fonts
32 |
33 |
34 | )}
35 |
46 | {FONTS.map((font) => {
47 | return (
48 |
56 | );
57 | })}
58 |
59 | }
60 | />
61 |
62 | );
63 | };
64 |
65 | export default FontSelect;
66 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/font-select/index.ts:
--------------------------------------------------------------------------------
1 | export const FONTS = ["Inter", "Roboto", "Open Sans"];
2 |
3 | export { default } from "./font-select";
4 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/icon-button/icon-button.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 |
3 | interface IconButtonProps {
4 | icon: JSX.Element;
5 | tooltip: string;
6 | onClick: Function;
7 | }
8 |
9 | const IconButton = ({ icon, tooltip, onClick }: IconButtonProps) => {
10 | const [showTooltip, setShowToolTip] = useState(false);
11 |
12 | return (
13 | setShowToolTip(true)}
15 | onMouseLeave={() => setShowToolTip(false)}
16 | className="relative flex justify-center items-center"
17 | >
18 |
24 | {showTooltip && (
25 |
26 |
27 |
28 | {tooltip}
29 |
30 |
31 | )}
32 |
33 | );
34 | };
35 |
36 | export default IconButton;
37 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/icon-button/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./icon-button";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/logo/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./logo";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/logo/logo.tsx:
--------------------------------------------------------------------------------
1 | import { Link } from "react-router-dom";
2 |
3 | const Logo = () => {
4 | return (
5 |
9 |
23 |
24 | );
25 | };
26 |
27 | export default Logo;
28 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/modal/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./modal";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/modal/modal.tsx:
--------------------------------------------------------------------------------
1 | import { useRef, useState } from "react";
2 | import { CSSTransition } from "react-transition-group";
3 |
4 | interface ModalProps {
5 | button: JSX.Element;
6 | content: JSX.Element;
7 | size?: "sm" | "md" | "lg";
8 | }
9 |
10 | const Modal = ({ button, content, size = "md" }: ModalProps) => {
11 | const [showModal, setShowModal] = useState(false);
12 | const contentRef = useRef(null);
13 |
14 | const getSizeClass = () => {
15 | switch (size) {
16 | case "sm":
17 | return "max-w-sm";
18 | case "md":
19 | return "max-w-2xl";
20 | case "lg":
21 | return "max-w-5xl";
22 | }
23 | };
24 |
25 | return (
26 | <>
27 | setShowModal(true)}>{button}
28 |
36 |
40 | {content}
41 |
42 | setShowModal(false)}
44 | className="absolute top-0 left-0 right-0 bottom-0 bg-black opacity-50 z-0"
45 | >
46 |
47 | }
48 | />
49 | >
50 | );
51 | };
52 |
53 | export default Modal;
54 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/spinner/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./spinner";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/spinner/spinner.tsx:
--------------------------------------------------------------------------------
1 | interface SpinnerProps {
2 | size: "sm" | "md" | "lg";
3 | className?: string;
4 | }
5 |
6 | const Spinner = ({ size, className }: SpinnerProps) => {
7 | const getSpinnerSize = () => {
8 | switch (size) {
9 | case "sm":
10 | return "w-4 h-4";
11 | case "md":
12 | return "w-5 h-5";
13 | case "lg":
14 | return "w-7 h-7";
15 | }
16 | };
17 |
18 | const getSpinnerDivSize = () => {
19 | switch (size) {
20 | case "sm":
21 | return "w-4 h-4 border-2 margin-2 border-white";
22 | case "md":
23 | return "w-5 h-5 border-2 margin-2 border-white";
24 | case "lg":
25 | return "w-7 h-7 border-2 margin-2 border-white";
26 | }
27 | };
28 |
29 | return (
30 |
35 | );
36 | };
37 |
38 | export default Spinner;
39 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/text-field/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./text-field";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/text-field/text-field.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useRef, useState } from "react";
2 | import InputProps from "../../../types/interfaces/input";
3 | import InputMask from "inputmask";
4 | import { EyeIcon, EyeOffIcon } from "@heroicons/react/outline";
5 | import { ExclamationCircleIcon } from "@heroicons/react/solid";
6 | import Errors from "../errors/errors";
7 |
8 | interface TextFieldProps extends InputProps {
9 | value?: string | number;
10 | onInput?: Function;
11 | type?: "text" | "password" | "textarea";
12 | mask?: string;
13 | icon?: JSX.Element;
14 | color?: "primary" | "secondary";
15 | }
16 |
17 | const TEXT_FIELD_CLASSES = {
18 | primary: "bg-white dark:bg-slate-800",
19 | secondary: "bg-slate-50 dark:bg-slate-700",
20 | };
21 |
22 | const TextField = ({
23 | value,
24 | onInput = () => alert("onInput not registered"),
25 | type = "text",
26 | label,
27 | placeholder,
28 | errors = [],
29 | mask,
30 | icon,
31 | color = "primary",
32 | }: TextFieldProps) => {
33 | const textFieldRef = useRef(null);
34 | const [showPassword, setShowPassword] = useState(false);
35 | const [isFocused, setIsFocused] = useState(false);
36 |
37 | useEffect(() => {
38 | if (textFieldRef && textFieldRef.current && mask) {
39 | const inputMask = new InputMask(mask);
40 | inputMask.mask(textFieldRef.current);
41 | }
42 | }, [mask]);
43 |
44 | return (
45 |
46 | {label &&
}
47 |
58 |
{icon}
59 | {type !== "textarea" ? (
60 |
61 | onInput((e.target as HTMLTextAreaElement).value)}
65 | onFocus={() => setIsFocused(true)}
66 | onBlur={() => setIsFocused(false)}
67 | value={value}
68 | className={`${TEXT_FIELD_CLASSES[color]} w-full p-2 rounded`}
69 | placeholder={placeholder && placeholder}
70 | />
71 | {type === "password" && (
72 |
83 | )}
84 |
85 | ) : (
86 |
102 |
103 |
104 | );
105 | };
106 |
107 | export default TextField;
108 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/toast/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./toast";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/toast/toast.tsx:
--------------------------------------------------------------------------------
1 | import { MouseEvent, useContext } from "react";
2 | import ToastInterface from "../../../types/interfaces/toast";
3 | import { ToastContext } from "../../../contexts/toast-context";
4 |
5 | const TOAST_CLASSES = {
6 | primary: "toast-primary",
7 | secondary: "toast-secondary",
8 | success: "toast-success",
9 | warning: "toast-warning",
10 | danger: "toast-danger",
11 | };
12 |
13 | const Toast = ({ id, color, title, body, actions }: ToastInterface) => {
14 | const { removeToast } = useContext(ToastContext);
15 |
16 | const handleToastClick = (e: MouseEvent) => {
17 | const classListArr = Array.from((e.target as HTMLButtonElement).classList);
18 | if (!classListArr.includes("action")) removeToast(id);
19 | };
20 |
21 | return (
22 |
26 |
27 | {title &&
{title}
}
28 | {body &&
{body}
}
29 |
30 | {actions?.map((a, index) => {
31 | return (
32 |
39 | );
40 | })}
41 |
42 |
43 |
44 | );
45 | };
46 |
47 | export default Toast;
48 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/user-dropdown/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./user-dropdown";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/atoms/user-dropdown/user-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useRef, useState } from "react";
2 | import { ToastContext } from "../../../contexts/toast-context";
3 | import useAuth from "../../../hooks/use-auth";
4 | import { useNavigate } from "react-router-dom";
5 | import useRandomBackground from "../../../hooks/use-random-background";
6 | import { CSSTransition } from "react-transition-group";
7 |
8 | const UserDropDown = () => {
9 | const [showDropDown, setShowDropDown] = useState(false);
10 | const { backgroundColor } = useRandomBackground();
11 | const dropdownRef = useRef(null);
12 | const { success } = useContext(ToastContext);
13 | const { email, logout } = useAuth();
14 | const navigate = useNavigate();
15 |
16 | const logoutUser = async () => {
17 | await logout();
18 | success("Successfully logged out!");
19 | navigate("/login");
20 | };
21 |
22 | return (
23 | setShowDropDown(false)}>
24 |
30 |
41 |
47 |
48 | }
49 | />
50 |
51 | );
52 | };
53 |
54 | export default UserDropDown;
55 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/auth-route/auth-route.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect } from "react";
2 | import useAuth from "../../../hooks/use-auth";
3 | import { Navigate } from "react-router-dom";
4 |
5 | interface AuthRouteProps {
6 | element: JSX.Element;
7 | }
8 |
9 | const AuthRoute = ({ element }: AuthRouteProps) => {
10 | const { loadingAuth, isAuthenticated, refreshAccessToken } = useAuth();
11 |
12 | useEffect(() => {
13 | refreshAccessToken();
14 | }, []);
15 |
16 | if (loadingAuth) {
17 | return <>>;
18 | } else {
19 | if (isAuthenticated) return element;
20 | else return ;
21 | }
22 | };
23 |
24 | export default AuthRoute;
25 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/auth-route/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./auth-route";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/document-menu-bar/document-menu-bar.tsx:
--------------------------------------------------------------------------------
1 | import { ChangeEvent, FocusEvent, useContext } from "react";
2 | import useAuth from "../../../hooks/use-auth";
3 | import { DocumentContext } from "../../../contexts/document-context";
4 | import DocumentInterface from "../../../types/interfaces/document";
5 | import DocumentService from "../../../services/document-service";
6 | import Logo from "../../atoms/logo/logo";
7 | import UserDropDown from "../../atoms/user-dropdown/user-dropdown";
8 | import useRandomBackground from "../../../hooks/use-random-background";
9 | import ShareDocumentModal from "../share-document-modal/share-document-modal";
10 |
11 | const CurrentUsers = () => {
12 | const { email } = useAuth();
13 | const { currentUsers } = useContext(DocumentContext);
14 | const { backgroundColor } = useRandomBackground();
15 | return (
16 | <>
17 | {Array.from(currentUsers)
18 | .filter((currentUser) => currentUser !== email)
19 | .map((currentUser) => {
20 | return (
21 |
25 | {currentUser[0]}
26 |
27 | );
28 | })}
29 | >
30 | );
31 | };
32 |
33 | const DocumentMenuBar = () => {
34 | const { accessToken, userId } = useAuth();
35 |
36 | const {
37 | document,
38 | saving,
39 | setDocumentTitle,
40 | setDocument,
41 | setSaving,
42 | setErrors,
43 | } = useContext(DocumentContext);
44 |
45 | const handleTitleInputChange = (event: ChangeEvent) => {
46 | const title = event.target.value;
47 | setDocumentTitle(title);
48 | };
49 |
50 | const handleTitleInputBlur = async (event: FocusEvent) => {
51 | if (accessToken === null || document === null) return;
52 |
53 | setSaving(true);
54 |
55 | const title = (event.target as HTMLInputElement).value;
56 | const updatedDocument = {
57 | ...document,
58 | title,
59 | } as DocumentInterface;
60 | console.log(saving);
61 | console.log(document.id);
62 | console.log(updatedDocument);
63 | try {
64 | await DocumentService.update(accessToken, updatedDocument);
65 | } catch (error) {
66 | setErrors(["There was an error saving the document. Please try again."]);
67 | } finally {
68 | setDocument(updatedDocument);
69 | setSaving(false);
70 | }
71 | };
72 |
73 | return (
74 |
75 |
76 |
77 |
78 |
handleTitleInputBlur(event)}
82 | onChange={(event) => handleTitleInputChange(event)}
83 | value={document?.title ? document?.title : ""}
84 | className="font-medium text-lg px-2 pt-2"
85 | name=""
86 | id=""
87 | placeholder="Untitled Document"
88 | />
89 |
90 |
93 |
96 |
99 |
102 |
105 |
108 |
111 |
114 | {saving &&
Saving...
}
115 |
116 |
117 |
118 |
119 | {document !== null && document.userId === userId && (
120 |
121 | )}
122 |
123 |
124 |
125 |
126 |
127 |
128 | );
129 | };
130 |
131 | export default DocumentMenuBar;
132 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/document-menu-bar/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-menu-bar";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/documents-list/documents-list.tsx:
--------------------------------------------------------------------------------
1 | import DocumentInterface from "../../../types/interfaces/document";
2 | import DocumentCard from "../../atoms/document-card/document-card";
3 |
4 | interface DocumentsListProps {
5 | title: string;
6 | documents: Array;
7 | setDocuments: Function;
8 | }
9 |
10 | const DocumentsList = ({
11 | title,
12 | documents,
13 | setDocuments,
14 | }: DocumentsListProps) => {
15 | return (
16 |
17 |
18 |
{title}
19 |
20 | {documents
21 | .sort((a, b) => {
22 | return (
23 | new Date(b.updatedAt).getTime() -
24 | new Date(a.updatedAt).getTime()
25 | );
26 | })
27 | .map((document) => {
28 | return (
29 |
34 | );
35 | })}
36 |
37 |
38 |
39 | );
40 | };
41 |
42 | export default DocumentsList;
43 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/documents-list/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./documents-list";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/editor-toolbar/editor-toolbar.tsx:
--------------------------------------------------------------------------------
1 | import { useContext } from "react";
2 | import { EditorContext } from "../../../contexts/editor-context";
3 | import { EditorState } from "draft-js";
4 | import IconButton from "../../atoms/icon-button/icon-button";
5 | import { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/outline";
6 | import FontSelect from "../../atoms/font-select/font-select";
7 |
8 | const EditorToolbar = () => {
9 | const { editorState, setEditorState } = useContext(EditorContext);
10 |
11 | const handleUndoBtnClick = () => {
12 | setEditorState(EditorState.undo(editorState));
13 | };
14 |
15 | const handleRedoBtnClick = () => {
16 | setEditorState(EditorState.redo(editorState));
17 | };
18 |
19 | return (
20 |
21 |
}
24 | tooltip="Undo"
25 | />
26 |
}
29 | tooltip="Redo"
30 | />
31 |
32 |
33 |
34 | );
35 | };
36 |
37 | export default EditorToolbar;
38 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/editor-toolbar/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./editor-toolbar";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/share-document-modal/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./share-document-modal";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/share-document-modal/share-document-modal.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ChangeEvent,
3 | KeyboardEvent,
4 | useContext,
5 | useRef,
6 | useState,
7 | } from "react";
8 | import { DocumentContext } from "../../../contexts/document-context";
9 | import useAuth from "../../../hooks/use-auth";
10 | import { ToastContext } from "../../../contexts/toast-context";
11 | import validator from "validator";
12 | import PermissionEnum from "../../../types/enums/permission-enum";
13 | import DocumentUserService from "../../../services/document-user-service";
14 | import DocumentUser from "../../../types/interfaces/document-user";
15 | import DocumentInterface from "../../../types/interfaces/document";
16 | import Modal from "../../atoms/modal/modal";
17 | import { LinkIcon, UserAddIcon } from "@heroicons/react/outline";
18 | import SharedUsers from "../shared-users/shared-users";
19 | import Spinner from "../../atoms/spinner/spinner";
20 |
21 | const ShareDocumentModal = () => {
22 | const { document, saving, saveDocument, setDocument } =
23 | useContext(DocumentContext);
24 | const copyLinkInputRef = useRef(null);
25 | const [email, setEmail] = useState(null);
26 | const { accessToken } = useAuth();
27 | const { success, error } = useContext(ToastContext);
28 | const [loading, setLoading] = useState(false);
29 |
30 | const shareDocument = async () => {
31 | if (
32 | email === null ||
33 | !validator.isEmail(email) ||
34 | accessToken === null ||
35 | document === null
36 | )
37 | return;
38 |
39 | const payload = {
40 | documentId: document.id,
41 | email: email,
42 | permission: PermissionEnum.EDIT,
43 | };
44 |
45 | setLoading(true);
46 |
47 | try {
48 | const response = await DocumentUserService.create(accessToken, payload);
49 | const documentUser = response.data as DocumentUser;
50 | documentUser.user = { email };
51 |
52 | success(`Successfully shared document with ${email}`);
53 |
54 | setDocument({
55 | ...document,
56 | users: [...document.users, documentUser],
57 | } as DocumentInterface);
58 | setEmail("");
59 | } catch (err) {
60 | error(`Unable to share this document with ${email}. Please try again`);
61 | } finally {
62 | setLoading(false);
63 | }
64 | };
65 |
66 | const handleShareEmailInputChange = (event: ChangeEvent) => {
67 | setEmail((event.target as HTMLInputElement).value);
68 | };
69 |
70 | const handleCopyLinkBtnClick = () => {
71 | if (copyLinkInputRef === null || copyLinkInputRef.current === null) return;
72 |
73 | const url = window.location.href;
74 | copyLinkInputRef.current.value = url;
75 | copyLinkInputRef.current.focus();
76 | copyLinkInputRef.current.select();
77 | window.document.execCommand("copy");
78 | };
79 |
80 | const handleOnKeyPress = async (event: KeyboardEvent) => {
81 | if (event.key === "Enter") await shareDocument();
82 | };
83 |
84 | const updateIsPublic = (isPublic: boolean) => {
85 | const updatedDocument = {
86 | ...document,
87 | isPublic: isPublic,
88 | } as DocumentInterface;
89 |
90 | saveDocument(updatedDocument);
91 | };
92 |
93 | const handleShareBtnClick = async () => {
94 | await shareDocument();
95 | };
96 |
97 | const alreadyShared =
98 | document === null ||
99 | (document !== null &&
100 | document.users.filter((documentUser) => documentUser.user.email === email)
101 | .length > 0);
102 |
103 | const publicAccessBtn = (
104 |
105 |
115 |
116 | Public
117 | Anyone with this link can view
118 |
119 |
120 | );
121 |
122 | const restrictedAccessBtn = (
123 |
124 |
134 |
135 | Restricted
136 |
137 | Only people added can open with this link
138 |
139 |
140 |
141 | );
142 |
143 | return (
144 |
147 |
159 | Share
160 |
161 | }
162 | content={
163 | document === null ? (
164 | <>>
165 | ) : (
166 | handleOnKeyPress(event)}
168 | className="space-y-4 text-sm"
169 | >
170 |
171 |
172 |
173 |
174 |
175 |
Share with people
176 |
177 |
186 |
190 |
191 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
Get Link
216 |
217 |
218 |
219 |
220 | {document.isPublic ? publicAccessBtn : restrictedAccessBtn}
221 |
222 |
227 |
233 |
234 |
235 |
236 |
237 | )
238 | }
239 | />
240 | );
241 | };
242 |
243 | export default ShareDocumentModal;
244 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/shared-users/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./shared-users";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/molecules/shared-users/shared-users.tsx:
--------------------------------------------------------------------------------
1 | import { Dispatch, SetStateAction, useContext, useState } from "react";
2 | import DocumentUser from "../../../types/interfaces/document-user";
3 | import DocumentInterface from "../../../types/interfaces/document";
4 | import useRandomBackground from "../../../hooks/use-random-background";
5 | import useAuth from "../../../hooks/use-auth";
6 | import { ToastContext } from "../../../contexts/toast-context";
7 | import { DocumentContext } from "../../../contexts/document-context";
8 | import DocumentService from "../../../services/document-service";
9 | import DocumentUserService from "../../../services/document-user-service";
10 |
11 | interface SharedUserProps {
12 | documentUsers: Array;
13 | setDocument: Dispatch>;
14 | }
15 |
16 | const SharedUsers = ({ documentUsers, setDocument }: SharedUserProps) => {
17 | const { backgroundColor } = useRandomBackground();
18 |
19 | const { backgroundColor: sharedUserBackgroundColor } = useRandomBackground();
20 | const { accessToken, email } = useAuth();
21 | const [loading, setLoading] = useState(false);
22 | const { addToast } = useContext(ToastContext);
23 | const { document } = useContext(DocumentContext);
24 |
25 | const removeDocumentUser = async (payload: {
26 | documentId: number;
27 | userId: number;
28 | }) => {
29 | if (!accessToken) return;
30 |
31 | setLoading(true);
32 |
33 | try {
34 | await DocumentUserService.delete(accessToken, payload);
35 |
36 | setDocument({
37 | ...document,
38 | users: document?.users.filter(
39 | (documentUser) => documentUser.userId !== payload.userId
40 | ) as Array,
41 | } as DocumentInterface);
42 | } catch {
43 | addToast({
44 | color: "danger",
45 | title: "Unable to remove user",
46 | body: "Please try again.",
47 | });
48 | } finally {
49 | setLoading(false);
50 | }
51 | };
52 |
53 | return (
54 |
55 |
56 |
57 |
60 | {email !== null && email[0]}
61 |
62 |
{email !== null && email} (you)
63 |
64 |
Owner
65 |
66 | {documentUsers.map((documentUser) => {
67 | return (
68 |
72 |
73 |
76 | {documentUser.user.email[0]}
77 |
78 |
{documentUser.user.email}
79 |
80 |
92 |
93 | );
94 | })}
95 |
96 | );
97 | };
98 |
99 | export default SharedUsers;
100 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-create-header/document-create-header.tsx:
--------------------------------------------------------------------------------
1 | import DocumentSearchBar from "../../atoms/document-searchbar/document-searchbar";
2 | import Logo from "../../atoms/logo/logo";
3 | import UserDropDown from "../../atoms/user-dropdown/user-dropdown";
4 |
5 | const DocumentCreateHeader = () => {
6 | return (
7 |
8 |
9 |
10 |
11 |
12 | );
13 | };
14 |
15 | export default DocumentCreateHeader;
16 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-create-header/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-create-header";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-editor/document-editor.tsx:
--------------------------------------------------------------------------------
1 | import { useContext } from "react";
2 | import { EditorContext } from "../../../contexts/editor-context";
3 | import { Editor } from "draft-js";
4 |
5 | const DocumentEditor = () => {
6 | const { editorState, editorRef, handleEditorChange, focusEditor } =
7 | useContext(EditorContext);
8 |
9 | return (
10 |
15 |
20 |
21 | );
22 | };
23 |
24 | export default DocumentEditor;
25 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-editor/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-editor";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-header/document-header.tsx:
--------------------------------------------------------------------------------
1 | import { MutableRefObject } from "react";
2 | import DocumentMenuBar from "../../molecules/document-menu-bar/document-menu-bar";
3 | import EditorToolbar from "../../molecules/editor-toolbar/editor-toolbar";
4 |
5 | interface DocumentHeaderProps {
6 | documentHeaderRef: MutableRefObject;
7 | }
8 |
9 | const DocumentHeader = ({ documentHeaderRef }: DocumentHeaderProps) => {
10 | return (
11 |
15 |
16 |
17 |
18 | );
19 | };
20 |
21 | export default DocumentHeader;
22 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/document-header/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./document-header";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/toast-manager/index.ts:
--------------------------------------------------------------------------------
1 | export { default } from "./toast-manager";
2 |
--------------------------------------------------------------------------------
/client/googledocs/src/components/organisms/toast-manager/toast-manager.tsx:
--------------------------------------------------------------------------------
1 | import { useContext } from "react";
2 | import { ToastContext } from "../../../contexts/toast-context";
3 | import useWindowSize from "../../../hooks/use-window-size";
4 | import { TransitionGroup, CSSTransition } from "react-transition-group";
5 | import Toast from "../../atoms/toast/toast";
6 |
7 | const ToastManager = () => {
8 | const { toasts } = useContext(ToastContext);
9 | const { heightStr } = useWindowSize();
10 |
11 | return (
12 |
16 |
17 | {toasts.reverse().map((toast) => {
18 | return (
19 | }
25 | />
26 | );
27 | })}
28 |
29 |
30 | );
31 | };
32 |
33 | export default ToastManager;
34 |
--------------------------------------------------------------------------------
/client/googledocs/src/contexts/auth-context.tsx:
--------------------------------------------------------------------------------
1 | import { Dispatch, SetStateAction, createContext, useState } from "react";
2 |
3 | interface AuthContextInterface {
4 | accessToken: string | null;
5 | setAccessToken: Dispatch>;
6 | isAuthenticated: boolean;
7 | setIsAuthenticated: Dispatch>;
8 | loading: boolean;
9 | setLoading: Dispatch>;
10 | loadingAuth: boolean;
11 | setLoadingAuth: Dispatch>;
12 | errors: Array;
13 | setErrors: Dispatch>>;
14 | userId: number | null;
15 | setUserId: Dispatch>;
16 | email: string | null;
17 | setEmail: Dispatch>;
18 | }
19 |
20 | const defaultValues = {
21 | accessToken: null,
22 | setAccessToken: () => {},
23 | isAuthenticated: false,
24 | setIsAuthenticated: () => {},
25 | loading: false,
26 | setLoading: () => {},
27 | loadingAuth: true,
28 | setLoadingAuth: () => {},
29 | errors: [],
30 | setErrors: () => {},
31 | userId: null,
32 | setUserId: () => {},
33 | email: null,
34 | setEmail: () => {},
35 | };
36 |
37 | export const AuthContext = createContext(defaultValues);
38 |
39 | interface AuthProviderInterface {
40 | children: JSX.Element;
41 | }
42 |
43 | export const AuthProvider = ({ children }: AuthProviderInterface) => {
44 | const [accessToken, setAccessToken] = useState(
45 | defaultValues.accessToken
46 | );
47 | const [isAuthenticated, setIsAuthenticated] = useState(
48 | defaultValues.isAuthenticated
49 | );
50 | const [loading, setLoading] = useState(defaultValues.loading);
51 | const [loadingAuth, setLoadingAuth] = useState(
52 | defaultValues.loadingAuth
53 | );
54 | const [errors, setErrors] = useState>(defaultValues.errors);
55 | const [userId, setUserId] = useState(defaultValues.userId);
56 | const [email, setEmail] = useState(defaultValues.email);
57 |
58 | return (
59 |
77 | {children}
78 |
79 | );
80 | };
81 |
--------------------------------------------------------------------------------
/client/googledocs/src/contexts/document-context.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Dispatch,
3 | SetStateAction,
4 | createContext,
5 | useContext,
6 | useEffect,
7 | useState,
8 | } from "react";
9 | import DocumentInterface from "../types/interfaces/document";
10 | import { ToastContext } from "./toast-context";
11 | import useAuth from "../hooks/use-auth";
12 | import DocumentService from "../services/document-service";
13 |
14 | interface DocumentContextInterface {
15 | document: DocumentInterface | null;
16 | setDocument: Dispatch>;
17 | errors: Array;
18 | setErrors: Dispatch>>;
19 | loading: boolean;
20 | setLoading: Dispatch>;
21 | saving: boolean;
22 | setSaving: Dispatch>;
23 | currentUsers: Set;
24 | setCurrentUsers: Dispatch>>;
25 | setDocumentTitle: (title: string) => void;
26 | saveDocument: (updatedDocument: DocumentInterface) => Promise;
27 | }
28 |
29 | const defaultValues = {
30 | document: null,
31 | setDocument: () => {},
32 | errors: [],
33 | setErrors: () => {},
34 | loading: false,
35 | setLoading: () => {},
36 | saving: false,
37 | setSaving: () => {},
38 | currentUsers: new Set(),
39 | setCurrentUsers: () => {},
40 | setDocumentTitle: () => {},
41 | saveDocument: async () => {},
42 | };
43 |
44 | export const DocumentContext =
45 | createContext(defaultValues);
46 |
47 | interface DocumentProviderInterface {
48 | children: JSX.Element;
49 | }
50 |
51 | export const DocumentProvider = ({ children }: DocumentProviderInterface) => {
52 | const { error } = useContext(ToastContext);
53 | const { accessToken } = useAuth();
54 |
55 | const [document, setDocument] = useState(
56 | defaultValues.document
57 | );
58 | const [errors, setErrors] = useState>(defaultValues.errors);
59 | const [loading, setLoading] = useState(defaultValues.loading);
60 | const [saving, setSaving] = useState(defaultValues.saving);
61 | const [currentUsers, setCurrentUsers] = useState(defaultValues.currentUsers);
62 |
63 | const setDocumentTitle = (title: string) => {
64 | setDocument({ ...document, title } as DocumentInterface);
65 | };
66 |
67 | const saveDocument = async (updatedDocument: DocumentInterface) => {
68 | if (accessToken === null) return;
69 |
70 | setSaving(true);
71 |
72 | try {
73 | await DocumentService.update(accessToken, updatedDocument);
74 | setDocument(updatedDocument);
75 | } catch (error) {
76 | setErrors(["There was an error saving the document. Please try again."]);
77 | } finally {
78 | setSaving(false);
79 | }
80 | };
81 |
82 | useEffect(() => {
83 | if (errors.length) {
84 | errors.forEach((err) => {
85 | error(err);
86 | });
87 | }
88 | }, [errors]);
89 |
90 | return (
91 |
107 | {children}
108 |
109 | );
110 | };
111 |
--------------------------------------------------------------------------------
/client/googledocs/src/contexts/editor-context.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | EditorState,
3 | Editor,
4 | convertToRaw,
5 | convertFromRaw,
6 | RawDraftContentState,
7 | } from "draft-js";
8 | import {
9 | Dispatch,
10 | MutableRefObject,
11 | SetStateAction,
12 | createContext,
13 | useContext,
14 | useEffect,
15 | useRef,
16 | useState,
17 | } from "react";
18 | import { FONTS } from "../components/atoms/font-select";
19 | import { DocumentContext } from "./document-context";
20 | import { ToastContext } from "./toast-context";
21 | import useAuth from "../hooks/use-auth";
22 | import SocketEvent from "../types/enums/socket-events-enum";
23 | import DocumentInterface from "../types/interfaces/document";
24 | import { io } from "socket.io-client";
25 | import { BASE_URL } from "../services/api";
26 |
27 | interface EditorContextInterface {
28 | editorState: EditorState;
29 | setEditorState: Dispatch>;
30 | socket: null | MutableRefObject;
31 | documentRendered: boolean;
32 | setDocumentRendered: Dispatch>;
33 | editorRef: null | MutableRefObject;
34 | handleEditorChange: (editorState: EditorState) => void;
35 | focusEditor: () => void;
36 | currentFont: string;
37 | setCurrentFont: Dispatch>;
38 | }
39 |
40 | const defaultValues = {
41 | editorState: EditorState.createEmpty(),
42 | setEditorState: () => {},
43 | socket: null,
44 | documentRendered: false,
45 | setDocumentRendered: () => {},
46 | editorRef: null,
47 | handleEditorChange: () => {},
48 | focusEditor: () => {},
49 | currentFont: FONTS[0],
50 | setCurrentFont: () => {},
51 | };
52 |
53 | export const EditorContext =
54 | createContext(defaultValues);
55 |
56 | interface EditorProviderInterface {
57 | children: JSX.Element;
58 | }
59 |
60 | const DEFAULT_SAVE_TIME = 1500;
61 | let saveInterval: null | NodeJS.Timer = null;
62 |
63 | export const EditorProvider = ({ children }: EditorProviderInterface) => {
64 | const [editorState, setEditorState] = useState(defaultValues.editorState);
65 | const socket = useRef(defaultValues.socket);
66 | const [documentRendered, setDocumentRendered] = useState(
67 | defaultValues.documentRendered
68 | );
69 | const editorRef = useRef(defaultValues.editorRef);
70 | const [currentFont, setCurrentFont] = useState(defaultValues.currentFont);
71 |
72 | const { document, setCurrentUsers, setSaving, setDocument, saveDocument } =
73 | useContext(DocumentContext);
74 | const { error } = useContext(ToastContext);
75 | const { accessToken } = useAuth();
76 |
77 | const focusEditor = () => {
78 | if (editorRef === null || editorRef.current === null) return;
79 |
80 | editorRef.current.focus();
81 | };
82 |
83 | //Send Changes
84 | const handleEditorChange = (editorState: EditorState) => {
85 | setEditorState(EditorState.moveSelectionToEnd(editorState));
86 |
87 | if (socket === null) return;
88 |
89 | const content = convertToRaw(editorState.getCurrentContent());
90 |
91 | socket.current.emit(SocketEvent.SEND_CHANGES, content);
92 |
93 | const updatedDocument = {
94 | ...document,
95 | content: JSON.stringify(content),
96 | } as DocumentInterface;
97 |
98 | setDocument(updatedDocument);
99 |
100 | if (document === null || JSON.stringify(content) === document.content)
101 | return;
102 |
103 | setSaving(true);
104 |
105 | if (saveInterval !== null) {
106 | clearInterval(saveInterval);
107 | }
108 |
109 | saveInterval = setInterval(async () => {
110 | await saveDocument(updatedDocument);
111 | if (saveInterval) clearInterval(saveInterval);
112 | }, DEFAULT_SAVE_TIME);
113 | };
114 |
115 | //Load document content
116 | useEffect(() => {
117 | if (documentRendered || document === null || document.content === null)
118 | return;
119 |
120 | try {
121 | const contentState = convertFromRaw(
122 | JSON.parse(document.content) as RawDraftContentState
123 | );
124 | const newEditorState = EditorState.createWithContent(contentState);
125 | setEditorState(EditorState.moveSelectionToEnd(newEditorState));
126 | } catch {
127 | error("Error when loading document.");
128 | } finally {
129 | setDocumentRendered(true);
130 | }
131 | }, [document]);
132 |
133 | //Connect Socket
134 | useEffect(() => {
135 | if (
136 | document === null ||
137 | accessToken === null ||
138 | socket === null ||
139 | (socket.current !== null && socket.current.connected)
140 | )
141 | return;
142 |
143 | socket.current = io(BASE_URL, {
144 | query: { documentId: document.id, accessToken },
145 | }).connect();
146 | }, [document, socket, accessToken]);
147 |
148 | //Disconnect Socket
149 | useEffect(() => {
150 | return () => {
151 | socket?.current?.disconnect();
152 | };
153 | }, []);
154 |
155 | //Receive Changes
156 | useEffect(() => {
157 | if (socket.current === null) return;
158 |
159 | const handler = (rawDraftContentState: RawDraftContentState) => {
160 | const contentState = convertFromRaw(rawDraftContentState);
161 | const newEditorState = EditorState.createWithContent(contentState);
162 | setEditorState(EditorState.moveSelectionToEnd(newEditorState));
163 | };
164 |
165 | socket.current.on(SocketEvent.RECEIVE_CHANGES, handler);
166 |
167 | return () => {
168 | socket.current.off(SocketEvent.RECEIVE_CHANGES, handler);
169 | };
170 | }, [socket.current]);
171 |
172 | //current users updated
173 | useEffect(() => {
174 | if (socket.current === null) return;
175 |
176 | const handler = (currentUsers: Array) => {
177 | setCurrentUsers(new Set(currentUsers));
178 | };
179 |
180 | socket.current.on(SocketEvent.CURRENT_USERS_UPDATE, handler);
181 |
182 | return () => {
183 | socket.current.off(SocketEvent.CURRENT_USERS_UPDATE, handler);
184 | };
185 | }, [socket.current]);
186 |
187 | return (
188 |
202 | {children}
203 |
204 | );
205 | };
206 |
--------------------------------------------------------------------------------
/client/googledocs/src/contexts/toast-context.tsx:
--------------------------------------------------------------------------------
1 | import { createContext, useState } from "react";
2 | import ActionInterface from "../types/interfaces/action";
3 | import ToastInterface from "../types/interfaces/toast";
4 | import { v4 as uuid } from "uuid";
5 | import ToastManager from "../components/organisms/toast-manager/toast-manager";
6 |
7 | const TOAST_TIMEOUT = 5000;
8 |
9 | interface ToastContextInterface {
10 | toasts: Array;
11 | addToast: (
12 | {
13 | id,
14 | color,
15 | title,
16 | body,
17 | actions,
18 | }: {
19 | id?: string;
20 | color?: ToastInterface["color"];
21 | title?: string;
22 | body?: string;
23 | actions?: Array;
24 | },
25 | duration?: number
26 | ) => void;
27 | removeToast: (id: string) => void;
28 | error: (title: string) => void;
29 | success: (title: string) => void;
30 | }
31 |
32 | const defaultValues = {
33 | toasts: new Array(),
34 | addToast: () => {},
35 | removeToast: () => {},
36 | error: () => {},
37 | success: () => {},
38 | };
39 |
40 | export const ToastContext = createContext(defaultValues);
41 |
42 | interface ToastProviderInterface {
43 | children: JSX.Element;
44 | }
45 |
46 | export const ToastProvider = ({ children }: ToastProviderInterface) => {
47 | const [toasts, setToasts] = useState>(
48 | defaultValues.toasts
49 | );
50 |
51 | const addToast = (
52 | {
53 | id = uuid(),
54 | color = "primary",
55 | title,
56 | body,
57 | actions,
58 | }: {
59 | id?: string;
60 | color?: ToastInterface["color"];
61 | title?: string;
62 | body?: string;
63 | actions?: Array;
64 | },
65 | duration = TOAST_TIMEOUT
66 | ) => {
67 | setToasts((toasts) => [
68 | ...toasts,
69 | {
70 | id,
71 | color,
72 | title,
73 | body,
74 | actions,
75 | },
76 | ]);
77 | setTimeout(() => {
78 | removeToast(id);
79 | }, duration);
80 | };
81 |
82 | const removeToast = (id: string) => {
83 | setToasts((toasts) => toasts.filter((toast) => toast.id !== id));
84 | };
85 |
86 | const error = (title: string) => {
87 | addToast({ color: "danger", title });
88 | };
89 |
90 | const success = (title: string) => {
91 | addToast({ color: "success", title });
92 | };
93 |
94 | return (
95 |
98 | {children}
99 |
100 |
101 | );
102 | };
103 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-auth.tsx:
--------------------------------------------------------------------------------
1 | import { useContext } from "react";
2 | import { AuthContext } from "../contexts/auth-context";
3 | import useLocalStorage from "./use-local-storage";
4 | import jwt_decode from "jwt-decode";
5 | import Token from "../types/interfaces/token";
6 | import AuthService from "../services/auth-service";
7 |
8 | const useAuth = () => {
9 | const {
10 | accessToken,
11 | setAccessToken,
12 | isAuthenticated,
13 | setIsAuthenticated,
14 | loading,
15 | loadingAuth,
16 | setLoadingAuth,
17 | errors,
18 | userId,
19 | setUserId,
20 | email,
21 | setEmail,
22 | } = useContext(AuthContext);
23 |
24 | const [refreshToken, setRefreshToken] = useLocalStorage(
25 | "refreshToken",
26 | null
27 | );
28 |
29 | const login = (accessToken: string, refreshToken: string) => {
30 | const { exp, id, email } = jwt_decode(accessToken);
31 | silentRefresh(exp);
32 | setUserId(id);
33 | setEmail(email);
34 | setAccessToken(accessToken);
35 | setRefreshToken(refreshToken);
36 | setIsAuthenticated(true);
37 | };
38 |
39 | const logout = async () => {
40 | if (!accessToken) return;
41 | try {
42 | await AuthService.logout(accessToken);
43 | } catch {
44 | } finally {
45 | destoryAuth();
46 | }
47 | };
48 |
49 | const silentRefresh = (exp: number) => {
50 | const msExpiration = Math.abs(
51 | new Date().getTime() - new Date(exp * 1000).getTime()
52 | );
53 |
54 | setTimeout(() => {
55 | refreshAccessToken();
56 | }, msExpiration);
57 | };
58 |
59 | const destoryAuth = () => {
60 | setRefreshToken(null);
61 | setAccessToken(null);
62 | setUserId(null);
63 | setEmail(null);
64 | setIsAuthenticated(false);
65 | };
66 |
67 | const refreshAccessToken = async () => {
68 | if (refreshToken === null) {
69 | destoryAuth();
70 | setLoadingAuth(false);
71 | return;
72 | }
73 | try {
74 | const response = await AuthService.refreshToken({ token: refreshToken });
75 | const { accessToken: newAccessToken, refreshToken: newRefreshToken } =
76 | response.data;
77 | login(newAccessToken, newRefreshToken);
78 | } catch (error) {
79 | destoryAuth();
80 | } finally {
81 | setLoadingAuth(false);
82 | }
83 | };
84 |
85 | return {
86 | accessToken,
87 | isAuthenticated,
88 | loading,
89 | loadingAuth,
90 | errors,
91 | userId,
92 | email,
93 | login,
94 | logout,
95 | refreshAccessToken,
96 | };
97 | };
98 |
99 | export default useAuth;
100 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-document.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useEffect, useState } from "react";
2 | import useAuth from "./use-auth";
3 | import { ToastContext } from "../contexts/toast-context";
4 | import DocumentInterface from "../types/interfaces/document";
5 | import DocumentService from "../services/document-service";
6 | import axios, { AxiosError } from "axios";
7 |
8 | const useDocument = (documentId: number) => {
9 | const { accessToken } = useAuth();
10 | const { error } = useContext(ToastContext);
11 | const [loading, setLoading] = useState(false);
12 | const [errors, setErrors] = useState>([]);
13 | const [document, setDocument] = useState(null);
14 |
15 | const loadDocument = async (accessToken: string, documentId: number) => {
16 | setLoading(true);
17 |
18 | try {
19 | const response = await DocumentService.get(accessToken, documentId);
20 | setDocument(response.data as DocumentInterface);
21 | } catch (error: any) {
22 | if (axios.isAxiosError(error)) {
23 | const { response } = error as AxiosError;
24 | if (response?.status === 404) {
25 | setErrors((prev) => [...prev, "Document does not exist"]);
26 | } else {
27 | setErrors((prev) => [
28 | ...prev,
29 | "An unknown error has occurred. Please try again.",
30 | ]);
31 | }
32 | } else {
33 | setErrors((prev) => [
34 | ...prev,
35 | "An unknown error has occurred. Please try again.",
36 | ]);
37 | }
38 | } finally {
39 | setLoading(false);
40 | }
41 | };
42 |
43 | useEffect(() => {
44 | if (accessToken === null) return;
45 |
46 | loadDocument(accessToken, documentId);
47 | }, [accessToken, documentId]);
48 |
49 | useEffect(() => {
50 | if (errors.length) {
51 | errors.forEach((err) => {
52 | error(err);
53 | });
54 | }
55 | }, [errors]);
56 |
57 | return {
58 | document,
59 | errors,
60 | loading,
61 | };
62 | };
63 |
64 | export default useDocument;
65 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-documents.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useEffect, useState } from "react";
2 | import useAuth from "./use-auth";
3 | import DocumentInterface from "../types/interfaces/document";
4 | import { ToastContext } from "../contexts/toast-context";
5 | import DocumentService from "../services/document-service";
6 |
7 | const useDocuments = () => {
8 | const { accessToken } = useAuth();
9 | const [documents, setDocuments] = useState>([]);
10 | const [loading, setLoading] = useState(false);
11 | const { error } = useContext(ToastContext);
12 |
13 | const loadDocuments = async (accessToken: string) => {
14 | setLoading(true);
15 |
16 | try {
17 | const response = await DocumentService.list(accessToken);
18 | setDocuments(response.data as Array);
19 | } catch (err) {
20 | error("Unable to load documents. Please try again.");
21 | } finally {
22 | setLoading(false);
23 | }
24 | };
25 |
26 | useEffect(() => {
27 | if (accessToken === null) return;
28 | loadDocuments(accessToken);
29 | }, [accessToken]);
30 |
31 | return {
32 | documents,
33 | loading,
34 | setDocuments,
35 | setLoading,
36 | };
37 | };
38 |
39 | export default useDocuments;
40 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-local-storage.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 |
3 | const useLocalStorage = (
4 | key: string,
5 | initialValue: T
6 | ): [string, typeof setValue] => {
7 | const [storedValue, setStoredValue] = useState(() => {
8 | try {
9 | const item = window.localStorage.getItem(key);
10 | return item ? JSON.parse(item) : initialValue;
11 | } catch (error) {
12 | return initialValue;
13 | }
14 | });
15 |
16 | const setValue = (value: T): void => {
17 | try {
18 | const valueToStore =
19 | value instanceof Function ? value(storedValue) : value;
20 | setStoredValue(valueToStore);
21 | window.localStorage.setItem(key, JSON.stringify(valueToStore));
22 | } catch (error) {}
23 | };
24 |
25 | return [storedValue, setValue];
26 | };
27 |
28 | export default useLocalStorage;
29 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-random-background.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 | import { colors } from "../utils/constants";
3 |
4 | const useRandomBackground = () => {
5 | const [backgroundColor, setBackgroundColor] = useState("");
6 |
7 | useEffect(() => {
8 | setBackgroundColor(colors[Math.floor(Math.random() * colors.length)]);
9 | }, []);
10 |
11 | return {
12 | backgroundColor,
13 | };
14 | };
15 |
16 | export default useRandomBackground;
17 |
--------------------------------------------------------------------------------
/client/googledocs/src/hooks/use-window-size.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 |
3 | interface Size {
4 | width: number | undefined;
5 | height: number | undefined;
6 | }
7 |
8 | const useWindowSize = () => {
9 | const [windowSize, setWindowSize] = useState({
10 | width: undefined,
11 | height: undefined,
12 | });
13 |
14 | const [widthStr, setWidthStr] = useState("");
15 | const [heightStr, setHeightStr] = useState("");
16 | const [isMobileWidth, setIsMobileWidth] = useState(true);
17 |
18 | useEffect(() => {
19 | if (windowSize.height !== undefined && windowSize.width !== undefined) {
20 | setWidthStr(`${windowSize.width}px`);
21 | setHeightStr(`${windowSize.height}px`);
22 | setIsMobileWidth(windowSize.width < 1024);
23 | }
24 | }, [windowSize]);
25 |
26 | useEffect(() => {
27 | function handleResize() {
28 | setWindowSize({
29 | width: window.innerWidth,
30 | height: window.innerHeight,
31 | });
32 | }
33 |
34 | window.addEventListener("resize", handleResize);
35 | handleResize();
36 |
37 | return () => window.removeEventListener("resize", handleResize);
38 | }, []);
39 |
40 | return {
41 | height: windowSize.height,
42 | width: windowSize.width,
43 | widthStr,
44 | heightStr,
45 | isMobileWidth,
46 | };
47 | };
48 |
49 | export default useWindowSize;
50 |
--------------------------------------------------------------------------------
/client/googledocs/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
--------------------------------------------------------------------------------
/client/googledocs/src/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import "./index.css";
4 | import Login from "../src/pages/login";
5 | import Register from "../src/pages/register";
6 | import VerifyEmail from "../src/pages/user/verify-email";
7 | import { BrowserRouter, Route, Routes } from "react-router-dom";
8 | import { AuthProvider } from "./contexts/auth-context";
9 | import { ToastProvider } from "./contexts/toast-context";
10 | import { DocumentProvider } from "./contexts/document-context";
11 | import Document from "../src/pages/document/index";
12 | import AuthRoute from "./components/molecules/auth-route";
13 | import Create from "./pages/document/create";
14 | import { EditorProvider } from "./contexts/editor-context";
15 | const root = ReactDOM.createRoot(document.getElementById("root"));
16 | root.render(
17 |
18 |
19 |
20 |
21 |
22 | I am Home Page} />
23 | } />
24 | } />
25 | } />
26 | } />}
29 | />
30 |
36 |
37 |
38 |
39 |
40 | }
41 | />
42 | }
43 | />
44 |
45 |
46 |
47 |
48 |
49 | );
50 |
--------------------------------------------------------------------------------
/client/googledocs/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/client/googledocs/src/pages/document/create.tsx:
--------------------------------------------------------------------------------
1 | import CreateDocumentButton from "../../components/atoms/create-document-button/create-document-btn";
2 | import Spinner from "../../components/atoms/spinner/spinner";
3 | import DocumentsList from "../../components/molecules/documents-list/documents-list";
4 | import DocumentCreateHeader from "../../components/organisms/document-create-header/document-create-header";
5 | import useAuth from "../../hooks/use-auth";
6 | import useDocuments from "../../hooks/use-documents";
7 | import useWindowSize from "../../hooks/use-window-size";
8 |
9 | const Create = () => {
10 | const { heightStr } = useWindowSize();
11 | const { userId } = useAuth();
12 | const { documents, loading, setDocuments } = useDocuments();
13 |
14 | const recentDocuments =
15 | documents === null
16 | ? []
17 | : documents.filter((document) => document.userId === userId);
18 |
19 | const sharedDocuments =
20 | documents === null
21 | ? []
22 | : documents.filter((document) => document.userId !== userId);
23 |
24 | return (
25 |
26 |
27 |
28 | {loading ? (
29 |
30 | ) : (
31 | <>
32 |
37 |
42 | >
43 | )}
44 |
45 | );
46 | };
47 |
48 | export default Create;
49 |
--------------------------------------------------------------------------------
/client/googledocs/src/pages/document/index.tsx:
--------------------------------------------------------------------------------
1 | import { useParams } from "react-router-dom";
2 | import useWindowSize from "../../hooks/use-window-size";
3 | import useDocument from "../../hooks/use-document";
4 | import DocumentHeader from "../../components/organisms/document-header/document-header";
5 | import { useContext, useEffect, useRef } from "react";
6 | import { DocumentContext } from "../../contexts/document-context";
7 | import DocumentEditor from "../../components/organisms/document-editor/document-editor";
8 |
9 | const Document = () => {
10 | const { heightStr, widthStr } = useWindowSize();
11 | const { id: documentId } = useParams();
12 | const documentHeaderRef = useRef(null);
13 | const { loading, document } = useDocument(parseInt(documentId as string));
14 | const { setDocument } = useContext(DocumentContext);
15 |
16 | const documentViewerHeight = `calc(${heightStr} - ${documentHeaderRef.current?.clientHeight}px)`;
17 |
18 | useEffect(() => {
19 | if (document !== null) setDocument(document);
20 | }, [document]);
21 |
22 | return (
23 |
27 | {loading ? (
28 | <>Loading...>
29 | ) : (
30 | <>
31 |
32 |
45 | >
46 | )}
47 |
48 | );
49 | };
50 |
51 | export default Document;
52 |
--------------------------------------------------------------------------------
/client/googledocs/src/pages/login/index.tsx:
--------------------------------------------------------------------------------
1 | import { KeyboardEvent, useContext, useState } from "react";
2 | import TextField from "../../components/atoms/text-field/text-field";
3 | import useWindowSize from "../../hooks/use-window-size";
4 | import validator from "validator";
5 | import AuthService from "../../services/auth-service";
6 | import useAuth from "../../hooks/use-auth";
7 | import { ToastContext } from "../../contexts/toast-context";
8 | import { useNavigate } from "react-router-dom";
9 | import Logo from "../../components/atoms/logo/logo";
10 |
11 | const Login = () => {
12 | const { widthStr, heightStr } = useWindowSize();
13 | const [email, setEmail] = useState("");
14 | const [emailErrors, setEmailErros] = useState>([]);
15 | const [password, setPassword] = useState("");
16 | const [passwordErrors, setPasswordErrors] = useState>([]);
17 | const [loading, setLoading] = useState(false);
18 | const { login } = useAuth();
19 | const { success, error } = useContext(ToastContext);
20 | const navigate = useNavigate();
21 |
22 | const validate = () => {
23 | setEmailErros([]);
24 | setPasswordErrors([]);
25 | let isValid = true;
26 |
27 | if (!validator.isEmail(email)) {
28 | setEmailErros(["Must enter a valid email"]);
29 | isValid = false;
30 | }
31 | if (!password.length) {
32 | setPasswordErrors(["Must enter a password"]);
33 | isValid = false;
34 | }
35 |
36 | return isValid;
37 | };
38 |
39 | const loginUser = async () => {
40 | if (!validate()) return;
41 | setLoading(true);
42 | try {
43 | const response = await AuthService.login({ email, password });
44 | const { accessToken: newAccessToken, refreshToken: newRefreshToken } =
45 | response.data;
46 |
47 | login(newAccessToken, newRefreshToken);
48 | success("Successfully logged in! ");
49 | navigate("/document/create");
50 | } catch (err) {
51 | error("Incorrect username or password");
52 | } finally {
53 | setLoading(false);
54 | }
55 | };
56 |
57 | const handleOnKeyPress = (event: KeyboardEvent) => {
58 | if (event.key === "Enter") loginUser();
59 | };
60 |
61 | const handleOnInputEmail = (value: string) => {
62 | setEmailErros([]);
63 | setEmail(value);
64 | };
65 |
66 | const handleOnInputPassword = (value: string) => {
67 | setPasswordErrors([]);
68 | setPassword(value);
69 | };
70 | return (
71 |
76 |
77 |
78 |
79 |
80 |
Sign in
81 |
to continue to Docs
82 |
83 |
90 |
91 | Need an account? - router to register
92 |
93 |
101 |
107 |
114 |
115 |
116 |
117 |
120 |
123 |
124 |
125 | );
126 | };
127 |
128 | export default Login;
129 |
--------------------------------------------------------------------------------
/client/googledocs/src/pages/register/index.tsx:
--------------------------------------------------------------------------------
1 | import { KeyboardEvent, useContext, useState } from "react";
2 | import useWindowSize from "../../hooks/use-window-size";
3 | import { Link, useNavigate } from "react-router-dom";
4 | import validator from "validator";
5 | import AuthService from "../../services/auth-service";
6 | import { ToastContext } from "../../contexts/toast-context";
7 | import axios, { AxiosError } from "axios";
8 | import TextField from "../../components/atoms/text-field/text-field";
9 | import Logo from "../../components/atoms/logo/logo";
10 |
11 | const Register = () => {
12 | const { widthStr, heightStr } = useWindowSize();
13 | const [email, setEmail] = useState("");
14 | const [emailErrors, setEmailErrors] = useState>([]);
15 | const [loading, setLoading] = useState(false);
16 | const [password1, setPassword1] = useState("");
17 | const [password1Errors, setPassword1Errors] = useState>([]);
18 | const [password2, setPassword2] = useState("");
19 | const [password2Errors, setPassword2Errors] = useState>([]);
20 |
21 | const navigate = useNavigate();
22 | const { addToast, error } = useContext(ToastContext);
23 |
24 | const validate = () => {
25 | setEmailErrors([]);
26 | setPassword1Errors([]);
27 | setPassword2Errors([]);
28 | let isValid = true;
29 |
30 | if (!validator.isEmail(email)) {
31 | setEmailErrors(["Must enter a valid email"]);
32 | isValid = false;
33 | }
34 | if (!(password1.length >= 8 && password1.length <= 25)) {
35 | setPassword1Errors((prev) => [
36 | ...prev,
37 | "Password must be between 1 and 25 characters",
38 | ]);
39 | isValid = false;
40 | }
41 | if (!/\d/.test(password1)) {
42 | setPassword1Errors((prev) => [
43 | ...prev,
44 | "Password must contain at least 1 number",
45 | ]);
46 | isValid = false;
47 | }
48 | if (password1 !== password2) {
49 | setPassword2Errors(["Passwords do not match"]);
50 | isValid = false;
51 | }
52 |
53 | return isValid;
54 | };
55 |
56 | const register = async () => {
57 | if (!validate()) return;
58 |
59 | try {
60 | await AuthService.register({
61 | email,
62 | password1,
63 | password2,
64 | });
65 |
66 | addToast({
67 | title: `Successfully registered ${email}!`,
68 | body: "Please check your inbox to verify your email address",
69 | color: "success",
70 | });
71 | navigate("/login");
72 | } catch (err) {
73 | if (axios.isAxiosError(err)) {
74 | const { response } = err as AxiosError;
75 | const errors = (response as any).data.errors;
76 | const emailFieldErrors = errors
77 | .filter((error: any) => error.param === "email")
78 | .map((error: any) => error.msg);
79 | const password1FieldErrors = errors
80 | .filter((error: any) => error.param === "password1")
81 | .map((error: any) => error.msg);
82 | const password2FieldErrors = errors
83 | .filter((error: any) => error.param === "password2")
84 | .map((error: any) => error.msg);
85 |
86 | if (emailFieldErrors) setEmailErrors(emailFieldErrors);
87 | if (password1FieldErrors) setPassword1Errors(password1FieldErrors);
88 | if (password2FieldErrors) setPassword2Errors(password2FieldErrors);
89 |
90 | if (
91 | !emailFieldErrors &&
92 | !password1FieldErrors &&
93 | !password2FieldErrors
94 | ) {
95 | error("An unknown error has occured. Please try again");
96 | }
97 | } else {
98 | error("An unknown error has occured. Please try again");
99 | }
100 | } finally {
101 | setLoading(false);
102 | }
103 | };
104 |
105 | const handleOnKeyPress = (event: KeyboardEvent) => {
106 | if (event.key === "Enter") register();
107 | };
108 |
109 | const handleOnInputEmail = (value: string) => {
110 | setEmailErrors([]);
111 | setEmail(value);
112 | };
113 |
114 | const handleOnInputPassword1 = (value: string) => {
115 | setPassword1Errors([]);
116 | setPassword1(value);
117 | };
118 |
119 | const handleOnInputPassword2 = (value: string) => {
120 | setPassword2Errors([]);
121 | setPassword2(value);
122 | };
123 |
124 | return (
125 |
130 |
131 |
132 |
133 |
134 |
Sign up
135 |
for a Docs account
136 |
137 |
144 |
152 |
160 |
164 | Sign in instead
165 |
166 |
173 |
174 |
175 |
176 |
179 |
182 |
183 |
184 | );
185 | };
186 |
187 | export default Register;
188 |
--------------------------------------------------------------------------------
/client/googledocs/src/pages/user/verify-email.tsx:
--------------------------------------------------------------------------------
1 | import { useContext, useEffect, useState } from "react";
2 | import { Navigate, useParams } from "react-router-dom";
3 | import { ToastContext } from "../../contexts/toast-context";
4 | import AuthService from "../../services/auth-service";
5 | import axios from "axios";
6 |
7 | const VerifyEmail = () => {
8 | const { token } = useParams();
9 | const { addToast, error } = useContext(ToastContext);
10 | const [children, setChildren] = useState(<>Loading...>);
11 |
12 | const verifyEmail = async () => {
13 | if (token === undefined) {
14 | error("This token is invalid.");
15 | setChildren();
16 | return;
17 | }
18 | console.log(token);
19 | try {
20 | await AuthService.verifyEmail(token);
21 |
22 | addToast({
23 | title: "Successfully verified your email address!",
24 | body: "You may now login.",
25 | color: "success",
26 | });
27 | } catch (err) {
28 | if (axios.isAxiosError(err)) {
29 | error("An unknown error has occurred. Please try again");
30 | } else {
31 | error("An unknown error has occurred. Please try again");
32 | }
33 | } finally {
34 | setChildren();
35 | return;
36 | }
37 | };
38 |
39 | useEffect(() => {
40 | verifyEmail();
41 | }, []);
42 |
43 | return children;
44 | };
45 |
46 | export default VerifyEmail;
47 |
--------------------------------------------------------------------------------
/client/googledocs/src/services/api.ts:
--------------------------------------------------------------------------------
1 | import axios from "axios";
2 |
3 | export const BASE_URL = "http://localhost:8080/";
4 |
5 | const API = axios.create({
6 | baseURL: BASE_URL,
7 | headers: {
8 | Accept: "application/json",
9 | "Content-Type": "application/json",
10 | },
11 | });
12 |
13 | export default API;
14 |
--------------------------------------------------------------------------------
/client/googledocs/src/services/auth-service.ts:
--------------------------------------------------------------------------------
1 | import API from "./api";
2 |
3 | const AuthService = {
4 | login: (payload: { email: string; password: string }) => {
5 | return API.post("auth/login", payload);
6 | },
7 | register: (payload: {
8 | email: string;
9 | password1: string;
10 | password2: string;
11 | }) => {
12 | return API.post("user", payload);
13 | },
14 | refreshToken: (payload: { token: string }) => {
15 | return API.post("auth/refresh-token", payload);
16 | },
17 | logout: (accessToken: string) => {
18 | return API.delete("auth/logiut", {
19 | headers: { Authorization: `Bearer ${accessToken}` },
20 | });
21 | },
22 | verifyEmail: (token: string) => {
23 | return API.put(`user/verify-email/${token}`);
24 | },
25 | };
26 |
27 | export default AuthService;
28 |
--------------------------------------------------------------------------------
/client/googledocs/src/services/document-service.ts:
--------------------------------------------------------------------------------
1 | import DocumentInterface from "../types/interfaces/document";
2 | import API from "./api";
3 |
4 | const DocumentService = {
5 | create: (accessToken: string) => {
6 | return API.post(
7 | "document",
8 | {},
9 | {
10 | headers: { Authorization: `Bearer ${accessToken}` },
11 | }
12 | );
13 | },
14 | get: (accessToken: string, documentId: number) => {
15 | return API.get(`document/${documentId}`, {
16 | headers: { Authorization: `Bearer ${accessToken}` },
17 | });
18 | },
19 | list: (accessToken: string) => {
20 | return API.get("document", {
21 | headers: { Authorization: `Bearer ${accessToken}` },
22 | });
23 | },
24 | update: (accessToken: string, payload: DocumentInterface) => {
25 | return API.put(`document/${payload.id}`, payload, {
26 | headers: { Authorization: `Bearer ${accessToken}` },
27 | });
28 | },
29 | delete: (accessToken: string, documentId: number) => {
30 | return API.delete(`document/${documentId}`, {
31 | headers: { Authorization: `Bearer ${accessToken}` },
32 | });
33 | },
34 | };
35 |
36 | export default DocumentService;
37 |
--------------------------------------------------------------------------------
/client/googledocs/src/services/document-user-service.ts:
--------------------------------------------------------------------------------
1 | import PermissionEnum from "../types/enums/permission-enum";
2 | import API from "./api";
3 |
4 | const DocumentUserService = {
5 | create: (
6 | accessToken: string,
7 | payload: { documentId: number; email: string; permission: PermissionEnum }
8 | ) => {
9 | return API.post(`document/${payload.documentId}/share`, payload, {
10 | headers: { Authorization: `Bearer ${accessToken}` },
11 | });
12 | },
13 |
14 | delete: (
15 | accessToken: string,
16 | payload: { documentId: number; userId: number }
17 | ) => {
18 | return API.delete(
19 | `document/${payload.documentId}/share/${payload.userId}`,
20 | {
21 | headers: { Authorization: `Bearer ${accessToken}` },
22 | }
23 | );
24 | },
25 | };
26 |
27 | export default DocumentUserService;
28 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/enums/permission-enum.ts:
--------------------------------------------------------------------------------
1 | enum PermissionEnum {
2 | VIEW = "VIEW",
3 | EDIT = "EDIT",
4 | }
5 |
6 | export default PermissionEnum;
7 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/enums/socket-events-enum.ts:
--------------------------------------------------------------------------------
1 | enum SocketEvent {
2 | SEND_CHANGES = "send-changes",
3 | RECEIVE_CHANGES = "receive-changes",
4 | CURRENT_USERS_UPDATE = "current-users-update",
5 | }
6 |
7 | export default SocketEvent;
8 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/action.ts:
--------------------------------------------------------------------------------
1 | interface ActionInterface {
2 | label: string;
3 | action: Function;
4 | }
5 |
6 | export default ActionInterface;
7 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/document-user.ts:
--------------------------------------------------------------------------------
1 | import PermissionEnum from "../enums/permission-enum";
2 |
3 | interface DocumentUser {
4 | permission: PermissionEnum;
5 | userId: number;
6 | documentId: number;
7 | createdAt: Date;
8 | updatedAt: Date;
9 | user: {
10 | email: string;
11 | };
12 | }
13 |
14 | export default DocumentUser;
15 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/document.ts:
--------------------------------------------------------------------------------
1 | import DocumentUser from "./document-user";
2 |
3 | interface DocumentInterface {
4 | id: number;
5 | title: string;
6 | content: string | null;
7 | createdAt: Date;
8 | updatedAt: Date;
9 | userId: number;
10 | users: Array;
11 | isPublic: boolean;
12 | }
13 |
14 | export default DocumentInterface;
15 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/input.ts:
--------------------------------------------------------------------------------
1 | interface InputProps {
2 | label?: string;
3 | placeholder?: string;
4 | errors?: Array;
5 | }
6 |
7 | export default InputProps;
8 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/toast.ts:
--------------------------------------------------------------------------------
1 | import ActionInterface from "./action";
2 |
3 | interface ToastInterface {
4 | id: string;
5 | color: "primary" | "secondary" | "success" | "warning" | "danger";
6 | title?: string | JSX.Element;
7 | body?: string | JSX.Element;
8 | actions?: Array;
9 | }
10 |
11 | export default ToastInterface;
12 |
--------------------------------------------------------------------------------
/client/googledocs/src/types/interfaces/token.ts:
--------------------------------------------------------------------------------
1 | interface Token {
2 | exp: number;
3 | id: number;
4 | email: string;
5 | }
6 |
7 | export default Token;
8 |
--------------------------------------------------------------------------------
/client/googledocs/src/utils/constants.ts:
--------------------------------------------------------------------------------
1 | export const colors = [
2 | "bg-red-700",
3 | "bg-orange-700",
4 | "bg-amber-700",
5 | "bg-yellow-700",
6 | "bg-lime-700",
7 | "bg-green-700",
8 | "bg-emerald-700",
9 | "bg-teal-700",
10 | "bg-cyan-700",
11 | "bg-sky-700",
12 | "bg-blue-700",
13 | "bg-indigo-700",
14 | "bg-violet-700",
15 | "bg-purple-700",
16 | "bg-fuchsia-700",
17 | "bg-pink-700",
18 | "bg-rose-700",
19 | ];
20 |
--------------------------------------------------------------------------------
/client/googledocs/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: ["./src/**/*.{js,jsx,ts,tsx}"],
4 | theme: {
5 | extend: {},
6 | },
7 | plugins: [],
8 | darkMode: "class",
9 | };
10 |
--------------------------------------------------------------------------------
/client/googledocs/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "include": ["src"],
3 | "compilerOptions": {
4 | "jsx": "react-jsx"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/server/.env.development:
--------------------------------------------------------------------------------
1 | NODE_ENV=development
2 | HOST=localhost
3 | PORT=8080
4 | DATABASE_URL=postgres://postgres:Agririze@6362@localhost:5432/gd
5 | USER=postgres
6 | PASSWORD=Agririze@6362
7 | DB_HOST=localhost
8 | DB_PORT=5432
9 | DATABASE=gd
10 |
--------------------------------------------------------------------------------
/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "build": "npx tsc",
9 | "start": "node dist/src/server.js",
10 | "dev": "NODE_ENV=development concurrently \"npx tsc --watch\" \"nodemon -q dist/src/server.js\""
11 | },
12 | "keywords": [],
13 | "author": "",
14 | "license": "ISC",
15 | "dependencies": {
16 | "bcrypt": "^5.1.0",
17 | "cors": "^2.8.5",
18 | "dotenv": "^16.3.1",
19 | "express": "^4.18.2",
20 | "express-validator": "^7.0.1",
21 | "jsonwebtoken": "^9.0.1",
22 | "nodemailer": "^6.9.4",
23 | "pg": "^8.11.2",
24 | "sequelize": "^6.32.1",
25 | "sequelize-typescript": "^2.1.5",
26 | "socket.io": "^4.7.2"
27 | },
28 | "devDependencies": {
29 | "@types/bcrypt": "^5.0.0",
30 | "@types/cors": "^2.8.13",
31 | "@types/express": "^4.17.17",
32 | "@types/jsonwebtoken": "^9.0.2",
33 | "@types/node": "^20.4.9",
34 | "@types/nodemailer": "^6.4.9",
35 | "@types/sequelize": "^4.28.15",
36 | "concurrently": "^8.2.0",
37 | "nodemon": "^3.0.1",
38 | "sequelize-cli": "^6.6.1",
39 | "typescript": "^5.1.6"
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/server/src/config/db.config.ts:
--------------------------------------------------------------------------------
1 | import { Sequelize } from "sequelize-typescript";
2 | import env from "./env.config";
3 |
4 | const sequelize =
5 | env.NODE_ENV === "test" || env.NODE_ENV === "development"
6 | ? new Sequelize("gd", "postgres", "Agririze@6362", {
7 | host: "localhost",
8 | dialect: "postgres",
9 | logging: false,
10 | })
11 | : new Sequelize(env.DATABASE_URL!, {
12 | dialect: "postgres",
13 | dialectOptions: {
14 | ssl: {
15 | require: true,
16 | rejectUnauthorized: false,
17 | },
18 | },
19 | logging: false,
20 | });
21 |
22 | export default sequelize;
23 |
--------------------------------------------------------------------------------
/server/src/config/env.config.ts:
--------------------------------------------------------------------------------
1 | // if (
2 | // process.env.NODE_ENV === undefined ||
3 | // process.env.HOST === undefined ||
4 | // process.env.PORT === undefined ||
5 | // process.env.DATABASE_URL === undefined ||
6 | // process.env.USER === undefined ||
7 | // process.env.PASSWORD === undefined ||
8 | // process.env.DB_HOST === undefined ||
9 | // process.env.DB_PORT === undefined ||
10 | // process.env.DATABASE === undefined
11 | // ) {
12 | // throw new Error("Environment variables missing.");
13 | // }
14 |
15 | const env = {
16 | NODE_ENV: process.env.NODE_ENV,
17 | HOST: process.env.HOST,
18 | PORT: process.env.PORT,
19 | DATABASE_URL: process.env.DATABASE_URL,
20 | USER: process.env.USER,
21 | PASSWORD: process.env.PASSWORD,
22 | DB_HOST: process.env.DB_PORT,
23 | DB_PORT: process.env.DB_PORT,
24 | DATABASE: process.env.DATABASE,
25 | };
26 |
27 | export default env;
28 |
--------------------------------------------------------------------------------
/server/src/config/smtp.config.ts:
--------------------------------------------------------------------------------
1 | import { createTransport } from "nodemailer";
2 |
3 | const transporter = createTransport({
4 | port: 465,
5 | host: "smtp.gmail.com",
6 | auth: {
7 | user: "kuluruvineeth8623@gmail.com",
8 | pass: "cqudocdrueyyuyyp",
9 | },
10 | secure: true,
11 | });
12 |
13 | export default transporter;
14 |
--------------------------------------------------------------------------------
/server/src/controllers/auth/auth.controller.ts:
--------------------------------------------------------------------------------
1 | import { validationResult } from "express-validator";
2 | import catchAsync from "../../middleware/catch-async";
3 | import { Request, Response } from "express";
4 | import { userService } from "../../services/user.service";
5 | import { emailNotVerified, userNotFound } from "../../responses";
6 | import jwt, { VerifyErrors } from "jsonwebtoken";
7 |
8 | class AuthController {
9 | public login = catchAsync(async (req: Request, res: Response) => {
10 | const err = validationResult(req);
11 | if (!err.isEmpty) {
12 | return res.status(400).json(err);
13 | }
14 |
15 | const { email, password } = req.body;
16 | const user = await userService.findUserByEmail(email);
17 | if (!user) return res.status(401).json({ errors: userNotFound });
18 |
19 | const validPassword = await userService.checkPassword(user, password);
20 | if (!validPassword) return res.status(401).json({ errors: userNotFound });
21 |
22 | if (!user.isVerified) res.status(403).json({ errors: emailNotVerified });
23 |
24 | const authResponse = await userService.generateAuthResponse(user);
25 | return res.status(200).json(authResponse);
26 | });
27 |
28 | public refreshToken = catchAsync(async (req: Request, res: Response) => {
29 | const err = validationResult(req);
30 | if (!err.isEmpty()) {
31 | return res.status(400).json(err);
32 | }
33 |
34 | const refreshToken = req.body.token;
35 |
36 | const isTokenActive = await userService.getIsTokenActive(refreshToken);
37 | if (!isTokenActive) return res.sendStatus(403);
38 |
39 | jwt.verify(
40 | refreshToken,
41 | "refresh_token",
42 | async (error: VerifyErrors | null, decoded: unknown) => {
43 | if (error) return res.sendStatus(403);
44 | try {
45 | const { id, email, roles } = decoded as RequestUser;
46 | const user = { id, email, roles };
47 |
48 | const authResponse = await userService.generateAuthResponse(user);
49 | return res.status(200).json(authResponse);
50 | } catch (error) {
51 | console.log(error);
52 | res.sendStatus(403);
53 | }
54 | }
55 | );
56 | });
57 |
58 | public logout = catchAsync(async (req: Request, res: Response) => {
59 | if (!req.user) return res.sendStatus(401);
60 |
61 | const userId = parseInt(req.user.id);
62 | await userService.logoutUser(userId);
63 |
64 | return res.sendStatus(200);
65 | });
66 | }
67 |
68 | const authController = new AuthController();
69 |
70 | export { authController };
71 |
--------------------------------------------------------------------------------
/server/src/controllers/document/document.controller.ts:
--------------------------------------------------------------------------------
1 | import { Request, Response } from "express";
2 | import catchAsync from "../../middleware/catch-async";
3 | import documentService from "../../services/document.service";
4 | import { Document } from "../../db/models/document.model";
5 | import { DocumentUser } from "../../db/models/document-user.model";
6 | import { json } from "sequelize";
7 | import { validationResult } from "express-validator";
8 |
9 | class DocumentController {
10 | public getOne = catchAsync(async (req: Request, res: Response) => {
11 | if (!req.user) return res.sendStatus(401);
12 |
13 | const { id } = req.params;
14 |
15 | const document = await documentService.findDocumentById(
16 | parseInt(id),
17 | parseInt(req.user.id)
18 | );
19 |
20 | if (document === null) return res.sendStatus(404);
21 |
22 | return res.status(200).json(document);
23 | });
24 |
25 | public getAll = catchAsync(async (req: Request, res: Response) => {
26 | const documents = await Document.findAll({
27 | where: {
28 | userId: req.user?.id,
29 | },
30 | });
31 | const documentUsers = await DocumentUser.findAll({
32 | where: {
33 | userId: req.user?.id,
34 | },
35 | include: {
36 | model: Document,
37 | },
38 | });
39 |
40 | const sharedDocuments = documentUsers.map(
41 | (documentUser) => documentUser.document
42 | );
43 |
44 | documents.push(...sharedDocuments);
45 |
46 | return res.status(200).json(documents);
47 | });
48 |
49 | public update = catchAsync(async (req: Request, res: Response) => {
50 | const err = validationResult(req);
51 | if (!err.isEmpty()) {
52 | return res.status(400).json(err);
53 | }
54 |
55 | if (!req.user) return res.sendStatus(401);
56 |
57 | const { id } = req.params;
58 | const { title, content, isPublic } = req.body;
59 |
60 | const document = await documentService.findDocumentById(
61 | parseInt(id),
62 | parseInt(req.user.id)
63 | );
64 |
65 | if (document === null) return res.sendStatus(404);
66 |
67 | if (title !== undefined && title !== null) document.title = title;
68 | if (content !== undefined && content !== null) document.content = content;
69 | if (isPublic !== undefined && isPublic !== null)
70 | document.isPublic = isPublic;
71 |
72 | await document.save();
73 |
74 | return res.sendStatus(200);
75 | });
76 |
77 | public create = catchAsync(async (req: Request, res: Response) => {
78 | const document = await Document.create({
79 | userId: req.user?.id,
80 | });
81 |
82 | return res.status(201).json(document);
83 | });
84 |
85 | public delete = catchAsync(async (req: Request, res: Response) => {
86 | const { id } = req.params;
87 |
88 | await Document.destroy({
89 | where: {
90 | id: id,
91 | userId: req.user?.id,
92 | },
93 | });
94 |
95 | return res.sendStatus(200);
96 | });
97 | }
98 |
99 | const documentController = new DocumentController();
100 |
101 | export { documentController };
102 |
--------------------------------------------------------------------------------
/server/src/controllers/document/share/share.controller.ts:
--------------------------------------------------------------------------------
1 | import { Request, Response } from "express";
2 | import catchAsync from "../../../middleware/catch-async";
3 | import { validationResult } from "express-validator";
4 | import { Document } from "../../../db/models/document.model";
5 | import { User } from "../../../db/models/user.model";
6 | import { DocumentUser } from "../../../db/models/document-user.model";
7 | import { mailservice } from "../../../services/mail.service";
8 |
9 | class ShareController {
10 | public create = catchAsync(async (req: Request, res: Response) => {
11 | const err = validationResult(req);
12 | if (!err.isEmpty()) {
13 | return res.status(400).json(err);
14 | }
15 |
16 | const { id } = req.params;
17 |
18 | const document = await Document.findByPk(id);
19 | if (!document) return res.sendStatus(400);
20 |
21 | if (!req.user?.id || document.userId !== parseInt(req.user?.id)) {
22 | return res.sendStatus(400);
23 | }
24 |
25 | const { email, permission } = req.body;
26 |
27 | const sharedUser = await User.findOne({
28 | where: {
29 | email,
30 | },
31 | });
32 |
33 | if (!sharedUser) return res.sendStatus(400);
34 |
35 | const documentUser = await DocumentUser.create({
36 | documentId: id,
37 | userId: sharedUser.id,
38 | permission: permission,
39 | });
40 |
41 | const mail = {
42 | from: "kuluruvineeth8623@gmail.com",
43 | to: sharedUser.email,
44 | subject: `${req.user.email} shared a document with you!`,
45 | text: `Click the following link to view and edit the document : http://localhost:3000/document/${id}`,
46 | };
47 |
48 | //call mailservice to send email
49 | await mailservice.sendMail(mail);
50 |
51 | return res.status(201).json(documentUser);
52 | });
53 |
54 | public delete = catchAsync(async (req: Request, res: Response) => {
55 | const err = validationResult(req);
56 | if (!err.isEmpty()) {
57 | return res.status(400).json(err);
58 | }
59 |
60 | const { documentId, userId } = req.params;
61 |
62 | const document = await Document.findOne({
63 | where: {
64 | id: documentId,
65 | userId: req.user?.id,
66 | },
67 | });
68 | if (!document) return res.sendStatus(400);
69 |
70 | const query = {
71 | where: {
72 | documentId,
73 | userId,
74 | },
75 | };
76 |
77 | const documentUser = await DocumentUser.findOne(query);
78 |
79 | if (!documentUser) return res.sendStatus(400);
80 |
81 | await DocumentUser.destroy(query);
82 |
83 | return res.sendStatus(200);
84 | });
85 | }
86 |
87 | const shareController = new ShareController();
88 |
89 | export { shareController };
90 |
--------------------------------------------------------------------------------
/server/src/controllers/user/user.controller.ts:
--------------------------------------------------------------------------------
1 | import { validationResult } from "express-validator";
2 | import catchAsync from "../../middleware/catch-async";
3 | import { Request, Response } from "express";
4 | import { userService } from "../../services/user.service";
5 | import { resetPassword } from "../../responses";
6 | import jwt, { VerifyErrors } from "jsonwebtoken";
7 |
8 | class UserController {
9 | public register = catchAsync(async (req: Request, res: Response) => {
10 | const err = validationResult(req);
11 | if (!err.isEmpty) {
12 | return res.status(400).json(err);
13 | }
14 |
15 | const { email, password1 } = req.body;
16 |
17 | await userService.createUser(email, password1);
18 |
19 | return res.sendStatus(200);
20 | });
21 |
22 | public getUser = catchAsync(async (req: Request, res: Response) => {
23 | const userId = parseInt(req.params.id);
24 |
25 | const user = await userService.findUserById(userId);
26 |
27 | if (user === null) return res.sendStatus(400);
28 |
29 | return res.status(200).json(user);
30 | });
31 |
32 | public resetPassword = catchAsync(async (req: Request, res: Response) => {
33 | const err = validationResult(req);
34 | if (!err.isEmpty()) {
35 | return res.status(400).json(err);
36 | }
37 |
38 | const { email } = req.body;
39 | const user = await userService.findUserByEmail(email);
40 | if (!user) return res.status(200).json(resetPassword);
41 |
42 | await userService.resetPassword(user);
43 |
44 | return res.status(200).json(resetPassword);
45 | });
46 |
47 | public verifyEmail = catchAsync(async (req: Request, res: Response) => {
48 | const verificationToken = req.params.token;
49 |
50 | jwt.verify(
51 | verificationToken,
52 | "verify_email",
53 | async (err: VerifyErrors | null, decoded: unknown) => {
54 | if (err) return res.sendStatus(403);
55 | try {
56 | const { email } = decoded as { email: string };
57 |
58 | userService
59 | .findUserByVerificationToken(email, verificationToken)
60 | .then((user) => {
61 | if (!user || user.isVerified) {
62 | return res.sendStatus(400);
63 | }
64 |
65 | userService
66 | .updateIsVerified(user, true)
67 | .then(() => {
68 | return res.sendStatus(200);
69 | })
70 | .catch(() => {
71 | return res.sendStatus(500);
72 | });
73 | })
74 | .catch(() => {
75 | return res.sendStatus(500);
76 | });
77 | } catch (error) {
78 | console.log(error);
79 | return res.sendStatus(403);
80 | }
81 | }
82 | );
83 | });
84 |
85 | public confirmResetPassword = catchAsync(
86 | async (req: Request, res: Response) => {
87 | const err = validationResult(req);
88 | if (!err.isEmpty()) {
89 | return res.status(400).json(err);
90 | }
91 |
92 | const resetPasswordToken = req.params.token;
93 | const { password1 } = req.body;
94 |
95 | jwt.verify(
96 | resetPasswordToken,
97 | "password_reset",
98 | async (err: VerifyErrors | null, decoded: unknown) => {
99 | if (err) return res.sendStatus(403);
100 | try {
101 | const { email } = decoded as { email: string };
102 |
103 | userService
104 | .findUserByPasswordResetToken(email, resetPasswordToken)
105 | .then((user) => {
106 | if (!user) {
107 | return res.sendStatus(400);
108 | }
109 |
110 | userService
111 | .updatePassword(user, password1)
112 | .then(() => {
113 | return res.sendStatus(200);
114 | })
115 | .catch(() => {
116 | return res.sendStatus(500);
117 | });
118 | })
119 | .catch(() => {
120 | return res.sendStatus(500);
121 | });
122 | } catch (error) {
123 | console.log(error);
124 | return res.sendStatus(403);
125 | }
126 | }
127 | );
128 | }
129 | );
130 | }
131 |
132 | const userController = new UserController();
133 |
134 | export { userController };
135 |
--------------------------------------------------------------------------------
/server/src/db/models/document-user.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | BelongsTo,
3 | Column,
4 | DataType,
5 | ForeignKey,
6 | PrimaryKey,
7 | Table,
8 | Model,
9 | } from "sequelize-typescript";
10 | import PermissionEnum from "../../types/enums/permission-enum";
11 | import { User } from "./user.model";
12 | import { Document } from "./document.model";
13 |
14 | @Table({ tableName: "document_user", underscored: true })
15 | class DocumentUser extends Model {
16 | @Column(DataType.ENUM("VIEW", "EDIT"))
17 | permission!: PermissionEnum;
18 |
19 | @BelongsTo(() => User)
20 | user!: User;
21 |
22 | @ForeignKey(() => User)
23 | @PrimaryKey
24 | @Column
25 | userId!: number;
26 |
27 | @BelongsTo(() => Document)
28 | document!: Document;
29 |
30 | @ForeignKey(() => Document)
31 | @PrimaryKey
32 | @Column
33 | documentId!: number;
34 | }
35 |
36 | export { DocumentUser };
37 |
--------------------------------------------------------------------------------
/server/src/db/models/document.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | BelongsTo,
3 | Column,
4 | DataType,
5 | Default,
6 | ForeignKey,
7 | Table,
8 | Model,
9 | DefaultScope,
10 | HasMany,
11 | } from "sequelize-typescript";
12 | import { User } from "./user.model";
13 | import { DocumentUser } from "./document-user.model";
14 |
15 | @DefaultScope(() => ({
16 | include: [
17 | {
18 | model: DocumentUser,
19 | include: [
20 | {
21 | model: User,
22 | attributes: ["email"],
23 | },
24 | ],
25 | },
26 | ],
27 | }))
28 | @Table({ tableName: "document", underscored: true })
29 | class Document extends Model {
30 | @Column(DataType.STRING)
31 | title!: string;
32 |
33 | @Column(DataType.JSONB)
34 | content!: string;
35 |
36 | @ForeignKey(() => User)
37 | userId!: number;
38 |
39 | @BelongsTo(() => User)
40 | user!: User;
41 |
42 | @HasMany(() => DocumentUser, {
43 | onDelete: "CASCADE",
44 | })
45 | users!: Array;
46 |
47 | @Default(false)
48 | @Column(DataType.BOOLEAN)
49 | isPublic!: boolean;
50 | }
51 |
52 | export { Document };
53 |
--------------------------------------------------------------------------------
/server/src/db/models/index.ts:
--------------------------------------------------------------------------------
1 | import sequelize from "../../config/db.config";
2 | import { DocumentUser } from "./document-user.model";
3 | import { Document } from "./document.model";
4 | import { RefreshToken } from "./refresh-token.model";
5 | import { Role } from "./role.model";
6 | import { UserRole } from "./user-role.model";
7 | import { User } from "./user.model";
8 | import Sequelize from "sequelize";
9 |
10 | sequelize.addModels([
11 | User,
12 | RefreshToken,
13 | Role,
14 | UserRole,
15 | Document,
16 | DocumentUser,
17 | ]);
18 |
19 | const db = {
20 | Sequelize,
21 | sequelize,
22 | User,
23 | RefreshToken,
24 | Role,
25 | UserRole,
26 | Document,
27 | DocumentUser,
28 | };
29 |
30 | export default db;
31 |
--------------------------------------------------------------------------------
/server/src/db/models/refresh-token.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | BelongsTo,
3 | Column,
4 | DataType,
5 | ForeignKey,
6 | Table,
7 | Model,
8 | } from "sequelize-typescript";
9 | import { User } from "./user.model";
10 |
11 | @Table({ tableName: "refresh_token", underscored: true })
12 | class RefreshToken extends Model {
13 | @Column(DataType.STRING)
14 | token!: string;
15 |
16 | @ForeignKey(() => User)
17 | userId!: number;
18 |
19 | @BelongsTo(() => User)
20 | user!: User;
21 | }
22 |
23 | export { RefreshToken };
24 |
--------------------------------------------------------------------------------
/server/src/db/models/role.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Column,
3 | DataType,
4 | Table,
5 | Model,
6 | BelongsToMany,
7 | HasMany,
8 | } from "sequelize-typescript";
9 | import RoleEnum from "../../types/enums/role-enum";
10 | import { User } from "./user.model";
11 | import { UserRole } from "./user-role.model";
12 |
13 | @Table({ tableName: "role", underscored: true, timestamps: false })
14 | class Role extends Model {
15 | @Column(DataType.ENUM("ADMIN", "SUPERADMIN"))
16 | name!: RoleEnum;
17 |
18 | @BelongsToMany(() => User, {
19 | through: () => UserRole,
20 | })
21 | users!: Array;
22 |
23 | @HasMany(() => UserRole, {
24 | onDelete: "CASCADE",
25 | })
26 | roleUsers!: Array;
27 | }
28 |
29 | export { Role };
30 |
--------------------------------------------------------------------------------
/server/src/db/models/user-role.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | BelongsTo,
3 | Column,
4 | ForeignKey,
5 | PrimaryKey,
6 | Table,
7 | Model,
8 | } from "sequelize-typescript";
9 | import { User } from "./user.model";
10 | import { Role } from "./role.model";
11 |
12 | @Table({ tableName: "user_role", underscored: true })
13 | class UserRole extends Model {
14 | @BelongsTo(() => User)
15 | user!: User;
16 |
17 | @ForeignKey(() => User)
18 | @PrimaryKey
19 | @Column
20 | userId!: number;
21 |
22 | @BelongsTo(() => Role)
23 | role!: Role;
24 |
25 | @ForeignKey(() => Role)
26 | @PrimaryKey
27 | @Column
28 | roleId!: number;
29 | }
30 |
31 | export { UserRole };
32 |
--------------------------------------------------------------------------------
/server/src/db/models/user.model.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Column,
3 | DataType,
4 | HasMany,
5 | Table,
6 | Model,
7 | BelongsToMany,
8 | Scopes,
9 | } from "sequelize-typescript";
10 | import { RefreshToken } from "./refresh-token.model";
11 | import { Role } from "./role.model";
12 | import { UserRole } from "./user-role.model";
13 | import { DocumentUser } from "./document-user.model";
14 |
15 | @Scopes(() => ({
16 | withRoles: {
17 | include: [
18 | {
19 | model: UserRole,
20 | attributes: ["createdAt", "updatedAt"],
21 | include: [Role],
22 | },
23 | ],
24 | },
25 | }))
26 | @Table({ tableName: "user", underscored: true })
27 | class User extends Model {
28 | @Column(DataType.STRING)
29 | email!: string;
30 |
31 | @Column(DataType.STRING)
32 | password!: string;
33 |
34 | @Column(DataType.BOOLEAN)
35 | isVerified!: boolean;
36 |
37 | @Column(DataType.STRING)
38 | verificationToken!: string;
39 |
40 | @Column(DataType.STRING)
41 | passwordResetToken!: string;
42 |
43 | @HasMany(() => RefreshToken, {
44 | onDelete: "CASCADE",
45 | })
46 | refreshTokens!: Array;
47 |
48 | @BelongsToMany(() => Role, {
49 | through: {
50 | model: () => UserRole,
51 | },
52 | })
53 | roles!: Array;
54 |
55 | @HasMany(() => UserRole, {
56 | onDelete: "CASCADE",
57 | })
58 | userRoles!: Array;
59 |
60 | @HasMany(() => DocumentUser, {
61 | onDelete: "CASCADE",
62 | })
63 | sharedDocuments!: Array;
64 | }
65 |
66 | export { User };
67 |
--------------------------------------------------------------------------------
/server/src/index.ts:
--------------------------------------------------------------------------------
1 | import express, { Express, Request, Response } from "express";
2 | import dotenv from "dotenv";
3 | import env from "./config/env.config";
4 | import db from "./db/models";
5 | import router from "./routes";
6 | import cors from "cors";
7 | import errorHandler from "./middleware/error-handler";
8 |
9 | dotenv.config();
10 |
11 | const app: Express = express();
12 | app.use(express.json());
13 | app.use(
14 | cors({
15 | origin: "*",
16 | })
17 | );
18 | app.use(router);
19 | app.use(errorHandler);
20 | const port = 8080;
21 |
22 | db.sequelize.sync();
23 |
24 | // app.get("/", (req: Request, res: Response) => {
25 | // res.send("Express + Typescript server11111");
26 | // });
27 |
28 | // app.listen(port, () => {
29 | // console.log(`server is listening on port : ${port}`);
30 | // });
31 |
32 | export default app;
33 |
--------------------------------------------------------------------------------
/server/src/middleware/auth.ts:
--------------------------------------------------------------------------------
1 | import { NextFunction, Request, Response } from "express";
2 | import jwt, { VerifyErrors } from "jsonwebtoken";
3 | import RoleEnum from "../types/enums/role-enum";
4 | import { UserRole } from "../db/models/user-role.model";
5 | import { Role } from "../db/models/role.model";
6 |
7 | const authenticate = (req: Request, res: Response, next: NextFunction) => {
8 | const authHeader = req.headers["authorization"];
9 |
10 | const token = authHeader && authHeader.split(" ")[1];
11 | if (!token) return res.sendStatus(401);
12 |
13 | jwt.verify(
14 | token,
15 | "access_token",
16 | (err: VerifyErrors | null, decoded: unknown) => {
17 | if (err) return res.sendStatus(403);
18 | try {
19 | const { id, email, roles } = decoded as RequestUser;
20 | req.user = { id, email, roles };
21 | next();
22 | } catch (error) {
23 | console.log(error);
24 | return res.sendStatus(403);
25 | }
26 | }
27 | );
28 | };
29 |
30 | const authorize = (permittedRoles: Array) => {
31 | return async (req: Request, res: Response, next: NextFunction) => {
32 | if (!req.user) return res.sendStatus(401);
33 | const userId = req.user.id;
34 |
35 | UserRole.findAll({ where: { userId }, include: Role })
36 | .then((data) => {
37 | const roles = data.map((userRole) => userRole.role.name);
38 | if (
39 | permittedRoles.some((permittedRole) => roles.includes(permittedRole))
40 | ) {
41 | next();
42 | } else {
43 | return res.sendStatus(403);
44 | }
45 | })
46 | .catch((error) => {
47 | console.log(error);
48 | return res.sendStatus(403);
49 | });
50 | };
51 | };
52 |
53 | export { authenticate, authorize };
54 |
--------------------------------------------------------------------------------
/server/src/middleware/catch-async.ts:
--------------------------------------------------------------------------------
1 | import { Request, Response, NextFunction } from "express";
2 |
3 | const catchAsync = (fn: Function) => {
4 | return (req: Request, res: Response, next: NextFunction) => {
5 | fn(req, res, next).catch(next);
6 | };
7 | };
8 |
9 | export default catchAsync;
10 |
--------------------------------------------------------------------------------
/server/src/middleware/error-handler.ts:
--------------------------------------------------------------------------------
1 | import { Errback, NextFunction, Request, Response } from "express";
2 |
3 | const errorHandler = (
4 | err: Errback,
5 | req: Request,
6 | res: Response,
7 | next: NextFunction
8 | ) => {
9 | console.log(err);
10 | res.sendStatus(500);
11 | };
12 |
13 | export default errorHandler;
14 |
--------------------------------------------------------------------------------
/server/src/responses/index.ts:
--------------------------------------------------------------------------------
1 | const userNotFound: Array = [
2 | {
3 | msg: "Your email or password is incorrect",
4 | },
5 | ];
6 |
7 | const emailNotVerified: Array = [
8 | {
9 | msg: "Please verify your email before logging in",
10 | },
11 | ];
12 |
13 | const resetPassword: Array = [
14 | {
15 | msg: "If a user with that email exists, you will receive a email with instructions to reset your password.",
16 | },
17 | ];
18 |
19 | export { userNotFound, emailNotVerified, resetPassword };
20 |
--------------------------------------------------------------------------------
/server/src/routes/auth.route.ts:
--------------------------------------------------------------------------------
1 | import { Router } from "express";
2 |
3 | import { authValidator } from "../validators/auth.validator";
4 | import { authController } from "../controllers/auth/auth.controller";
5 | import { authenticate } from "../middleware/auth";
6 |
7 | const router = Router();
8 |
9 | router.post("/login", authValidator.login, authController.login);
10 |
11 | router.post(
12 | "/refresh-token",
13 | authValidator.refreshToken,
14 | authController.refreshToken
15 | );
16 |
17 | router.delete("/logout", authenticate, authController.logout);
18 |
19 | export default router;
20 |
--------------------------------------------------------------------------------
/server/src/routes/document.route.ts:
--------------------------------------------------------------------------------
1 | import { Router } from "express";
2 | import { authenticate } from "../middleware/auth";
3 | import { documentController } from "../controllers/document/document.controller";
4 | import { documentValidator } from "../validators/document.validator";
5 | import { shareValidator } from "../validators/share.validator";
6 | import { shareController } from "../controllers/document/share/share.controller";
7 |
8 | const router = Router();
9 |
10 | router.get("/:id", authenticate, documentController.getOne);
11 |
12 | router.get("/", authenticate, documentController.getAll);
13 | router.put(
14 | "/:id",
15 | authenticate,
16 | documentValidator.update,
17 | documentController.update
18 | );
19 |
20 | router.post("/", authenticate, documentController.create);
21 | router.delete("/:id", authenticate, documentController.delete);
22 |
23 | router.post(
24 | "/:id/share",
25 | authenticate,
26 | shareValidator.create,
27 | shareController.create
28 | );
29 |
30 | router.delete(
31 | "/:documentId/share/:userId",
32 | authenticate,
33 | shareController.delete
34 | );
35 |
36 | export default router;
37 |
--------------------------------------------------------------------------------
/server/src/routes/index.ts:
--------------------------------------------------------------------------------
1 | import { Request, Response, Router } from "express";
2 | import user from "./user.route";
3 | import auth from "./auth.route";
4 | import document from "./document.route";
5 | import { authenticate, authorize } from "../middleware/auth";
6 | import RoleEnum from "../types/enums/role-enum";
7 |
8 | const router = Router();
9 |
10 | router.get(
11 | "/",
12 | authenticate,
13 | authorize([RoleEnum.SUPERADMIN]),
14 | async (req: Request, res: Response) => {
15 | return res.sendStatus(200);
16 | }
17 | );
18 |
19 | router.use("/user", user);
20 | router.use("/auth", auth);
21 | router.use("/document", document);
22 |
23 | export default router;
24 |
--------------------------------------------------------------------------------
/server/src/routes/user.route.ts:
--------------------------------------------------------------------------------
1 | import { Router } from "express";
2 | import { userValidator } from "../validators/user.validator";
3 | import { userController } from "../controllers/user/user.controller";
4 | import { authenticate } from "../middleware/auth";
5 |
6 | const router = Router();
7 |
8 | router.post("/", userValidator.register, userController.register);
9 | router.put("/verify-email/:token", userController.verifyEmail);
10 | router.get("/:id", authenticate, userController.getUser);
11 | router.post(
12 | "/reset-password",
13 | userValidator.resetPassword,
14 | userController.resetPassword
15 | );
16 |
17 | router.put(
18 | "/password/:token",
19 | userValidator.confirmResetPassword,
20 | userController.confirmResetPassword
21 | );
22 |
23 | export default router;
24 |
--------------------------------------------------------------------------------
/server/src/server.ts:
--------------------------------------------------------------------------------
1 | import http from "http";
2 | import app from "./index";
3 | import { Server } from "socket.io";
4 | import jwt, { VerifyErrors } from "jsonwebtoken";
5 | import documentService from "./services/document.service";
6 | import SocketEvent from "./types/enums/socket-events-enum";
7 |
8 | const port = 8080;
9 |
10 | const server = http.createServer(app);
11 |
12 | const io = new Server(server, {
13 | cors: {
14 | origin: "*",
15 | methods: "*",
16 | },
17 | });
18 |
19 | server.listen(port, () => {
20 | console.log(`Server listening on port ${port}`);
21 | });
22 |
23 | io.on("connection", (socket) => {
24 | const accessToken = socket.handshake.query.accessToken as string | undefined;
25 | const documentId = socket.handshake.query.documentId as string | undefined;
26 |
27 | if (!accessToken || !documentId) return socket.disconnect();
28 | else {
29 | jwt.verify(
30 | accessToken,
31 | "access_token",
32 | (err: VerifyErrors | null, decoded: unknown) => {
33 | const { id, email } = decoded as RequestUser;
34 | (socket as any).username = email;
35 |
36 | documentService
37 | .findDocumentById(parseInt(documentId), parseInt(id))
38 | .then(async (document) => {
39 | if (document === null) return socket.disconnect();
40 |
41 | socket.join(documentId);
42 |
43 | io.in(documentId)
44 | .fetchSockets()
45 | .then((clients) => {
46 | io.sockets.in(documentId).emit(
47 | SocketEvent.CURRENT_USERS_UPDATE,
48 | clients.map((client) => (client as any).username)
49 | );
50 | });
51 |
52 | socket.on(SocketEvent.SEND_CHANGES, (rawDraftContentState) => {
53 | socket.broadcast
54 | .to(documentId)
55 | .emit(SocketEvent.RECEIVE_CHANGES, rawDraftContentState);
56 | });
57 |
58 | socket.on("disconnect", async () => {
59 | socket.leave(documentId);
60 | socket.disconnect();
61 | io.in(documentId)
62 | .fetchSockets()
63 | .then((clients) => {
64 | io.sockets.in(documentId).emit(
65 | SocketEvent.CURRENT_USERS_UPDATE,
66 | clients.map((client) => (client as any).username)
67 | );
68 | });
69 | });
70 | })
71 | .catch((error) => {
72 | console.log(error);
73 | return socket.disconnect();
74 | });
75 | }
76 | );
77 | }
78 | });
79 |
--------------------------------------------------------------------------------
/server/src/services/document.service.ts:
--------------------------------------------------------------------------------
1 | import { Op } from "sequelize";
2 | import { Document } from "../db/models/document.model";
3 | import { DocumentUser } from "../db/models/document-user.model";
4 |
5 | class DocumentService {
6 | public findDocumentById = async (id: number, userId: number) => {
7 | let document = await Document.findOne({
8 | where: {
9 | [Op.or]: [
10 | {
11 | id: id,
12 | userId: userId,
13 | },
14 | {
15 | id: id,
16 | isPublic: true,
17 | },
18 | ],
19 | },
20 | });
21 |
22 | if (!document) {
23 | const sharedDocument = await DocumentUser.findOne({
24 | where: {
25 | userId: userId,
26 | documentId: id,
27 | },
28 | include: {
29 | model: Document,
30 | },
31 | });
32 |
33 | if (!sharedDocument) return null;
34 |
35 | document = sharedDocument.document;
36 | }
37 |
38 | return document;
39 | };
40 | }
41 |
42 | export default new DocumentService();
43 |
--------------------------------------------------------------------------------
/server/src/services/mail.service.ts:
--------------------------------------------------------------------------------
1 | import Mail from "nodemailer/lib/mailer";
2 | import transporter from "../config/smtp.config";
3 |
4 | class MailService {
5 | public sendMail = async (mailOptions: Mail.Options) => {
6 | transporter.sendMail(mailOptions);
7 | };
8 | }
9 |
10 | const mailservice = new MailService();
11 |
12 | export { mailservice };
13 |
--------------------------------------------------------------------------------
/server/src/services/user.service.ts:
--------------------------------------------------------------------------------
1 | import { User } from "../db/models/user.model";
2 | import { compare, genSalt, hash } from "bcrypt";
3 | import jwt from "jsonwebtoken";
4 | import { RefreshToken } from "../db/models/refresh-token.model";
5 | import { mailservice } from "./mail.service";
6 |
7 | class UserService {
8 | public findUserByEmail = async (email: string): Promise => {
9 | const user = await User.findOne({ where: { email } });
10 |
11 | return user;
12 | };
13 |
14 | public createUser = async (email: string, password: string) => {
15 | const salt = await genSalt();
16 | const hashedPassword = await hash(password, salt);
17 | const verificationToken = jwt.sign({ email }, "verify_email");
18 | const user = await User.create({
19 | email: email,
20 | password: hashedPassword,
21 | verificationToken: verificationToken,
22 | });
23 |
24 | //call method to send verification email
25 | await this.sendVerificationEmail(user);
26 | };
27 |
28 | private sendVerificationEmail = async (user: User) => {
29 | const mail = {
30 | from: "kuluruvineeth8623@gmail.com",
31 | to: user.email,
32 | subject: "Welcome to Google Docs",
33 | text: `click the following link to verify your email : http://localhost:3000/user/verify-email/${user.verificationToken}`,
34 | };
35 |
36 | await mailservice.sendMail(mail);
37 | };
38 |
39 | public sendPasswordResetEmail = async (user: User) => {
40 | const mail = {
41 | from: "kuluruvineeth8623@gmail.com",
42 | to: user.email,
43 | subject: "Reset your password!",
44 | text: `http://localhost:3000/user/reset-email/${user.passwordResetToken}`,
45 | };
46 |
47 | await mailservice.sendMail(mail);
48 | };
49 |
50 | public checkPassword = async (
51 | user: User,
52 | password: string
53 | ): Promise => {
54 | return await compare(password, user.password);
55 | };
56 |
57 | public getRequestUser = async (
58 | user: User | RequestUser
59 | ): Promise => {
60 | if (user instanceof User) {
61 | const userWithRoles = await User.scope("withRoles").findByPk(user.id);
62 | const roles = userWithRoles?.userRoles.map(
63 | (userRole) => userRole.role.name
64 | );
65 | return {
66 | id: user.id,
67 | email: user.email,
68 | roles: roles,
69 | } as RequestUser;
70 | } else return user;
71 | };
72 |
73 | public generateAuthResponse = async (
74 | user: RequestUser | User
75 | ): Promise => {
76 | const requestUser = await this.getRequestUser(user);
77 |
78 | const accessToken = jwt.sign(requestUser, "access_token", {
79 | expiresIn: "24h",
80 | });
81 |
82 | const refreshToken = jwt.sign(requestUser, "refresh_token", {
83 | expiresIn: "24h",
84 | });
85 |
86 | await RefreshToken.destroy({
87 | where: { userId: requestUser.id },
88 | });
89 |
90 | await RefreshToken.create({ token: refreshToken, userId: requestUser.id });
91 |
92 | return { accessToken, refreshToken };
93 | };
94 |
95 | public getIsTokenActive = async (token: string): Promise => {
96 | const refreshToken = await RefreshToken.findOne({
97 | where: { token },
98 | });
99 |
100 | return refreshToken != null;
101 | };
102 |
103 | public logoutUser = async (userId: number) => {
104 | await RefreshToken.destroy({
105 | where: {
106 | userId,
107 | },
108 | });
109 | };
110 |
111 | public findUserById = async (id: number): Promise => {
112 | const user = await User.findByPk(id);
113 | return user;
114 | };
115 |
116 | public resetPassword = async (user: User) => {
117 | const passwordResetToken = jwt.sign(
118 | { id: user.id, email: user.email },
119 | "password_reset",
120 | {
121 | expiresIn: "24h",
122 | }
123 | );
124 |
125 | await user.update({ passwordResetToken });
126 |
127 | //send password reset email method should be called
128 | await this.sendPasswordResetEmail(user);
129 | };
130 |
131 | public findUserByPasswordResetToken = async (
132 | email: string,
133 | passwordResetToken: string
134 | ): Promise => {
135 | const user = await User.findOne({
136 | where: {
137 | email,
138 | passwordResetToken,
139 | },
140 | });
141 |
142 | return user;
143 | };
144 |
145 | public updatePassword = async (user: User, password: string) => {
146 | const salt = await genSalt();
147 | const hashedPassword = await hash(password, salt);
148 | await user.update({
149 | password: hashedPassword,
150 | });
151 | };
152 |
153 | public findUserByVerificationToken = async (
154 | email: string,
155 | verificationToken: string
156 | ): Promise => {
157 | const user = await User.findOne({
158 | where: {
159 | email,
160 | verificationToken,
161 | },
162 | });
163 |
164 | return user;
165 | };
166 |
167 | public updateIsVerified = async (user: User, isVerified: boolean) => {
168 | await user.update({
169 | isVerified,
170 | });
171 | };
172 | }
173 |
174 | const userService = new UserService();
175 |
176 | export { userService };
177 |
--------------------------------------------------------------------------------
/server/src/types/enums/permission-enum.ts:
--------------------------------------------------------------------------------
1 | enum PermissionEnum {
2 | VIEW = "VIEW",
3 | EDIT = "EDIT",
4 | }
5 |
6 | export default PermissionEnum;
7 |
--------------------------------------------------------------------------------
/server/src/types/enums/role-enum.ts:
--------------------------------------------------------------------------------
1 | enum RoleEnum {
2 | ADMIN = "ADMIN",
3 | SUPERADMIN = "SUPERADMIN",
4 | }
5 |
6 | export default RoleEnum;
7 |
--------------------------------------------------------------------------------
/server/src/types/enums/socket-events-enum.ts:
--------------------------------------------------------------------------------
1 | enum SocketEvent {
2 | SEND_CHANGES = "send-changes",
3 | RECEIVE_CHANGES = "receive-changes",
4 | CURRENT_USERS_UPDATE = "current-users-update",
5 | }
6 |
7 | export default SocketEvent;
8 |
--------------------------------------------------------------------------------
/server/src/types/interfaces/environment.d.ts:
--------------------------------------------------------------------------------
1 | declare global {
2 | namespace NodeJS {
3 | interface ProcessEnv {
4 | NODE_ENV?: "test" | "development" | "production";
5 | HOST?: string;
6 | PORT?: string;
7 | DATABASE_URL?: string;
8 | USER?: string;
9 | PASSWORD?: string;
10 | DB_HOST?: string;
11 | DB_PORT?: string;
12 | DATABASE?: string;
13 | }
14 | }
15 | }
16 |
17 | export {};
18 |
--------------------------------------------------------------------------------
/server/src/types/interfaces/express/index.d.ts:
--------------------------------------------------------------------------------
1 | import { RequestUser } from "../global";
2 |
3 | declare global {
4 | namespace Express {
5 | interface Request {
6 | user?: RequestUser;
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/server/src/types/interfaces/global.d.ts:
--------------------------------------------------------------------------------
1 | declare global {
2 | interface ResponseMessage {
3 | msg: string;
4 | }
5 |
6 | interface RequestUser {
7 | id: string;
8 | email: string;
9 | roles: Array;
10 | }
11 |
12 | interface TokenPair {
13 | accessToken: string;
14 | refreshToken: string;
15 | }
16 | }
17 |
18 | export { RequestUser };
19 |
--------------------------------------------------------------------------------
/server/src/validators/auth.validator.ts:
--------------------------------------------------------------------------------
1 | import { body } from "express-validator";
2 |
3 | class AuthValidator {
4 | public login = [
5 | body("email")
6 | .isEmail()
7 | .normalizeEmail()
8 | .withMessage("Must provide a valid email address"),
9 | body("password").exists().withMessage("Must provide a password"),
10 | ];
11 |
12 | public refreshToken = [
13 | body("token").exists().withMessage("Must provide a valid token."),
14 | ];
15 | }
16 |
17 | const authValidator = new AuthValidator();
18 |
19 | export { authValidator };
20 |
--------------------------------------------------------------------------------
/server/src/validators/document.validator.ts:
--------------------------------------------------------------------------------
1 | import { body } from "express-validator";
2 |
3 | class DocumentValidator {
4 | public update = [
5 | body("title")
6 | .optional()
7 | .isLength({ min: 0, max: 25 })
8 | .withMessage("Title must be between 0 and 25 characters."),
9 | // body("content")
10 | // .optional()
11 | // .custom((value) => {
12 | // try {
13 | // JSON.parse(value);
14 | // } catch (error) {
15 | // console.log(error);
16 | // throw new Error("Invalid document content.");
17 | // }
18 | // }),
19 | body("isPublic")
20 | .optional()
21 | .isBoolean()
22 | .withMessage("Must provide true or false value"),
23 | ];
24 | }
25 |
26 | const documentValidator = new DocumentValidator();
27 |
28 | export { documentValidator };
29 |
--------------------------------------------------------------------------------
/server/src/validators/share.validator.ts:
--------------------------------------------------------------------------------
1 | import { body } from "express-validator";
2 | import PermissionEnum from "../types/enums/permission-enum";
3 |
4 | class ShareValidator {
5 | public create = [
6 | body("email")
7 | .isEmail()
8 | .normalizeEmail()
9 | .withMessage("Must provide a valid email to share this document with."),
10 | body("permission").custom((value) => {
11 | if (!Object.values(PermissionEnum).includes(value))
12 | throw new Error("Must provide a valid document permisson.");
13 | else return true;
14 | }),
15 | ];
16 | }
17 |
18 | const shareValidator = new ShareValidator();
19 |
20 | export { shareValidator };
21 |
--------------------------------------------------------------------------------
/server/src/validators/user.validator.ts:
--------------------------------------------------------------------------------
1 | import { body } from "express-validator";
2 | import { userService } from "../services/user.service";
3 |
4 | class UserValidator {
5 | public register = [
6 | body("email")
7 | .isEmail()
8 | .normalizeEmail()
9 | .withMessage("Must provide a valid email address."),
10 | body("email").custom(async (value) => {
11 | const user = await userService.findUserByEmail(value);
12 |
13 | if (user) {
14 | return Promise.reject("User with email already exists.");
15 | }
16 | return true;
17 | }),
18 | body("password1")
19 | .isLength({ min: 8, max: 25 })
20 | .withMessage("Passsword must be between 8 to 25 characters."),
21 | body("password1")
22 | .matches(/\d/)
23 | .withMessage("Password must contain atleast 1 number"),
24 | body("password2").custom((value, { req }) => {
25 | if (value !== req.body.password1) {
26 | throw new Error("Passwords must match.");
27 | }
28 | return true;
29 | }),
30 | ];
31 |
32 | public resetPassword = [
33 | body("email")
34 | .isEmail()
35 | .normalizeEmail()
36 | .withMessage("Must provide a valid email address."),
37 | ];
38 |
39 | public confirmResetPassword = [
40 | body("password1")
41 | .isLength({ min: 8, max: 25 })
42 | .withMessage("Password must be between 8 to 25 characters."),
43 | body("password1")
44 | .matches(/\d/)
45 | .withMessage("Password must contain atleast 1 number"),
46 | body("password2").custom((value, { req }) => {
47 | if (value !== req.body.password1) {
48 | throw new Error("Passwords must match.");
49 | }
50 | return true;
51 | }),
52 | ];
53 | }
54 |
55 | const userValidator = new UserValidator();
56 |
57 | export { userValidator };
58 |
--------------------------------------------------------------------------------
/server/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs" /* Specify what module code is generated. */,
29 | // "rootDir": "./", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | // "outDir": "./", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
83 |
84 | /* Type Checking */
85 | "strict": true /* Enable all strict type-checking options. */,
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */,
108 | "outDir": "dist",
109 | "rootDir": "./",
110 | "experimentalDecorators": true,
111 | "emitDecoratorMetadata": true,
112 | "typeRoots": ["src/types/interfaces", "./node_modules/@types"]
113 | }
114 | }
115 |
--------------------------------------------------------------------------------