├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── client ├── .dockerignore ├── .gitignore ├── Dockerfile ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt ├── src │ ├── App.js │ ├── App.module.scss │ ├── App.test.js │ ├── cache.js │ ├── components │ │ ├── Home │ │ │ ├── Home.js │ │ │ └── Home.module.scss │ │ ├── Login │ │ │ └── Login.module.scss │ │ ├── Logout │ │ │ ├── Logout.js │ │ │ └── Logout.module.scss │ │ ├── Profile │ │ │ ├── Profile.js │ │ │ └── Profile.module.scss │ │ ├── Routes │ │ │ └── Routes.js │ │ ├── TopBar │ │ │ ├── TopBar.js │ │ │ └── TopBar.module.scss │ │ └── login │ │ │ └── login.js │ ├── constants │ │ └── constants.js │ ├── hooks │ │ ├── auth.js │ │ ├── provideAppState.js │ │ └── provideTheme.js │ ├── index.css │ ├── index.js │ ├── queries │ │ └── profile.js │ ├── react-app-env.d.ts │ ├── reportWebVitals.js │ ├── setupTests.js │ └── styles │ │ ├── base.module.scss │ │ └── themeProperties.module.scss └── tsconfig.json ├── docker-compose.yml ├── heroku.yml ├── package.json └── server ├── .dockerignore ├── Dockerfile.dev ├── nodemon.json ├── package-lock.json ├── package.json ├── src ├── controllers │ └── auth.ts ├── db │ ├── index.ts │ └── models │ │ └── user.ts ├── graphql │ ├── datasources │ │ └── user.ts │ ├── resolvers.ts │ └── schema.ts ├── index.ts └── routes │ └── auth.ts ├── tsconfig.json └── tslint.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | # Server tsc dist 107 | server/dist 108 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Prod docker config 2 | 3 | FROM node as prod 4 | 5 | ENV NODE_ENV=prod 6 | 7 | # Set up and build client 8 | 9 | WORKDIR /app/client 10 | 11 | COPY ./client/package*.json ./ 12 | 13 | RUN npm install 14 | 15 | COPY ./client ./ 16 | 17 | RUN npm run build 18 | 19 | # Set up server 20 | 21 | WORKDIR /app/server 22 | 23 | COPY server/package*.json ./ 24 | 25 | RUN npm install 26 | 27 | COPY ./server ./ 28 | 29 | RUN npm run build 30 | 31 | EXPOSE 5000 32 | 33 | CMD ["node", "dist/index.js"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Cory Crowley 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fullstack-auth-docker-boilerplate 2 | This is a monolithic, containerized, boilerplate repo for kickstarting fullstack applications. The boilerplate code sets up an authentication API using google login OAuth2 with users saved to a Mongo database. It exposes an Apollo graphQL server for querying and mutating data. This repo also sets up a simple front-end which includes persistent login with google, protected routes, themes and modular scss style-sheets, and login / logout auth token management. 3 | 4 | The client, server, and database are then containerized using the `docker-compose.yml` file. Once you've installed [docker](https://www.docker.com/products/docker-desktop), you can spin up the the development environment with two simple commands. 5 | 6 | 1. `docker-compose build` 7 | 2. `docker-compose up` 8 | 3. (when you've finished) `docker-compose down` 9 | 10 | ## Backend boilerplate 11 | - Node server with Express to simplify server and serve static frontend build files 12 | - REST endpoint for authentication `/auth/googleLogin`, this listens for requests from frontend with google `tokenId`, and uses Google's OAuth2Client `google-auth-library` to verify the token, create a user in the mongo database, sign a `jsonwebtoken` using the users ID, and respond with that `jsonwebtoken` and basic google profile data to the frontend. 13 | - Graph QL context to verify all `/graphql` API requests have valid `Authorization: Bearer [token]` 14 | - GraphQL using Apollo server on `/graphql` endpoint for exposing data 15 | - Mongo database set up with `User` model 16 | 17 | ## Frontend 18 | - `create-react-app` boilerplate code 19 | - `react-router-dom` set up with `/login`, `/profile`, and `/` pages 20 | - `PrivateRoute` wrapper which requires user to be logged in to access route, otherwise redirects to `/login` 21 | - `react-google-login` components for Login / Logout functionality via Google OAuth2 22 | - `auth.js` hook to build auth context using React hooks, handle local storage control of auth token, get authentication status, and basic user details 23 | - `cache.js` creates an Apollo client [InMemoryCache](https://www.apollographql.com/docs/react/caching/cache-configuration/). [Reactive variables](https://www.apollographql.com/docs/react/local-state/reactive-variables/) can be defined here. 24 | - `provideTheme.js` hook to hold app theme state and save to localStorage 25 | - `provideAppState.js` hook which combines useReducer and react context to provide a mini redux-style app store. This may be useful for setting app level state such as which modal is open, etc.. 26 | - `base.module.scss` provides base styles with `_.className` naming. 27 | - `themeProperties.module.scss` defines themed [custom css properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) to use throughout the app. If you want to support multiple themes, make sure to add each --propertyName key to both :root{} and [data-theme="themeName"]{} blocks 28 | 29 | # Set up development environment 30 | ## Create .env file in the root directory of the repository with the following fields. 31 | *Note, you may also need to copy the .env file to the `/server` directory when deploying the containers. 32 | 33 | |Key | Value| 34 | |-------- | -----| 35 | |PORT | `5000`| 36 | |DB_USER | `username`| 37 | |DB_PASSWORD | `password`| 38 | |GOOGLE_OAUTH_CLIENT_ID | OAUTH client ID from console.cloud.google.com| 39 | |JWT_SECRET | any string that is complex and not easy to guess / brute force | 40 | |MONGO_CONNECTION_URL | connection string for live mongoDB (not required for local development) | 41 | 42 | ## Install Docker desktop 43 | 1. Navigate to [here](https://www.docker.com/products/docker-desktop), download and install docker desktop 44 | 45 | ## Set up Google OAuth Credentials 46 | 1. Navigate to console.cloud.google.com 47 | 2. Create new project 48 | 3. In navigation menu, go to APIs & Services -> Credentials 49 | 4. Create credentials -> OAuth client ID 50 | 5. Follow steps and copy google client ID into both the .env & component 51 | 52 | ## Build docker images 53 | 1. Navigate to the root project directory (where docker-compose.yml is located) 54 | 2. Once docker-desktop is installed, run `docker-compose build`. This will build the the following images for your app 55 | - lightweight mongo database server (port 27017 by default) 56 | - lightweight node server for API and graphql (port 5000 by default) 57 | - lightweight node server for serving create-react-app client build (port 3000 by default) 58 | 59 | ## Start / stop docker containers 60 | 1. To start, run `docker-compose up` 61 | 2. To stop, run `docker-compose down` 62 | 63 | ## Test Graph QL Queries 64 | Once containers are running, navigate to `http://localhost:5000/graphql` to play around with your API and make test queries. 65 | 66 | *Note `5000` should be replaced with the port you set in the .env file. Also, because the API is protected by authentication middleware, you won't be able to access the graphql playground unless your requests contain a valid valid `Authorization: Bearer [token]`. To get a valid token, you can log the token returned from the `/auth/googleLogin` API call on the frontend. You can also view the client `localStorage` session key and copy the token from there. Once you have the token, paste it into the HTTP header section of the graphql playground. 67 | -------------------------------------------------------------------------------- /client/.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/Dockerfile: -------------------------------------------------------------------------------- 1 | # download a base version of node from Docker Hub 2 | FROM node:14 3 | 4 | # create the working directory for the application called /app that will be the root 5 | WORKDIR /app 6 | 7 | # npm install the dependencies and run the start script from each package.json 8 | CMD ls -ltr && npm install && npm start 9 | -------------------------------------------------------------------------------- /client/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 the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will 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/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fullstack-auth-docker-boilerplate-client", 3 | "proxy": "http://api:5000/", 4 | "version": "0.1.0", 5 | "private": true, 6 | "dependencies": { 7 | "@apollo/client": "^3.3.6", 8 | "@testing-library/jest-dom": "^5.11.6", 9 | "@testing-library/react": "^11.2.2", 10 | "@testing-library/user-event": "^12.3.0", 11 | "@types/jest": "^26.0.15", 12 | "@types/node": "^14.14.10", 13 | "@types/react": "^17.0.0", 14 | "@types/react-dom": "^17.0.0", 15 | "classnames": "^2.2.6", 16 | "graphql": "^15.4.0", 17 | "install": "^0.13.0", 18 | "jwt-decode": "^3.1.2", 19 | "node-sass": "^4.14.1", 20 | "npm": "^6.14.9", 21 | "react": "^17.0.1", 22 | "react-dom": "^17.0.1", 23 | "react-google-login": "^5.1.25", 24 | "react-router-dom": "^5.2.0", 25 | "react-scripts": "4.0.1", 26 | "typescript": "^4.1.3", 27 | "web-vitals": "^0.2.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 | } 54 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccrowley96/fullstack-auth-docker-boilerplate/80121f9264d888b946495c14a8470b7b7cec6021/client/public/favicon.ico -------------------------------------------------------------------------------- /client/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/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccrowley96/fullstack-auth-docker-boilerplate/80121f9264d888b946495c14a8470b7b7cec6021/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccrowley96/fullstack-auth-docker-boilerplate/80121f9264d888b946495c14a8470b7b7cec6021/client/public/logo512.png -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { ProvideAuth } from './hooks/auth'; 3 | import Routes from './components/Routes/Routes'; 4 | import { ApolloProvider, createHttpLink, ApolloClient, from } from '@apollo/client'; 5 | import { setContext } from '@apollo/client/link/context'; 6 | import { onError } from '@apollo/client/link/error'; 7 | import { ProvideTheme } from "./hooks/provideTheme"; 8 | import { ProvideAppState } from './hooks/provideAppState'; 9 | import { cache } from './cache'; 10 | 11 | // The classnames/bind dependency ensures scss modules are scoped at the component level 12 | // This means only this component can access styles in the App.module.scss file. 13 | import classNames from 'classnames/bind'; 14 | const cx = classNames.bind(require('./App.module.scss')); 15 | 16 | export default function App() { 17 | return ( 18 | 19 | 20 | 21 | 22 |
23 | 24 |
25 |
26 |
27 |
28 |
29 | ); 30 | } 31 | 32 | const httpLink = createHttpLink({ 33 | uri: '/graphql', 34 | }); 35 | 36 | // Use this function to globally handle graphQL errors 37 | const errorLink = onError(({ graphQLErrors, networkError, operation }) => { 38 | if (graphQLErrors) 39 | graphQLErrors.forEach(({ message, extensions: { code }}) => { 40 | console.log(`[GraphQL error]:`, {message, code}) 41 | 42 | // Redirect to login if session invalid 43 | if(code === 'UNAUTHENTICATED'){ 44 | localStorage.removeItem('session'); 45 | window.location = '/login'; 46 | } 47 | 48 | }); 49 | if (networkError) console.log(`[Network error]: ${networkError}`); 50 | }) 51 | 52 | // Attach auth token to outgoing GraphQL requests 53 | const authLink = setContext((_, { headers }) => { 54 | // get the authentication token from local storage if it exists 55 | let token = null; 56 | let sessionString = localStorage.getItem('session'); 57 | if(sessionString){ 58 | let session = JSON.parse(sessionString); 59 | if(session.token){ 60 | token = session.token; 61 | } 62 | } 63 | // return the headers to the context so httpLink can read them 64 | return { 65 | headers: { 66 | ...headers, 67 | authorization: token ? `Bearer ${token}` : "", 68 | } 69 | } 70 | }); 71 | 72 | export const client = new ApolloClient({ 73 | link: from([ 74 | authLink, 75 | errorLink, 76 | httpLink 77 | ]), 78 | cache 79 | }) -------------------------------------------------------------------------------- /client/src/App.module.scss: -------------------------------------------------------------------------------- 1 | @import './styles/base.module.scss'; // Gives this component access to base styles 2 | body{ 3 | background-color: var(--color-bg-canvas); // Themed background 4 | color: var(--color-text-primary); // Themed text color 5 | width: 100%; 6 | } 7 | a{ 8 | color: var(--color-text-primary); // Themed text color 9 | } 10 | *{ 11 | box-sizing: border-box; 12 | } -------------------------------------------------------------------------------- /client/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /client/src/cache.js: -------------------------------------------------------------------------------- 1 | import { InMemoryCache, makeVar } from '@apollo/client' 2 | 3 | // Define apollo client cache and reactive variables here 4 | // testIdVar can be used in functional components with the 5 | // testId = useReactiveVar(testIdVar) hook. Anytime you change the value 6 | // of testId in the cache by calling testIdVar(newVal), all components 7 | // subscribed to this var via the useReactiveVar hook will be updated 8 | // with the new value. For more details, see: 9 | // https://www.apollographql.com/docs/react/local-state/reactive-variables/ 10 | 11 | export const cache = new InMemoryCache({ 12 | typePolicies: { 13 | Query: { 14 | fields: { 15 | testId: { 16 | read() { 17 | return testIdVar(); 18 | } 19 | } 20 | } 21 | } 22 | } 23 | }) 24 | 25 | export const testIdVar = makeVar(null); -------------------------------------------------------------------------------- /client/src/components/Home/Home.js: -------------------------------------------------------------------------------- 1 | import classNames from 'classnames/bind'; 2 | const cx = classNames.bind(require('./Home.module.scss')); 3 | 4 | const Home = () => { 5 | return( 6 |
7 |

