├── .gitignore
├── README.md
├── client
├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
│ ├── components
│ ├── App
│ │ ├── App.css
│ │ ├── App.test.js
│ │ └── index.js
│ ├── Home
│ │ ├── auth.js
│ │ ├── index.js
│ │ └── nonauth.js
│ ├── Login
│ │ └── index.js
│ ├── Navigation
│ │ ├── auth.js
│ │ ├── index.js
│ │ └── nonauth.js
│ ├── NotFound
│ │ └── index.js
│ ├── Signup
│ │ └── index.js
│ └── WithAuthenticate
│ │ └── index.js
│ ├── constants
│ ├── action_types.js
│ └── routes.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ ├── reducers
│ ├── index.js
│ └── session.js
│ ├── serviceWorker.js
│ └── store
│ └── index.js
└── server
├── .babelrc
├── graphql
├── resolvers
│ ├── handlerGenerators
│ │ └── auth.js
│ └── index.js
└── schema
│ └── index.js
├── index.js
├── models
└── user.js
├── package-lock.json
└── package.json
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | node_modules
5 |
6 | # testing
7 | coverage
8 |
9 | # production
10 | build
11 |
12 | # misc
13 | .env
14 | .DS_Store
15 | .env.local
16 | .env.development.local
17 | .env.test.local
18 | .env.production.local
19 |
20 | npm-debug.log*
21 | yarn-debug.log*
22 | yarn-error.log*
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # mern-graphql-jwt
2 |
--------------------------------------------------------------------------------
/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/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `npm start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `npm test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `npm run build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `npm run eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | 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.
35 |
36 | 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.
37 |
38 | 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.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `npm run build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "client",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "axios": "^0.18.0",
7 | "react": "^16.8.2",
8 | "react-dom": "^16.8.2",
9 | "react-router": "^4.3.1",
10 | "react-router-dom": "^4.3.1",
11 | "react-scripts": "2.1.5",
12 | "redux": "^4.0.1",
13 | "redux-logger": "^3.0.6",
14 | "redux-react-hook": "^3.1.0"
15 | },
16 | "scripts": {
17 | "start": "react-scripts start",
18 | "build": "react-scripts build",
19 | "test": "react-scripts test",
20 | "eject": "react-scripts eject"
21 | },
22 | "eslintConfig": {
23 | "extends": "react-app"
24 | },
25 | "browserslist": [
26 | ">0.2%",
27 | "not dead",
28 | "not ie <= 11",
29 | "not op_mini all"
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/client/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aboudicheng/mern-graphql-jwt/1d44f610613291140b04ea9ab7b5186da4baa917/client/public/favicon.ico
--------------------------------------------------------------------------------
/client/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
25 | React App
26 |
27 |
28 | You need to enable JavaScript to run this app.
29 |
30 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/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 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/client/src/components/App/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-header {
6 | background-color: #282c34;
7 | min-height: calc(100vh - 64px);
8 | display: flex;
9 | flex-direction: column;
10 | align-items: center;
11 | justify-content: center;
12 | font-size: calc(10px + 2vmin);
13 | color: white;
14 | }
15 |
16 | .navbar {
17 | height: 64px;
18 | display: flex;
19 | flex-direction: row;
20 | justify-content: space-between;
21 | align-items: center;
22 | padding: 0 50px;
23 | flex: 0 0 auto;
24 | background: #282c34;
25 | }
26 |
27 | .navbar-right {
28 | width: 150px;
29 | display: flex;
30 | justify-content: space-around;
31 | }
32 |
33 | a {
34 | text-decoration: none;
35 | color: white;
36 | }
37 |
38 | a:hover {
39 | color: #4CAF50;
40 | }
41 |
42 | .auth-form {
43 | border-radius: 5px;
44 | background-color: #f2f2f2;
45 | padding: 20px;
46 | width: 400px;
47 | }
48 |
49 | .form-input {
50 | width: 100%;
51 | padding: 12px 20px;
52 | margin: 8px 0;
53 | display: inline-block;
54 | border: 1px solid #ccc;
55 | border-radius: 4px;
56 | box-sizing: border-box;
57 | }
58 |
59 | .form-submit {
60 | width: 100px;
61 | background-color: #4CAF50;
62 | color: white;
63 | padding: 14px 20px;
64 | margin: 8px 0;
65 | border: none;
66 | border-radius: 4px;
67 | cursor: pointer;
68 | }
69 |
70 | .form-submit:hover {
71 | background-color: #45a049;
72 | }
--------------------------------------------------------------------------------
/client/src/components/App/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render( , div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/client/src/components/App/index.js:
--------------------------------------------------------------------------------
1 | import React, { useCallback } from 'react';
2 | import {
3 | BrowserRouter as Router,
4 | Route,
5 | Switch
6 | } from 'react-router-dom';
7 | import Navigation from '../Navigation';
8 | import Home from '../Home';
9 | import Signup from '../Signup';
10 | import Login from '../Login';
11 | import NotFound from '../NotFound';
12 | import useWithAuthenticate from '../WithAuthenticate';
13 | import * as routes from '../../constants/routes';
14 | import { useMappedState } from 'redux-react-hook';
15 | import './App.css';
16 |
17 | function App() {
18 | useWithAuthenticate();
19 |
20 | const mapState = useCallback((state) => ({
21 | loading: state.sessionState.loading
22 | }), [])
23 |
24 | const { loading } = useMappedState(mapState);
25 |
26 | if (loading) return Loading...
27 |
28 | return (
29 |
30 |
31 |
32 |
33 |
34 | } />
35 | } />
36 | } />
37 |
38 |
39 |
40 |
41 |
42 | );
43 | }
44 |
45 | export default App;
46 |
--------------------------------------------------------------------------------
/client/src/components/Home/auth.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | function AuthHome() {
4 | return (
5 | <>
6 | Home
7 | You are logged in
8 | >
9 | )
10 | }
11 |
12 | export default AuthHome;
--------------------------------------------------------------------------------
/client/src/components/Home/index.js:
--------------------------------------------------------------------------------
1 | import React, { useCallback } from 'react';
2 | import { useMappedState } from 'redux-react-hook';
3 | import AuthHome from './auth';
4 | import NonAuthHome from './nonauth';
5 |
6 | function Home() {
7 | const mapState = useCallback((state) => ({
8 | authUser: state.sessionState.authUser
9 | }), [])
10 |
11 | const { authUser } = useMappedState(mapState);
12 |
13 | return authUser ? :
14 | }
15 |
16 | export default Home;
--------------------------------------------------------------------------------
/client/src/components/Home/nonauth.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | function NonAuthHome() {
4 | return (
5 | <>
6 | Home
7 | Homepage for everyone
8 | >
9 | )
10 | }
11 |
12 | export default NonAuthHome;
--------------------------------------------------------------------------------
/client/src/components/Login/index.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import axios from 'axios';
3 | import { useDispatch } from 'redux-react-hook';
4 | import { withRouter } from 'react-router-dom';
5 | import * as actions from '../../constants/action_types';
6 | import * as routes from '../../constants/routes';
7 |
8 | function Login(props) {
9 | const [email, setEmail] = useState("");
10 | const [password, setPassword] = useState("");
11 | const [error, setError] = useState(null);
12 | const [loading, setLoading] = useState(false);
13 | const dispatch = useDispatch();
14 |
15 | const handleChange = setter => e => {
16 | setter(e.target.value);
17 | }
18 |
19 | const submit = async (e) => {
20 | e.preventDefault();
21 | setLoading(true);
22 |
23 | try {
24 | const requestBody = {
25 | query: `
26 | query {
27 | login(email: "${email}", password: "${password}") {
28 | _id
29 | token
30 | email
31 | }
32 | }
33 | `
34 | };
35 |
36 | const { data } = await axios.post('http://localhost:5000/graphql', requestBody);
37 |
38 | if (data.errors) {
39 | setError(data.errors[0].message);
40 | setLoading(false);
41 | }
42 | else {
43 | setError(null);
44 | setLoading(false);
45 | const { _id, token } = await data.data.login;
46 |
47 | dispatch({
48 | type: actions.SET_AUTH_USER,
49 | authUser: {
50 | _id,
51 | email
52 | }
53 | })
54 | localStorage.setItem('token', token);
55 | props.history.push(routes.HOME);
56 | }
57 | }
58 | catch (e) {
59 | setError(e);
60 | setLoading(false);
61 | }
62 | }
63 |
64 | return (
65 | <>
66 | Login
67 |
77 | >
78 | )
79 | }
80 |
81 | export default withRouter(Login);
--------------------------------------------------------------------------------
/client/src/components/Navigation/auth.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { useDispatch } from 'redux-react-hook';
3 | import { Link } from 'react-router-dom';
4 | import * as routes from '../../constants/routes';
5 | import * as actions from '../../constants/action_types';
6 |
7 | function AuthNavigation() {
8 | const dispatch = useDispatch();
9 |
10 | function logout() {
11 | dispatch({ type: actions.SET_AUTH_USER, authUser: null });
12 | localStorage.removeItem('token');
13 | }
14 |
15 | return (
16 |
17 |
HOME
18 |
19 | LOGOUT
20 |
21 |
22 | )
23 | }
24 |
25 | export default AuthNavigation;
--------------------------------------------------------------------------------
/client/src/components/Navigation/index.js:
--------------------------------------------------------------------------------
1 | import React, { useCallback } from 'react';
2 | import { useMappedState } from 'redux-react-hook';
3 | import AuthNavigation from './auth';
4 | import NonAuthNavigation from './nonauth';
5 |
6 | function Navigation() {
7 | const mapState = useCallback((state) => ({
8 | authUser: state.sessionState.authUser
9 | }), [])
10 |
11 | const { authUser } = useMappedState(mapState);
12 |
13 | return authUser ? :
14 | }
15 |
16 | export default Navigation;
--------------------------------------------------------------------------------
/client/src/components/Navigation/nonauth.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Link } from 'react-router-dom';
3 | import * as routes from '../../constants/routes';
4 |
5 | function NonAuthNavigation() {
6 | return (
7 |
8 |
HOME
9 |
10 | SIGN UP
11 | LOGIN
12 |
13 |
14 | )
15 | }
16 |
17 | export default NonAuthNavigation;
--------------------------------------------------------------------------------
/client/src/components/NotFound/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | function NotFound() {
4 | return Oops...Page does not exist!
5 | }
6 |
7 | export default NotFound;
--------------------------------------------------------------------------------
/client/src/components/Signup/index.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import axios from 'axios';
3 | import { useDispatch } from 'redux-react-hook';
4 | import { withRouter } from 'react-router-dom';
5 | import * as actions from '../../constants/action_types';
6 | import * as routes from '../../constants/routes';
7 |
8 | function Signup(props) {
9 | const [email, setEmail] = useState("");
10 | const [password, setPassword] = useState("");
11 | const [confirm, setConfirm] = useState("");
12 | const [error, setError] = useState(null);
13 | const [loading, setLoading] = useState(false);
14 | const dispatch = useDispatch();
15 |
16 | const handleChange = setter => e => {
17 | setter(e.target.value);
18 | }
19 |
20 | const submit = async (e) => {
21 | e.preventDefault();
22 | setLoading(true);
23 |
24 | try {
25 | const requestBody = {
26 | query: `
27 | mutation {
28 | createUser(userInput: {
29 | email: "${email}"
30 | password: "${password}"
31 | confirm: "${confirm}"
32 | }) {
33 | _id
34 | token
35 | email
36 | }
37 | }
38 | `
39 | };
40 |
41 | const { data } = await axios.post('http://localhost:5000/graphql', requestBody);
42 |
43 | if (data.errors) {
44 | setError(data.errors[0].message);
45 | setLoading(false);
46 | }
47 | else {
48 | setError(null);
49 | setLoading(false);
50 | const { _id, token } = await data.data.createUser;
51 |
52 | dispatch({
53 | type: actions.SET_AUTH_USER,
54 | authUser: {
55 | _id,
56 | email
57 | }
58 | })
59 | localStorage.setItem('token', token);
60 | props.history.push(routes.HOME);
61 | }
62 | }
63 | catch (e) {
64 | setError(e);
65 | setLoading(false);
66 | }
67 | }
68 |
69 | return (
70 | <>
71 | Sign up
72 |
83 | >
84 | )
85 | }
86 |
87 | export default withRouter(Signup);
--------------------------------------------------------------------------------
/client/src/components/WithAuthenticate/index.js:
--------------------------------------------------------------------------------
1 | import { useEffect } from 'react';
2 | import { useDispatch } from 'redux-react-hook';
3 | import axios from 'axios';
4 | import * as actions from '../../constants/action_types';
5 |
6 | async function authenticate(dispatch) {
7 | const token = localStorage.getItem('token');
8 |
9 | if (!!token) {
10 | try {
11 | const requestBody = {
12 | query: `
13 | query {
14 | verifyToken(token: "${token}") {
15 | _id
16 | email
17 | }
18 | }
19 | `
20 | }
21 |
22 | const { data } = await axios.post('http://localhost:5000/graphql', requestBody);
23 | const user = await data.data.verifyToken;
24 |
25 | if (user) {
26 | dispatch({
27 | type: actions.SET_AUTH_USER,
28 | authUser: {
29 | _id: user._id,
30 | email: user.email
31 | }
32 | })
33 | }
34 | else {
35 | dispatch({ type: actions.SET_AUTH_USER, authUser: null });
36 | localStorage.removeItem('token');
37 | }
38 | }
39 | catch {
40 | dispatch({ type: actions.SET_AUTH_USER, authUser: null });
41 | }
42 | }
43 | else {
44 | dispatch({ type: actions.SET_AUTH_USER, authUser: null });
45 | }
46 | }
47 |
48 | function useWithAuthenticate() {
49 | const dispatch = useDispatch();
50 | useEffect(() => {
51 | authenticate(dispatch);
52 | }, [])
53 | }
54 |
55 | export default useWithAuthenticate;
56 |
--------------------------------------------------------------------------------
/client/src/constants/action_types.js:
--------------------------------------------------------------------------------
1 | export const SET_AUTH_USER = "SET_AUTH_USER";
--------------------------------------------------------------------------------
/client/src/constants/routes.js:
--------------------------------------------------------------------------------
1 | export const HOME = '/';
2 | export const LOGIN = '/login';
3 | export const SIGN_UP = '/signup';
--------------------------------------------------------------------------------
/client/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/client/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './components/App';
5 | import { StoreContext } from 'redux-react-hook';
6 | import store from './store';
7 | import * as serviceWorker from './serviceWorker';
8 |
9 | ReactDOM.render(
10 |
11 |
12 | ,
13 | document.getElementById('root'));
14 |
15 | // If you want your app to work offline and load faster, you can change
16 | // unregister() to register() below. Note this comes with some pitfalls.
17 | // Learn more about service workers: http://bit.ly/CRA-PWA
18 | serviceWorker.unregister();
19 |
--------------------------------------------------------------------------------
/client/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/client/src/reducers/index.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from 'redux';
2 | import sessionReducer from './session';
3 |
4 | const rootReducer = combineReducers({
5 | sessionState: sessionReducer,
6 | });
7 |
8 | export default rootReducer;
--------------------------------------------------------------------------------
/client/src/reducers/session.js:
--------------------------------------------------------------------------------
1 | import { SET_AUTH_USER } from '../constants/action_types'
2 |
3 | const INITIAL_STATE = {
4 | authUser: null,
5 | loading: true
6 | };
7 |
8 | function sessionReducer(state = INITIAL_STATE, action) {
9 | switch (action.type) {
10 | case SET_AUTH_USER: {
11 | return { authUser: action.authUser, loading: false };
12 | }
13 | default: return state;
14 | }
15 | }
16 |
17 | export default sessionReducer;
--------------------------------------------------------------------------------
/client/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read http://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/client/src/store/index.js:
--------------------------------------------------------------------------------
1 | import { createStore, applyMiddleware } from 'redux';
2 | import logger from 'redux-logger';
3 | import rootReducer from '../reducers';
4 |
5 | const store = createStore(rootReducer, applyMiddleware(logger));
6 |
7 | export default store;
--------------------------------------------------------------------------------
/server/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "@babel/preset-env"
4 | ]
5 | }
--------------------------------------------------------------------------------
/server/graphql/resolvers/handlerGenerators/auth.js:
--------------------------------------------------------------------------------
1 | import User from '../../../models/user';
2 | import bcrypt from 'bcryptjs';
3 | import jwt from 'jsonwebtoken';
4 |
5 | export async function createUser(args) {
6 | try {
7 | const {
8 | email,
9 | password,
10 | confirm
11 | } = args.userInput; //retrieve values from arguments
12 |
13 | const existingUser = await User.findOne({ email });
14 |
15 | if (existingUser) {
16 | throw new Error('User already exists!');
17 | }
18 |
19 | if (password !== confirm) {
20 | throw new Error('Passwords are inconsistent!');
21 | }
22 |
23 | const hashedPassword = await bcrypt.hash(password, 10);
24 | const user = new User({
25 | email,
26 | password: hashedPassword
27 | }, (err) => { if (err) throw err });
28 |
29 | user.save();
30 |
31 | // if user is registered without errors
32 | // create a token
33 | const token = jwt.sign({ id: user._id }, "mysecret");
34 |
35 | return { token, password: null, ...user._doc }
36 | }
37 | catch (err) {
38 | throw err;
39 | }
40 | }
41 |
42 | export async function login(args) {
43 | try {
44 | const user = await User.findOne({ email: args.email });
45 | if (!user) throw new Error('Email does not exist');
46 |
47 | const passwordIsValid = await bcrypt.compareSync(args.password, user.password);
48 | if (!passwordIsValid) throw new Error('Password incorrect');
49 |
50 | const token = jwt.sign({ id: user._id }, "mysecret");
51 |
52 | return { token, password: null, ...user._doc }
53 | }
54 | catch (err) {
55 | throw err;
56 | }
57 | }
58 |
59 | export async function verifyToken(args) {
60 | try {
61 | const decoded = jwt.verify(args.token, "mysecret");
62 | const user = await User.findOne({ _id: decoded.id })
63 | return { ...user._doc, password: null };
64 | }
65 | catch (err) {
66 | throw err;
67 | }
68 | }
--------------------------------------------------------------------------------
/server/graphql/resolvers/index.js:
--------------------------------------------------------------------------------
1 | import * as authHandlers from './handlerGenerators/auth';
2 |
3 | export default {
4 | ...authHandlers
5 | }
--------------------------------------------------------------------------------
/server/graphql/schema/index.js:
--------------------------------------------------------------------------------
1 | import { buildSchema } from 'graphql';
2 |
3 | export default buildSchema(`
4 | type User {
5 | _id: ID!
6 | email: String!
7 | token: String!
8 | }
9 | input UserInput {
10 | email: String!
11 | password: String!
12 | confirm: String!
13 | }
14 | type RootQuery {
15 | login(email: String!, password: String!): User
16 | verifyToken(token: String!): User
17 | }
18 | type RootMutation {
19 | createUser(userInput: UserInput): User
20 | }
21 | schema {
22 | query: RootQuery
23 | mutation: RootMutation
24 | }
25 | `)
--------------------------------------------------------------------------------
/server/index.js:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import bodyParser from 'body-parser';
3 | import expressGraphQL from "express-graphql";
4 | import cors from "cors";
5 | import mongoose from 'mongoose';
6 | import graphQLSchema from './graphql/schema';
7 | import graphQLResolvers from './graphql/resolvers';
8 | require('dotenv').config();
9 |
10 | const app = express();
11 |
12 | app.use(
13 | cors(),
14 | bodyParser.json()
15 | )
16 |
17 | app.use(
18 | "/graphql",
19 | expressGraphQL({
20 | schema: graphQLSchema,
21 | rootValue: graphQLResolvers,
22 | graphiql: true
23 | })
24 | );
25 |
26 | function main() {
27 | const port = process.env.PORT || 5000;
28 | const URI = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@ds135852.mlab.com:35852/mern-graphql-jwt`;
29 | mongoose.connect(URI, { useNewUrlParser: true })
30 | .then(() => {
31 | app.listen(port, () => console.log(`Server is listening on port: ${port}`));
32 | })
33 | .catch(err => {
34 | console.log(err);
35 | })
36 | }
37 |
38 | main();
--------------------------------------------------------------------------------
/server/models/user.js:
--------------------------------------------------------------------------------
1 | import mongoose, { Schema } from 'mongoose';
2 |
3 | const userSchema = new Schema({
4 | email: {
5 | type: String,
6 | required: true
7 | },
8 | password: {
9 | type: String,
10 | required: true,
11 | min: 8,
12 | max: 32
13 | }
14 | })
15 |
16 | export default mongoose.model('User', userSchema);
--------------------------------------------------------------------------------
/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "server": "nodemon --exec babel-node index.js"
8 | },
9 | "dependencies": {
10 | "bcryptjs": "^2.4.3",
11 | "body-parser": "^1.18.3",
12 | "cors": "^2.8.5",
13 | "dotenv": "^6.2.0",
14 | "express": "^4.16.4",
15 | "express-graphql": "^0.7.1",
16 | "graphql": "^14.1.1",
17 | "jsonwebtoken": "^8.4.0",
18 | "mongoose": "^5.4.12"
19 | },
20 | "devDependencies": {
21 | "@babel/cli": "^7.2.3",
22 | "@babel/core": "^7.2.2",
23 | "@babel/node": "^7.2.2",
24 | "@babel/preset-env": "^7.3.1",
25 | "concurrently": "^4.1.0",
26 | "nodemon": "^1.18.10"
27 | }
28 | }
--------------------------------------------------------------------------------