├── client └── googledocs │ ├── src │ ├── components │ │ ├── atoms │ │ │ ├── logo │ │ │ │ ├── index.ts │ │ │ │ └── logo.tsx │ │ │ ├── modal │ │ │ │ ├── index.ts │ │ │ │ └── modal.tsx │ │ │ ├── toast │ │ │ │ ├── index.ts │ │ │ │ └── toast.tsx │ │ │ ├── errors │ │ │ │ ├── index.ts │ │ │ │ └── errors.tsx │ │ │ ├── spinner │ │ │ │ ├── index.ts │ │ │ │ └── spinner.tsx │ │ │ ├── text-field │ │ │ │ ├── index.ts │ │ │ │ └── text-field.tsx │ │ │ ├── document-card │ │ │ │ ├── index.ts │ │ │ │ └── document-card.tsx │ │ │ ├── icon-button │ │ │ │ ├── index.ts │ │ │ │ └── icon-button.tsx │ │ │ ├── user-dropdown │ │ │ │ ├── index.ts │ │ │ │ └── user-dropdown.tsx │ │ │ ├── document-searchbar │ │ │ │ ├── index.ts │ │ │ │ └── document-searchbar.tsx │ │ │ ├── create-document-button │ │ │ │ ├── index.ts │ │ │ │ └── create-document-btn.tsx │ │ │ ├── document-menu-button │ │ │ │ ├── index.ts │ │ │ │ └── document-menu-button.tsx │ │ │ └── font-select │ │ │ │ ├── index.ts │ │ │ │ └── font-select.tsx │ │ ├── molecules │ │ │ ├── auth-route │ │ │ │ ├── index.ts │ │ │ │ └── auth-route.tsx │ │ │ ├── shared-users │ │ │ │ ├── index.ts │ │ │ │ └── shared-users.tsx │ │ │ ├── documents-list │ │ │ │ ├── index.ts │ │ │ │ └── documents-list.tsx │ │ │ ├── editor-toolbar │ │ │ │ ├── index.ts │ │ │ │ └── editor-toolbar.tsx │ │ │ ├── document-menu-bar │ │ │ │ ├── index.ts │ │ │ │ └── document-menu-bar.tsx │ │ │ └── share-document-modal │ │ │ │ ├── index.ts │ │ │ │ └── share-document-modal.tsx │ │ └── organisms │ │ │ ├── toast-manager │ │ │ ├── index.ts │ │ │ └── toast-manager.tsx │ │ │ ├── document-editor │ │ │ ├── index.ts │ │ │ └── document-editor.tsx │ │ │ ├── document-header │ │ │ ├── index.ts │ │ │ └── document-header.tsx │ │ │ └── document-create-header │ │ │ ├── index.ts │ │ │ └── document-create-header.tsx │ ├── index.css │ ├── types │ │ ├── enums │ │ │ ├── permission-enum.ts │ │ │ └── socket-events-enum.ts │ │ └── interfaces │ │ │ ├── token.ts │ │ │ ├── action.ts │ │ │ ├── input.ts │ │ │ ├── document-user.ts │ │ │ ├── toast.ts │ │ │ └── document.ts │ ├── App.js │ ├── services │ │ ├── api.ts │ │ ├── auth-service.ts │ │ ├── document-user-service.ts │ │ └── document-service.ts │ ├── utils │ │ └── constants.ts │ ├── hooks │ │ ├── use-random-background.tsx │ │ ├── use-local-storage.tsx │ │ ├── use-documents.tsx │ │ ├── use-window-size.tsx │ │ ├── use-document.tsx │ │ └── use-auth.tsx │ ├── App.css │ ├── pages │ │ ├── user │ │ │ └── verify-email.tsx │ │ ├── document │ │ │ ├── create.tsx │ │ │ └── index.tsx │ │ ├── login │ │ │ └── index.tsx │ │ └── register │ │ │ └── index.tsx │ ├── index.js │ ├── logo.svg │ └── contexts │ │ ├── auth-context.tsx │ │ ├── toast-context.tsx │ │ ├── document-context.tsx │ │ └── editor-context.tsx │ ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html │ ├── tsconfig.json │ ├── tailwind.config.js │ ├── package.json │ └── README.md ├── .gitignore ├── server ├── src │ ├── types │ │ ├── enums │ │ │ ├── role-enum.ts │ │ │ ├── permission-enum.ts │ │ │ └── socket-events-enum.ts │ │ └── interfaces │ │ │ ├── express │ │ │ └── index.d.ts │ │ │ ├── global.d.ts │ │ │ └── environment.d.ts │ ├── middleware │ │ ├── catch-async.ts │ │ ├── error-handler.ts │ │ └── auth.ts │ ├── config │ │ ├── smtp.config.ts │ │ ├── db.config.ts │ │ └── env.config.ts │ ├── services │ │ ├── mail.service.ts │ │ ├── document.service.ts │ │ └── user.service.ts │ ├── db │ │ └── models │ │ │ ├── refresh-token.model.ts │ │ │ ├── user-role.model.ts │ │ │ ├── index.ts │ │ │ ├── role.model.ts │ │ │ ├── document-user.model.ts │ │ │ ├── document.model.ts │ │ │ └── user.model.ts │ ├── responses │ │ └── index.ts │ ├── validators │ │ ├── auth.validator.ts │ │ ├── share.validator.ts │ │ ├── document.validator.ts │ │ └── user.validator.ts │ ├── routes │ │ ├── auth.route.ts │ │ ├── index.ts │ │ ├── user.route.ts │ │ └── document.route.ts │ ├── index.ts │ ├── controllers │ │ ├── auth │ │ │ └── auth.controller.ts │ │ ├── document │ │ │ ├── share │ │ │ │ └── share.controller.ts │ │ │ └── document.controller.ts │ │ └── user │ │ │ └── user.controller.ts │ └── server.ts ├── .env.development ├── package.json └── tsconfig.json └── .vscode └── launch.json /client/googledocs/src/components/atoms/logo/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./logo"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/modal/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./modal"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/toast/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./toast"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/errors/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./errors"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/spinner/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./spinner"; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | server/node_modules/* 2 | client/node_modules/* 3 | node_modules/* 4 | dist 5 | node_modules -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/text-field/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./text-field"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/index.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/document-card/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-card"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/icon-button/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./icon-button"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/user-dropdown/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./user-dropdown"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/auth-route/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./auth-route"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/shared-users/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./shared-users"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/organisms/toast-manager/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./toast-manager"; 2 | -------------------------------------------------------------------------------- /client/googledocs/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/document-searchbar/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-searchbar"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/documents-list/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./documents-list"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/editor-toolbar/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./editor-toolbar"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/organisms/document-editor/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-editor"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/organisms/document-header/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-header"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/create-document-button/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./create-document-btn"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/atoms/document-menu-button/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-menu-button"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/document-menu-bar/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-menu-bar"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/molecules/share-document-modal/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./share-document-modal"; 2 | -------------------------------------------------------------------------------- /client/googledocs/src/components/organisms/document-create-header/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from "./document-create-header"; 2 | -------------------------------------------------------------------------------- /client/googledocs/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src"], 3 | "compilerOptions": { 4 | "jsx": "react-jsx" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /client/googledocs/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/HEAD/client/googledocs/public/favicon.ico -------------------------------------------------------------------------------- /client/googledocs/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/HEAD/client/googledocs/public/logo192.png -------------------------------------------------------------------------------- /client/googledocs/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kuluruvineeth/googledocs-clone/HEAD/client/googledocs/public/logo512.png -------------------------------------------------------------------------------- /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/permission-enum.ts: -------------------------------------------------------------------------------- 1 | enum PermissionEnum { 2 | VIEW = "VIEW", 3 | EDIT = "EDIT", 4 | } 5 | 6 | export default PermissionEnum; 7 | -------------------------------------------------------------------------------- /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/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/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/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/input.ts: -------------------------------------------------------------------------------- 1 | interface InputProps { 2 | label?: string; 3 | placeholder?: string; 4 | errors?: Array; 5 | } 6 | 7 | export default InputProps; 8 | -------------------------------------------------------------------------------- /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/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/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/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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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/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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/components/atoms/logo/logo.tsx: -------------------------------------------------------------------------------- 1 | import { Link } from "react-router-dom"; 2 | 3 | const Logo = () => { 4 | return ( 5 | 9 | 17 | 22 | 23 | 24 | ); 25 | }; 26 | 27 | export default Logo; 28 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 |
31 |
32 |
33 |
34 |
35 | ); 36 | }; 37 | 38 | export default Spinner; 39 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 |
38 |
42 | 43 |
44 |
45 | 46 | )} 47 |
48 | ); 49 | }; 50 | 51 | export default Document; 52 | -------------------------------------------------------------------------------- /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/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/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/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/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/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 65 | 70 | 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/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/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/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/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/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 |