Home page

8 | This is public content 9 |
10 | ); 11 | } 12 | 13 | export default Home; -------------------------------------------------------------------------------- /client/src/components/Home/Home.module.scss: -------------------------------------------------------------------------------- 1 | @import '../../styles/base.module.scss'; // Gives this component access to base styles 2 | 3 | .homeWrapper{ 4 | width: 100%; 5 | padding: 20px; 6 | } 7 | -------------------------------------------------------------------------------- /client/src/components/Login/Login.module.scss: -------------------------------------------------------------------------------- 1 | @import '../../styles/base.module.scss'; // Gives this component access to base styles 2 | 3 | .loginWrapper{ 4 | background-color: rgba(0,0,0,.1); 5 | border-radius: 8px; 6 | max-width: 400px; 7 | height: 140px; 8 | position: absolute; 9 | left: 0; 10 | right: 0; 11 | top: 0; 12 | bottom: 0; 13 | margin: auto; 14 | } 15 | 16 | .googleLogin{ 17 | position: absolute; 18 | box-sizing: border-box; 19 | display: flex; 20 | justify-content: center; 21 | width: 100%; 22 | margin: auto; 23 | bottom: 0px; 24 | padding: 20px; 25 | } 26 | 27 | .loginTitle{ 28 | text-align: center; 29 | } -------------------------------------------------------------------------------- /client/src/components/Logout/Logout.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { 3 | useHistory, 4 | useLocation 5 | } from "react-router-dom"; 6 | import { useAuth } from '../../hooks/auth'; 7 | import { GoogleLogout } from 'react-google-login'; 8 | import { useTheme } from "../../hooks/provideTheme"; 9 | 10 | import classNames from 'classnames/bind'; 11 | const cx = classNames.bind(require('./Logout.module.scss')); 12 | 13 | export default function Logout(){ 14 | let history = useHistory(); 15 | let location = useLocation(); 16 | const { theme } = useTheme() 17 | let auth = useAuth(); 18 | 19 | const responseGoogle = async (googleResponse) => { 20 | // Set auth state 21 | auth.deauthenticateUser(() => history.replace('/login')); 22 | } 23 | 24 | if(auth.isUserAuthenticated() && location.pathname !== '/login'){ 25 | return( 26 |
27 | 34 |
35 | ) 36 | } else{ 37 | return null; 38 | } 39 | } -------------------------------------------------------------------------------- /client/src/components/Logout/Logout.module.scss: -------------------------------------------------------------------------------- 1 | @import '../../styles/base.module.scss'; // Gives this component access to base styles -------------------------------------------------------------------------------- /client/src/components/Profile/Profile.js: -------------------------------------------------------------------------------- 1 | import { USER_QUERY } from '../../queries/profile'; 2 | import { useQuery } from '@apollo/client'; 3 | import Logout from '../Logout/Logout'; 4 | import { useTheme } from '../../hooks/provideTheme'; 5 | 6 | import classNames from 'classnames/bind'; 7 | const cx = classNames.bind(require('./Profile.module.scss')); 8 | 9 | export default function Profile({user}){ 10 | 11 | const { loading, error, data } = useQuery(USER_QUERY, {variables: {id: user._id}}); 12 | const { toggleTheme } = useTheme(); 13 | 14 | if (loading) return

Loading...

; 15 | if (error) return

Error :(

; 16 | 17 | if(data.user){ 18 | let { user } = data; 19 | let registeredDate = new Date(Number(user.registered)); 20 | return( 21 |
22 | profile 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 |
Name{user.name}
Email{user.email}
ID{user.id}
Registered{registeredDate.toLocaleString()}
43 | 44 |
45 | 46 |
47 | 48 |
49 | 50 |
51 | 52 | This is private content (you must be logged in to view) 53 |
54 | ) 55 | } else{ 56 | return null; 57 | } 58 | } -------------------------------------------------------------------------------- /client/src/components/Profile/Profile.module.scss: -------------------------------------------------------------------------------- 1 | @import '../../styles/base.module.scss'; // Gives this component access to base styles 2 | 3 | .profileWrapper{ 4 | width: 100%; 5 | padding: 20px; 6 | th, td { 7 | padding: 10px; 8 | } 9 | } 10 | 11 | .profileBtn{ 12 | margin: 20px 0px; 13 | } -------------------------------------------------------------------------------- /client/src/components/Routes/Routes.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useAuth } from '../../hooks/auth'; 3 | import { 4 | BrowserRouter as Router, 5 | Switch, 6 | Route, 7 | Redirect, 8 | Link, 9 | } from "react-router-dom"; 10 | import Login from '../Login/Login'; 11 | import Profile from '../Profile/Profile'; 12 | import Home from '../Home/Home'; 13 | import TopBar from '../TopBar/TopBar'; 14 | 15 | export default function Routes(){ 16 | const auth = useAuth(); 17 | return( 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | ) 34 | } 35 | 36 | // A wrapper for that redirects to the login 37 | // screen if you're not yet authenticated. 38 | function PrivateRoute({ children, ...rest }) { 39 | let auth = useAuth(); 40 | return ( 41 | 44 | auth.isUserAuthenticated() ? ( 45 | children 46 | ) : ( 47 | 53 | ) 54 | } 55 | /> 56 | ); 57 | } -------------------------------------------------------------------------------- /client/src/components/TopBar/TopBar.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { useAuth } from '../../hooks/auth'; 3 | import { Link } from "react-router-dom"; 4 | 5 | import classNames from 'classnames/bind'; 6 | const cx = classNames.bind(require('./TopBar.module.scss')); 7 | 8 | const TopBar = () => { 9 | const { session } = useAuth(); 10 | 11 | const picture = session?.user?.picture; 12 | 13 | return( 14 |
15 |
16 | 17 | Home 18 | 19 |
20 |
21 | { 22 | picture ? 23 | 24 | profile 25 | 26 | : 27 | Profile 28 | } 29 | 30 |
31 |
32 | ) 33 | } 34 | 35 | export default TopBar; -------------------------------------------------------------------------------- /client/src/components/TopBar/TopBar.module.scss: -------------------------------------------------------------------------------- 1 | .topBar{ 2 | height: 60px; 3 | width: 100%; 4 | display: flex; 5 | justify-content: flex-end; 6 | } 7 | 8 | .navItem{ 9 | height: 100%; 10 | margin: 0px 8px; 11 | display: flex; 12 | justify-content: center; 13 | align-items: center; 14 | } 15 | 16 | .profile{ 17 | width: 60px; 18 | .imgWrapper{ 19 | height: 60%; 20 | width: 60%; 21 | .userImg{ 22 | height: 100%; 23 | width: 100%; 24 | border-radius: 50%; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /client/src/components/login/login.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { 3 | useHistory, 4 | useLocation 5 | } from "react-router-dom"; 6 | import { useAuth } from '../../hooks/auth'; 7 | import { GoogleLogin } from 'react-google-login'; 8 | import { useTheme } from "../../hooks/provideTheme"; 9 | 10 | import classNames from 'classnames/bind'; 11 | const cx = classNames.bind(require('./Login.module.scss')); 12 | 13 | export default function Login(){ 14 | let history = useHistory(); 15 | let location = useLocation(); 16 | const { theme } = useTheme(); 17 | let auth = useAuth(); 18 | 19 | let { from } = location.state || { from: { pathname: "/" } }; 20 | 21 | const responseGoogle = async (googleResponse) => { 22 | console.log(googleResponse) 23 | let response = await fetch(`/auth/googleLogin`, { 24 | method: 'POST', 25 | headers: { 26 | 'Content-Type': 'application/json' 27 | }, 28 | body: JSON.stringify({tokenId: googleResponse.tokenId}) 29 | }); 30 | 31 | if(response.status === 200){ 32 | let parsedResponse = await response.json(); 33 | // Set auth state 34 | auth.authenticateUser(parsedResponse, () => history.push(from)); 35 | } else{ 36 | console.log('Google login failed') 37 | } 38 | } 39 | 40 | return( 41 |
42 |

Login to continue

43 |
44 | 53 |
54 |
55 | ) 56 | } -------------------------------------------------------------------------------- /client/src/constants/constants.js: -------------------------------------------------------------------------------- 1 | export const themes = { 2 | light: 'light', 3 | dark: 'dark' 4 | } 5 | 6 | export const actionTypes = { 7 | // Redux style action type keys here, example action for setting the active modal 8 | // SET_ACTIVE_MODAL: 'SET_ACTIVE_MODAL' 9 | } -------------------------------------------------------------------------------- /client/src/hooks/auth.js: -------------------------------------------------------------------------------- 1 | import jwt_decode from "jwt-decode"; 2 | import React, { useContext, createContext, useState } from "react"; 3 | import { client } from '../App'; 4 | 5 | const authContext = createContext(); 6 | 7 | export function ProvideAuth({children}){ 8 | const auth = useProvideAuth(); 9 | 10 | return( 11 | 12 | {children} 13 | 14 | ); 15 | } 16 | 17 | export function useAuth(){ 18 | return useContext(authContext); 19 | } 20 | 21 | const getSessionFromLocalStorage = () => { 22 | let sessionString = localStorage.getItem('session'); 23 | if(sessionString){ 24 | let session = JSON.parse(sessionString); 25 | if(session){ 26 | return session 27 | } 28 | } 29 | return null; 30 | } 31 | 32 | export function useProvideAuth(){ 33 | let sessionFromStorage = getSessionFromLocalStorage(); 34 | const [session, setSession] = useState(sessionFromStorage); 35 | 36 | const authenticateUser = (session, cb) => { 37 | setSession(session); 38 | localStorage.setItem('session', JSON.stringify(session)); 39 | cb(); 40 | } 41 | 42 | const deauthenticateUser = cb => { 43 | localStorage.removeItem('session'); 44 | client.clearStore(); 45 | setSession(null); 46 | cb(); 47 | } 48 | 49 | const isUserAuthenticated = () => { 50 | let session = getSessionFromLocalStorage(); 51 | if(session){ 52 | let token = session.token; 53 | const { exp } = jwt_decode(token); 54 | const expirationTime = (exp * 1000); 55 | if(Date.now() >= expirationTime){ 56 | localStorage.removeItem('session'); 57 | } else{ 58 | return true; 59 | } 60 | } 61 | return false; 62 | } 63 | 64 | const getToken = () => { 65 | let session = getSessionFromLocalStorage(); 66 | return session?.token; 67 | } 68 | 69 | return { 70 | session, 71 | authenticateUser, 72 | deauthenticateUser, 73 | isUserAuthenticated, 74 | getToken 75 | } 76 | } -------------------------------------------------------------------------------- /client/src/hooks/provideAppState.js: -------------------------------------------------------------------------------- 1 | import React, { useContext, useReducer, useMemo } from "react"; 2 | import { actionTypes } from "../constants/constants"; 3 | 4 | const AppStateContext = React.createContext(); 5 | export const useAppState = () => useContext(AppStateContext); 6 | 7 | const initialAppState = { 8 | 9 | } 10 | 11 | const AppStateReducer = (state, action) =>{ 12 | switch(action.type){ 13 | /* Example reducer for setting active modal 14 | case actionTypes.SET_ACTIVE_MODAL: 15 | return {...state, activeModal: action.payload} 16 | */ 17 | default: 18 | throw new Error(); 19 | } 20 | } 21 | 22 | export const ProvideAppState = ({children}) =>{ 23 | const appState = useProvideAppState(); 24 | return( 25 | 26 | {children} 27 | 28 | ) 29 | } 30 | 31 | const useProvideAppState = () => { 32 | const [appState, appDispatch] = useReducer(AppStateReducer, initialAppState); 33 | 34 | const appStateContextValue = useMemo(() => { 35 | return { appState, appDispatch }; 36 | }, [appState, appDispatch]); 37 | 38 | return appStateContextValue; 39 | } -------------------------------------------------------------------------------- /client/src/hooks/provideTheme.js: -------------------------------------------------------------------------------- 1 | import React, { useContext, useEffect, useState } from "react"; 2 | import { themes } from '../constants/constants' 3 | 4 | const Theme = React.createContext(); 5 | export const useTheme = () => useContext(Theme); 6 | 7 | export const ProvideTheme = ({children}) =>{ 8 | const theme = useProvideTheme(); 9 | return( 10 | 11 | {children} 12 | 13 | ) 14 | } 15 | 16 | const useProvideTheme = () => { 17 | const initialTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : themes.light; 18 | 19 | useEffect(() => { 20 | document.documentElement.setAttribute('data-theme', initialTheme); 21 | }, [initialTheme]) 22 | 23 | const [theme, setTheme] = useState(initialTheme); 24 | 25 | const toggleTheme = () => { 26 | if(theme === themes.dark){ 27 | document.documentElement.setAttribute('data-theme', 'light'); 28 | localStorage.setItem('theme', themes.light); 29 | setTheme(themes.light) 30 | } else{ 31 | document.documentElement.setAttribute('data-theme', 'dark'); 32 | localStorage.setItem('theme', themes.dark); 33 | setTheme(themes.dark) 34 | } 35 | } 36 | 37 | return {theme, toggleTheme} 38 | } -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /client/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | import './styles/themeProperties.module.scss'; // Import theme properties 7 | 8 | ReactDOM.render( 9 | 10 | 11 | , 12 | document.getElementById('root') 13 | ); 14 | 15 | // If you want to start measuring performance in your app, pass a function 16 | // to log results (for example: reportWebVitals(console.log)) 17 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 18 | reportWebVitals(); -------------------------------------------------------------------------------- /client/src/queries/profile.js: -------------------------------------------------------------------------------- 1 | import { gql } from '@apollo/client'; 2 | 3 | export const USER_QUERY = gql` 4 | query getUser($id: ID!) { 5 | user(id: $id){ 6 | id 7 | name 8 | email 9 | given_name 10 | family_name 11 | picture 12 | registered 13 | } 14 | } 15 | `; -------------------------------------------------------------------------------- /client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /client/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /client/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /client/src/styles/base.module.scss: -------------------------------------------------------------------------------- 1 | /* 2 | This file contains base styles for the application. You can access these styles by importing 3 | this file at the top of a components style-sheet 4 | 5 | @import 'path-to-this-file/base.modules.scss' 6 | 7 | Then adding any of the class names in this file to a components className prop. 8 | 9 | 10 | 11 | It's a good idea to prefix these classNames with _ to differentiate them with component scoped 12 | styles. 13 | */ 14 | 15 | ._btn{ 16 | color: var(--color-btn-text); 17 | background-color: var(--color-btn-bg); 18 | border-radius: 6px; 19 | padding: 5px 16px; 20 | font-size: 14px; 21 | font-weight: 600; 22 | border: 1px solid; 23 | line-height: 20px; 24 | white-space: nowrap; 25 | vertical-align: middle; 26 | cursor: pointer; 27 | } -------------------------------------------------------------------------------- /client/src/styles/themeProperties.module.scss: -------------------------------------------------------------------------------- 1 | /* 2 | This file defines css properties which can be consumed in any style-sheet to 3 | maintain consistency in the app. If you want to support multiple themes, 4 | you must add matching properties for each theme, otherwise, just add your 5 | --propertyName variables to the :root block. 6 | 7 | Example consumption: 8 | var(--color-btn-text) will grab the current --color-btn-text value 9 | */ 10 | 11 | // Default styles 12 | :root{ 13 | --color-btn-text: #24292e; 14 | --color-btn-bg: #fafbfc; 15 | --color-bg-canvas: #fff; 16 | --color-text-primary: #24292e; 17 | } 18 | 19 | 20 | // Dark theme styles 21 | [data-theme="dark"] { 22 | --color-btn-text: #c9d1d9; 23 | --color-btn-bg: #21262d; 24 | --color-bg-canvas: #0d1117; 25 | --color-text-primary: #c9d1d9; 26 | } -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | services: 3 | client: 4 | build: 5 | context: ./client 6 | dockerfile: ./Dockerfile 7 | volumes: 8 | - "./client:/app" 9 | ports: 10 | - "3000:3000" 11 | depends_on: 12 | - server 13 | restart: always 14 | 15 | server: 16 | container_name: api 17 | build: 18 | context: ./server 19 | dockerfile: Dockerfile.dev 20 | volumes: 21 | - ./server:/app 22 | expose: 23 | - "5000" 24 | ports: 25 | - "5000:5000" 26 | - "9229:9229" 27 | command: npm start 28 | environment: 29 | PORT: "${PORT}" 30 | DB_USER: "${DB_USER}" 31 | DB_PASSWORD: "${DB_PASSWORD}" 32 | JWT_SECRET: "${JWT_SECRET}" 33 | GOOGLE_OAUTH_CLIENT_ID: "${GOOGLE_OAUTH_CLIENT_ID}" 34 | 35 | depends_on: 36 | - mongodb_container 37 | 38 | mongodb_container: 39 | image: mongo:latest 40 | environment: 41 | MONGO_INITDB_ROOT_USERNAME: "${DB_USER}" 42 | MONGO_INITDB_ROOT_PASSWORD: "${DB_PASSWORD}" 43 | ports: 44 | - 27017:27017 45 | volumes: 46 | - mongodb_data_container:/data/db 47 | restart: always 48 | 49 | volumes: 50 | mongodb_data_container: -------------------------------------------------------------------------------- /heroku.yml: -------------------------------------------------------------------------------- 1 | build: 2 | docker: 3 | web: Dockerfile 4 | 5 | run: 6 | web: -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fullstack-auth-docker-boilerplate", 3 | "version": "1.0.0", 4 | "description": "Fullstack boilerplate app setup with google auth", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/ccrowley96/fullstack-auth-docker-boilerplate.git" 12 | }, 13 | "author": "Cory Crowley", 14 | "license": "ISC", 15 | "bugs": { 16 | "url": "https://github.com/ccrowley96/fullstack-auth-docker-boilerplate/issues" 17 | }, 18 | "homepage": "https://github.com/ccrowley96/fullstack-auth-docker-boilerplate#readme" 19 | } 20 | -------------------------------------------------------------------------------- /server/.dockerignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules -------------------------------------------------------------------------------- /server/Dockerfile.dev: -------------------------------------------------------------------------------- 1 | # download a base version of node from Docker Hub 2 | FROM node 3 | 4 | # create the working directory for the application called /app that will be the root 5 | WORKDIR /app 6 | 7 | COPY ./package*.json ./ 8 | 9 | ENV NODE_ENV=dev 10 | 11 | RUN npm install 12 | 13 | USER node -------------------------------------------------------------------------------- /server/nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "verbose": true, 3 | "ignore": ["src/**/*.spec.ts"], 4 | "watch": ["src/**/*.ts", "src/**/*.js"], 5 | "execMap": { 6 | "ts": "node --inspect=0.0.0.0:9229 --nolazy -r ts-node/register" 7 | } 8 | } -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fullstack-auth-docker-boilerplate-server", 3 | "version": "1.0.0", 4 | "description": "Node/Express server configured with Google auth and mongoose/mongo db", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "tsc", 9 | "start": "nodemon src/index.ts" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/ccrowley96/fullstack-boilerplate.git" 14 | }, 15 | "author": "Cory Crowley", 16 | "license": "MIT", 17 | "bugs": { 18 | "url": "https://github.com/ccrowley96/fullstack-boilerplate/issues" 19 | }, 20 | "homepage": "https://github.com/ccrowley96/fullstack-boilerplate#readme", 21 | "devDependencies": { 22 | "@types/express": "^4.17.9", 23 | "@types/node": "^14.14.14", 24 | "cross-env": "^7.0.2", 25 | "shx": "^0.3.3", 26 | "ts-node": "^9.1.1", 27 | "tslint": "^6.1.3" 28 | }, 29 | "dependencies": { 30 | "@apollo/client": "^3.3.4", 31 | "apollo-datasource-mongodb": "^0.2.8", 32 | "apollo-server-express": "^2.19.0", 33 | "concurrently": "^5.3.0", 34 | "cors": "^2.8.5", 35 | "dotenv": "^8.2.0", 36 | "express": "^4.17.1", 37 | "express-graphql": "^0.12.0", 38 | "google-auth-library": "^6.1.3", 39 | "graphql": "^15.4.0", 40 | "install": "^0.13.0", 41 | "jsonwebtoken": "^8.5.1", 42 | "jwt-decode": "^3.1.2", 43 | "mongoose": "^5.11.4", 44 | "morgan": "^1.10.0", 45 | "nodemon": "^2.0.6", 46 | "npm": "^6.14.9", 47 | "path": "^0.12.7", 48 | "typescript": "^4.1.3" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /server/src/controllers/auth.ts: -------------------------------------------------------------------------------- 1 | import { OAuth2Client } from 'google-auth-library'; 2 | import jwt from 'jsonwebtoken'; 3 | import express from 'express'; 4 | import { User } from '../db/index'; 5 | 6 | 7 | const client = new OAuth2Client( 8 | process.env.GOOGLE_OAUTH_CLIENT_ID 9 | ) 10 | 11 | const sendUserInfo = (res: express.Response, user) => { 12 | const {_id, name, email} = user; 13 | const token = jwt.sign({_id}, process.env.JWT_SECRET, {expiresIn: '7d'}) 14 | 15 | res.json({ 16 | token, 17 | user: {_id, name, email} 18 | }) 19 | } 20 | 21 | export const googleLogin = async (req: express.Request, res: express.Response) => { 22 | const { tokenId } = req.body; 23 | let response: any; 24 | try{ 25 | response = await client.verifyIdToken({idToken: tokenId, audience: process.env.GOOGLE_OAUTH_CLIENT_ID}); 26 | } catch(err){ 27 | console.log(err); 28 | res.status(400).json({error: "Error verifying ID token"}); 29 | return; 30 | } 31 | 32 | const {name, given_name, family_name, email, picture} = response.payload; 33 | 34 | try{ 35 | const user = await User.findOne({email}); 36 | if(user){ 37 | sendUserInfo(res, user); 38 | } else{ 39 | let newUser = new User({name, given_name, family_name, email, picture}); 40 | newUser = await newUser.save(); 41 | if(newUser){ 42 | sendUserInfo(res, newUser); 43 | } else{ 44 | throw new Error('Error saving new user'); 45 | } 46 | } 47 | } catch (err){ 48 | console.log(err); 49 | res.status(400).json({error: "Something went wrong..."}); 50 | } 51 | } -------------------------------------------------------------------------------- /server/src/db/index.ts: -------------------------------------------------------------------------------- 1 | 2 | import dotenv from 'dotenv'; 3 | import mongoose from 'mongoose'; 4 | import UserModel from './models/user' 5 | 6 | dotenv.config(); 7 | 8 | export const User = UserModel; 9 | 10 | export const connectDB = async () => { 11 | try{ 12 | let conn = null; 13 | if(process.env.NODE_ENV === 'dev'){ // Connect to DEV DB 14 | conn = await mongoose.connect(`mongodb://mongodb_container:27017`, 15 | { 16 | user: process.env.DB_USER , 17 | pass: process.env.DB_PASSWORD, 18 | useNewUrlParser: true, 19 | useUnifiedTopology: true, 20 | useCreateIndex: true 21 | }) 22 | } else{ // Connect to PROD DB 23 | conn = await mongoose.connect(process.env.MONGO_CONNECTION_URL, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true}) 24 | } 25 | // Check connection 26 | console.log(`MongoDB Connected ${conn.connection.host}`); 27 | } catch(err){ 28 | console.error(err); 29 | process.exit(1); 30 | } 31 | } -------------------------------------------------------------------------------- /server/src/db/models/user.ts: -------------------------------------------------------------------------------- 1 | import mongoose from 'mongoose'; 2 | 3 | const userSchema = new mongoose.Schema({ 4 | name: String, 5 | email: String, 6 | given_name: String, 7 | family_name: String, 8 | picture: String, 9 | registered: { 10 | type: Date, 11 | default: Date.now 12 | } 13 | }) 14 | 15 | export default mongoose.model('User', userSchema); -------------------------------------------------------------------------------- /server/src/graphql/datasources/user.ts: -------------------------------------------------------------------------------- 1 | import { MongoDataSource } from 'apollo-datasource-mongodb'; 2 | import { User } from '../../db/index'; 3 | import mongoose from 'mongoose'; 4 | 5 | export default class Users extends MongoDataSource{ 6 | async findUser(id){ 7 | if(!id) return null; 8 | const user = await User.findById(new mongoose.Types.ObjectId(id)); 9 | return user ? user: null; 10 | } 11 | 12 | async getAllUsers(){ 13 | const users = await User.find({}); 14 | return users; 15 | } 16 | } -------------------------------------------------------------------------------- /server/src/graphql/resolvers.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | // More granular type resolvers go here 3 | // <-- 4 | 5 | // Query resolvers 6 | Query: { 7 | users: (_, __, { dataSources: { users } }) => { 8 | return users.getAllUsers(); 9 | }, 10 | user: (_, { id }, { dataSources: { users } }) =>{ 11 | return users.findUser(id) 12 | }, 13 | me: (_, __, { user}) => { 14 | return user 15 | } 16 | } 17 | 18 | // Mutation resolvers 19 | } -------------------------------------------------------------------------------- /server/src/graphql/schema.ts: -------------------------------------------------------------------------------- 1 | import { gql } from 'apollo-server-express'; 2 | 3 | const typeDefs = gql` 4 | type User{ 5 | id: ID! 6 | name: String 7 | email: String 8 | given_name: String 9 | family_name: String 10 | picture: String 11 | registered: String 12 | } 13 | 14 | type Query { 15 | users: [User]! 16 | user(id: ID!): User 17 | me: User 18 | } 19 | `; 20 | 21 | export default typeDefs; -------------------------------------------------------------------------------- /server/src/index.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import cors from 'cors'; 3 | import dotenv from 'dotenv' 4 | import path from 'path'; 5 | import { connectDB, User } from './db/index'; 6 | import morgan from 'morgan'; 7 | import authApi from './routes/auth'; 8 | import jwt from 'jsonwebtoken'; 9 | import typeDefs from './graphql/schema'; 10 | import resolvers from './graphql/resolvers'; 11 | import Users from './graphql/datasources/user'; 12 | import { ApolloServer, AuthenticationError } from 'apollo-server-express'; 13 | import mongoose from 'mongoose'; 14 | 15 | dotenv.config(); 16 | 17 | const app = express(); 18 | const port = process.env.PORT || 5000; 19 | 20 | // Connect to mongo database 21 | connectDB(); 22 | 23 | // Log all server-dev requests with morgan 24 | if(process.env.NODE_ENV === 'dev'){ 25 | app.use(morgan('dev')) 26 | } 27 | 28 | // Enable Cross Origin Requests with CORS 29 | app.use(cors({credentials: true, origin: true})); 30 | 31 | // Use JSON 32 | app.use(express.json()); 33 | 34 | // HTTPS Redirect for production 35 | if (process.env.NODE_ENV !== 'dev') { 36 | app.enable('trust proxy'); 37 | app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { 38 | if (req.secure) { 39 | next(); 40 | } else { 41 | res.redirect('https://' + req.headers.host + req.url); 42 | } 43 | }); 44 | } 45 | 46 | // Serve static client build files 47 | app.use(express.static(path.join(__dirname, '../../client/build'))); 48 | 49 | // Auth API used for login/sign-up 50 | app.use('/auth', authApi); 51 | 52 | // Use Apollo context to verify authentication token 53 | const context = async({req, res}) => { 54 | const token = req?.headers?.authorization?.replace('Bearer ', ''); 55 | if(!token) { 56 | throw new AuthenticationError('No authorization token provided!'); 57 | } 58 | try{ 59 | const user = jwt.verify(token, process.env.JWT_SECRET); 60 | req.userId = user._id; 61 | } catch(err){ 62 | throw new AuthenticationError('API access unauthorized!'); 63 | } 64 | 65 | const user = await User.findById(new mongoose.Types.ObjectId(req.userId)); 66 | 67 | if(user){ 68 | return { user } 69 | } else{ 70 | throw new AuthenticationError('User not found'); 71 | } 72 | } 73 | 74 | // Initialize Graph QL Apollo server 75 | const server = new ApolloServer({ 76 | typeDefs, 77 | resolvers, 78 | dataSources: () => ({ 79 | users: new Users(User) 80 | }), 81 | context 82 | }); 83 | 84 | server.applyMiddleware({ app }); 85 | 86 | // Default catch all -> to index.html (for react-router) 87 | app.get('/*', (_, res: express.Response) => { 88 | res.sendFile(path.join(__dirname, '../../client/build/index.html'), function(err) { 89 | if (err) { 90 | res.status(500).send(err) 91 | } 92 | }) 93 | }) 94 | 95 | // Start Listening 96 | app.listen(port, () => { 97 | console.log(`Graph QL server running on port: ${port}!`); 98 | } 99 | ); -------------------------------------------------------------------------------- /server/src/routes/auth.ts: -------------------------------------------------------------------------------- 1 | import express from 'express'; 2 | import { googleLogin } from '../controllers/auth'; // Import auth controller 3 | 4 | const router = express.Router(); 5 | 6 | router.post('/googleLogin', googleLogin); 7 | 8 | export default router; -------------------------------------------------------------------------------- /server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "esModuleInterop": true, 5 | "target": "es6", 6 | "noImplicitAny": false, 7 | "moduleResolution": "node", 8 | "sourceMap": true, 9 | "outDir": "dist", 10 | "baseUrl": ".", 11 | "allowJs": true, 12 | "paths": { 13 | "*": [ 14 | "node_modules/*" 15 | ] 16 | }, 17 | "types": [ 18 | "node" 19 | ] 20 | }, 21 | "include": [ 22 | "src/**/*" 23 | ], 24 | "exclude": 25 | [ 26 | "node_modules", 27 | "**/*.spec.ts" 28 | ] 29 | } -------------------------------------------------------------------------------- /server/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": [ 4 | "tslint:recommended" 5 | ], 6 | "jsRules": { 7 | "no-console": [ false ] 8 | }, 9 | "rules": { 10 | "trailing-comma": [ false ], 11 | "no-console": [ false ], 12 | "only-arrow-functions": false 13 | }, 14 | "rulesDirectory": [] 15 | } --------------------------------------------------------------------------------