├── .gitattributes
├── .gitignore
├── README.md
├── client
├── .gitignore
├── package-lock.json
├── package.json
├── public
│ ├── android-chrome-192x192.png
│ ├── android-chrome-512x512.png
│ ├── apple-touch-icon.png
│ ├── favicon-16x16.png
│ ├── favicon-32x32.png
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
│ ├── App.js
│ ├── api
│ └── index.js
│ ├── components
│ ├── AuthPage
│ │ ├── AuthPage.js
│ │ ├── Form
│ │ │ ├── FormLogin.js
│ │ │ ├── FormRegister.js
│ │ │ └── styles
│ │ │ │ └── Form.module.css
│ │ ├── images
│ │ │ └── gmail.svg
│ │ └── styles
│ │ │ └── AuthPage.module.css
│ └── EmailPage
│ │ ├── ComposeMail
│ │ ├── ComposeMail.js
│ │ └── styles
│ │ │ └── ComposeMail.module.css
│ │ ├── EmailCategory
│ │ ├── EmailCategory.js
│ │ ├── EmailListItem
│ │ │ ├── EmailListItem.js
│ │ │ └── styles
│ │ │ │ └── EmailListItem.module.css
│ │ └── styles
│ │ │ └── EmailCategory.module.css
│ │ ├── EmailOptions
│ │ ├── EmailOptions.js
│ │ └── styles
│ │ │ └── EmailOptions.module.css
│ │ ├── EmailPage.js
│ │ ├── EmailView
│ │ ├── EmailView.js
│ │ └── styles
│ │ │ └── EmailView.module.css
│ │ ├── Header
│ │ ├── AccountControls
│ │ │ ├── AccountControls.js
│ │ │ └── styles
│ │ │ │ └── AccountControls.module.css
│ │ ├── EditImageModal
│ │ │ ├── EditImageModal.js
│ │ │ └── styles
│ │ │ │ └── EditImageModal.module.css
│ │ ├── Header.js
│ │ ├── images
│ │ │ └── gmail-logo.png
│ │ └── styles
│ │ │ └── Header.module.css
│ │ ├── Sidebar
│ │ ├── Sidebar.js
│ │ ├── SidebarOption
│ │ │ ├── SidebarOption.js
│ │ │ └── styles
│ │ │ │ └── SidebarOption.module.css
│ │ └── styles
│ │ │ └── Sidebar.module.css
│ │ └── styles
│ │ └── EmailPage.module.css
│ ├── index.js
│ ├── redux
│ ├── actions
│ │ ├── accountActions.js
│ │ ├── clearErrors.js
│ │ └── emailActions.js
│ ├── constants
│ │ └── index.js
│ ├── reducers
│ │ ├── emailReducer.js
│ │ └── userReducer.js
│ └── store.js
│ └── styles
│ ├── App.css
│ └── reset.css
├── preview_login.png
├── preview_mailbox.png
└── server
├── .env.example
├── .gitignore
├── api
├── controllers
│ ├── account.js
│ └── email.js
├── middleware
│ ├── authToken.js
│ └── validations.js
├── models
│ ├── Account.js
│ └── Email.js
└── routes
│ ├── account.js
│ └── email.js
├── index.js
├── package-lock.json
└── package.json
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | .DS_Store
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MERN Gmail clone
2 |
3 | - **M** = [MongoDB](https://www.mongodb.com)
4 | - **E** = [Express.js](https://expressjs.com)
5 | - **R** = [React.js](https://reactjs.org)
6 | - **N** = [Node.js](https://nodejs.org)
7 |
8 |
9 |
10 | ## Preview of the UI
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/client/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | .DS_Store
3 | .eslintcache
--------------------------------------------------------------------------------
/client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "homepage": "https://gmail-clone-frontend.herokuapp.com",
3 | "name": "client",
4 | "version": "1.0.0",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "react-scripts start"
8 | },
9 | "author": "Ben Elferink",
10 | "license": "ISC",
11 | "dependencies": {
12 | "@material-ui/core": "^4.11.3",
13 | "@material-ui/icons": "^4.11.2",
14 | "axios": "^0.21.0",
15 | "react": "^17.0.1",
16 | "react-dom": "^17.0.1",
17 | "react-file-base64": "^1.0.3",
18 | "react-hook-form": "^6.15.1",
19 | "react-redux": "^7.2.2",
20 | "react-router-dom": "^5.2.0",
21 | "react-scripts": "^4.0.2",
22 | "redux": "^4.0.5",
23 | "redux-devtools-extension": "^2.13.8",
24 | "redux-logger": "^3.0.6",
25 | "redux-thunk": "^2.3.0"
26 | },
27 | "eslintConfig": {
28 | "extends": [
29 | "react-app",
30 | "react-app/jest"
31 | ]
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/client/public/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/android-chrome-192x192.png
--------------------------------------------------------------------------------
/client/public/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/android-chrome-512x512.png
--------------------------------------------------------------------------------
/client/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/client/public/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/favicon-16x16.png
--------------------------------------------------------------------------------
/client/public/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/favicon-32x32.png
--------------------------------------------------------------------------------
/client/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/public/favicon.ico
--------------------------------------------------------------------------------
/client/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
15 |
16 | Gmail
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/client/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "Gmail",
3 | "name": "MERN-stack Gmail clone",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src":"android-chrome-192x192.png",
12 | "sizes":"192x192",
13 | "type":"image/png"
14 | },
15 | {
16 | "src":"android-chrome-512x512.png",
17 | "sizes":"512x512",
18 | "type":"image/png"
19 | }]
20 | }
--------------------------------------------------------------------------------
/client/src/App.js:
--------------------------------------------------------------------------------
1 | import { useEffect } from 'react';
2 | import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
3 | import { useDispatch, useSelector } from 'react-redux';
4 | import { getUserAction } from './redux/actions/accountActions';
5 | import './styles/App.css';
6 | import AuthPage from './components/AuthPage/AuthPage';
7 | import EmailPage from './components/EmailPage/EmailPage';
8 |
9 | function App() {
10 | const dispatch = useDispatch();
11 | const { isLoggedIn, token } = useSelector((state) => state.userReducer);
12 |
13 | // if a token exists, try to get the user data from the server,
14 | // if this fetch has succeeded, App will redirect us to the emails page
15 | // if this fetch failed, that means the token has expired and the user needs to login
16 | useEffect(() => {
17 | if (token) {
18 | dispatch(getUserAction());
19 | }
20 | }, [token, dispatch]);
21 |
22 | return (
23 |
24 |
25 |
26 |
27 | {!isLoggedIn ? : }
28 |
29 |
30 |
31 | {!isLoggedIn ? : }
32 |
33 |
34 |
35 | {/* This route has multiple sub-routes */}
36 | {isLoggedIn ? : }
37 |
38 |
39 | (window.location.href = 'https://github.com/belferink1996')}
43 | />
44 |
45 |
46 |
47 | );
48 | }
49 |
50 | export default App;
51 |
--------------------------------------------------------------------------------
/client/src/api/index.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 |
3 | const url = 'https://gmail-clone-backend.herokuapp.com/api/v1';
4 | const headers = (token) => ({
5 | headers: {
6 | 'Content-Type': 'application/json',
7 | Authorization: 'Bearer ' + token,
8 | },
9 | });
10 |
11 | // account routes
12 | export const register = (form) => axios.post(`${url}/account/register`, form);
13 | export const login = (form) => axios.post(`${url}/account/login`, form);
14 | export const getUser = (token) => axios.get(`${url}/account`, headers(token));
15 | export const uploadImage = (token, image) =>
16 | axios.put(`${url}/account/image`, image, headers(token));
17 |
18 | // email routes
19 | export const getAllEmails = (token) => axios.get(`${url}/email`, headers(token));
20 | export const sendEmail = (token, form) => axios.post(`${url}/email/send`, form, headers(token));
21 | export const saveDraft = (token, form) => axios.post(`${url}/email/draft`, form, headers(token));
22 | export const updateDraft = (token, id, form) =>
23 | axios.put(`${url}/email/draft/${id}`, form, headers(token));
24 | export const moveToTrash = (token, id) =>
25 | axios.put(`${url}/email/${id}/trash`, null, headers(token));
26 | export const removeFromTrash = (token, id) =>
27 | axios.put(`${url}/email/${id}/untrash`, null, headers(token));
28 | export const markAsRead = (token, id) => axios.put(`${url}/email/${id}/read`, null, headers(token));
29 | export const markAsUnread = (token, id) =>
30 | axios.put(`${url}/email/${id}/unread`, null, headers(token));
31 | export const setFavorite = (token, id) =>
32 | axios.put(`${url}/email/${id}/favorite`, null, headers(token));
33 | export const unsetFavorite = (token, id) =>
34 | axios.put(`${url}/email/${id}/unfavorite`, null, headers(token));
35 | export const deleteEmail = (token, id) => axios.delete(`${url}/email/${id}`, headers(token));
36 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/AuthPage.js:
--------------------------------------------------------------------------------
1 | import { useState, useEffect, Fragment } from 'react';
2 | import { useSelector } from 'react-redux';
3 | import styles from './styles/AuthPage.module.css';
4 | import FormLogin from './Form/FormLogin';
5 | import FormRegister from './Form/FormRegister';
6 | import GmailIcon from './images/gmail.svg';
7 |
8 | export default function AuthPage() {
9 | const { user, isLoading, error } = useSelector((state) => state.userReducer);
10 |
11 | // defines if the register or login form is displayed
12 | const [isCreateNew, setIsCreateNew] = useState(false);
13 | const toggleIsCreateNew = () => setIsCreateNew(!isCreateNew);
14 |
15 | // if the user has registered, and the email used has been applied,
16 | // then toggle state to show 'login' component with the registered email.
17 | useEffect(() => {
18 | if (user.email) {
19 | toggleIsCreateNew();
20 | alert('Account successfully created!');
21 | }
22 | // eslint-disable-next-line
23 | }, [user.email]);
24 |
25 | return (
26 |
27 |

28 |
29 | {isCreateNew ? (
30 |
31 |
32 |
35 |
36 | ) : (
37 |
38 |
39 |
42 |
43 | )}
44 |
45 |
46 | Disclaimer: this clone is not associated with Google! All accounts & emails are fictive, but
47 | remain in a database.
48 |
49 |
50 | );
51 | }
52 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/Form/FormLogin.js:
--------------------------------------------------------------------------------
1 | import { useDispatch } from 'react-redux';
2 | import { loginAction } from '../../../redux/actions/accountActions';
3 | import { clearErrors } from '../../../redux/actions/clearErrors';
4 | import { useForm } from 'react-hook-form';
5 | import styles from './styles/Form.module.css';
6 | import { Button, CircularProgress } from '@material-ui/core';
7 |
8 | export default function FormLogin({ isLoading, error, user }) {
9 | const dispatch = useDispatch();
10 | const { register, handleSubmit, errors, formState } = useForm({
11 | defaultValues: {
12 | email: user.email, // this is given by Redux state (if the user has successfully registered)
13 | },
14 | });
15 |
16 | if (error) {
17 | alert(error);
18 | setTimeout(() => {
19 | dispatch(clearErrors());
20 | }, 0);
21 | }
22 |
23 | const onSubmit = (values) => {
24 | dispatch(loginAction(values));
25 | };
26 |
27 | if (isLoading) {
28 | return (
29 |
30 |
31 |
32 | );
33 | } else {
34 | return (
35 |
65 | );
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/Form/FormRegister.js:
--------------------------------------------------------------------------------
1 | import { useRef } from 'react';
2 | import { useDispatch } from 'react-redux';
3 | import { registerAction } from '../../../redux/actions/accountActions';
4 | import { clearErrors } from '../../../redux/actions/clearErrors';
5 | import { useForm } from 'react-hook-form';
6 | import styles from './styles/Form.module.css';
7 | import { Button, CircularProgress } from '@material-ui/core';
8 |
9 | export default function FormRegister({ isLoading, error }) {
10 | const dispatch = useDispatch();
11 | const { register, handleSubmit, errors, watch, formState } = useForm();
12 | const password = useRef({}); // used so I can compare the password and confirmed password
13 | password.current = watch('password', '');
14 |
15 | if (error) {
16 | alert(error);
17 | setTimeout(() => {
18 | dispatch(clearErrors());
19 | }, 0);
20 | }
21 |
22 | const onSubmit = (values) => {
23 | dispatch(registerAction(values));
24 | };
25 |
26 | if (isLoading) {
27 | return (
28 |
29 |
30 |
31 | );
32 | } else {
33 | return (
34 |
110 | );
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/Form/styles/Form.module.css:
--------------------------------------------------------------------------------
1 | .form {
2 | width: 320px;
3 | display: flex;
4 | flex-direction: column;
5 | align-items: center;
6 | }
7 |
8 | .form > input {
9 | width: 92%;
10 | padding: 7px 3px;
11 | border: none;
12 | border-bottom: 1px solid #f5f5f5;
13 | outline: none;
14 | }
15 |
16 | .form > button {
17 | width: 100% !important;
18 | margin: 7px 0 !important;
19 | padding: 10px 0 !important;
20 | background-color: #1e6df6 !important;
21 | border: none !important;
22 | border-radius: 20px !important;
23 | color: #fff !important;
24 | font-size: 16px !important;
25 | cursor: pointer !important;
26 | }
27 |
28 | .form > button:hover {
29 | background-color: #4b8ef9 !important;
30 | }
31 |
32 | .form > p {
33 | width: 100%;
34 | padding-left: 15px;
35 | font-size: 14px;
36 | color: #ff0000;
37 | text-align: left;
38 | }
39 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/images/gmail.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/client/src/components/AuthPage/styles/AuthPage.module.css:
--------------------------------------------------------------------------------
1 | .page {
2 | width: 100%;
3 | min-height: 100vh;
4 | display: flex;
5 | flex-direction: column;
6 | align-items: center;
7 | /* justify-content: center; */
8 | }
9 |
10 | .page > img {
11 | width: 350px;
12 | margin-top: 69px;
13 | margin-bottom: 42px;
14 | }
15 |
16 | .link {
17 | margin-bottom: 20px;
18 | background-color: transparent;
19 | border: none;
20 | color: #1e6df6;
21 | font-size: 12px;
22 | text-decoration: underline;
23 | cursor: pointer;
24 | }
25 |
26 | .link:hover {
27 | font-weight: 500;
28 | }
29 |
30 | .page > p {
31 | margin: auto 0 7px auto;
32 | color: #808080;
33 | text-align: center;
34 | font-size: 12px;
35 | }
36 |
37 | @media (max-width: 768px) {
38 | .page > img {
39 | width: 290px;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/ComposeMail/ComposeMail.js:
--------------------------------------------------------------------------------
1 | import { useRef } from 'react';
2 | import { useDispatch, useSelector } from 'react-redux';
3 | import {
4 | sendEmailAction,
5 | saveDraftAction,
6 | updateDraftAction,
7 | } from '../../../redux/actions/emailActions';
8 | import { useForm } from 'react-hook-form';
9 | import { Button } from '@material-ui/core';
10 | import styles from './styles/ComposeMail.module.css';
11 |
12 | function ComposeMail({ toggleIsCompose, composeDraft }) {
13 | const dispatch = useDispatch();
14 | const registeredEmail = useSelector((state) => state.userReducer.user.email);
15 | const { register, handleSubmit, errors, watch } = useForm({
16 | defaultValues: {
17 | from: registeredEmail,
18 | to: composeDraft?.to || '',
19 | subject: composeDraft?.subject || '',
20 | message: composeDraft?.message || '',
21 | },
22 | });
23 |
24 | // The following references purposes are to "pull" the form data from the useForm hook,
25 | // and used whenever the message will be saved as a draft
26 | const from = useRef({});
27 | const to = useRef({});
28 | const subject = useRef({});
29 | const message = useRef({});
30 | from.current = watch('from', '');
31 | to.current = watch('to', '');
32 | subject.current = watch('subject', '');
33 | message.current = watch('message', '');
34 |
35 | // the following function sends the message
36 | // (the server also creates a random reply to be received by the user)
37 | const onSubmit = (values) => {
38 | if (!composeDraft) {
39 | dispatch(sendEmailAction(values));
40 | } else {
41 | // but if the component was called by clicking on a draft,
42 | // then the email is sent, and the draft is updated too!
43 | dispatch(sendEmailAction(values));
44 | let form = {
45 | to: to.current,
46 | subject: subject.current,
47 | message: message.current,
48 | };
49 | dispatch(updateDraftAction(composeDraft._id, form));
50 | }
51 | toggleIsCompose();
52 | };
53 |
54 | const onClose = () => {
55 | if (!composeDraft) {
56 | // the following is used to save a message as draft
57 | // (only if one of the fields are not empty)
58 | if (to.current !== '' || subject.current !== '' || message.current !== '') {
59 | let form = {
60 | from: from.current,
61 | to: to.current,
62 | subject: subject.current,
63 | message: message.current,
64 | };
65 | dispatch(saveDraftAction(form));
66 | }
67 | } else {
68 | // the following is used to update the existing draft
69 | let form = {
70 | to: to.current,
71 | subject: subject.current,
72 | message: message.current,
73 | };
74 | dispatch(updateDraftAction(composeDraft._id, form));
75 | }
76 | toggleIsCompose();
77 | };
78 |
79 | return (
80 |
145 | );
146 | }
147 |
148 | export default ComposeMail;
149 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/ComposeMail/styles/ComposeMail.module.css:
--------------------------------------------------------------------------------
1 | .compose {
2 | width: 350px;
3 | height: 420px;
4 | position: fixed;
5 | bottom: 0;
6 | right: 11%;
7 | background-color: #fff;
8 | border: none;
9 | border-radius: 10px 10px 0 0;
10 | font-size: 15px;
11 | box-shadow: 0px 2px 10px -2px rgba(0, 0, 0, 0.75);
12 | z-index: 8;
13 | }
14 |
15 | .header {
16 | padding: 10px 15px;
17 | display: flex;
18 | align-items: center;
19 | justify-content: space-between;
20 | background-color: #505050;
21 | border-radius: 10px 10px 0 0;
22 | color: #fff;
23 | }
24 |
25 | .header > span {
26 | cursor: pointer;
27 | }
28 |
29 | .inpGroup {
30 | padding: 7px 15px;
31 | display: flex;
32 | align-items: center;
33 | border: none;
34 | border-bottom: 1px solid #f5f5f5;
35 | }
36 |
37 | .inpGroup > label {
38 | margin-right: 7px;
39 | cursor: text;
40 | }
41 |
42 | .inpGroup > input {
43 | width: 100%;
44 | border: none;
45 | outline: none;
46 | }
47 |
48 | .compose > textarea {
49 | width: 350px;
50 | height: 230px;
51 | padding: 7px 15px;
52 | border: none;
53 | resize: none;
54 | outline: none;
55 | }
56 |
57 | .send {
58 | height: 42px;
59 | display: flex;
60 | align-items: center;
61 | }
62 |
63 | .send > button {
64 | margin: 0 10px !important;
65 | background-color: #1e6df6 !important;
66 | border-radius: 10px !important;
67 | color: #fff !important;
68 | text-transform: Capitalize !important;
69 | }
70 |
71 | .send > button:hover {
72 | background-color: #4b8ef9 !important;
73 | }
74 |
75 | .send > span {
76 | color: #ff0000;
77 | font-size: 13px;
78 | }
79 |
80 | @media (max-width: 768px) {
81 | .compose {
82 | width: 90vw;
83 | right: 5%;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailCategory/EmailCategory.js:
--------------------------------------------------------------------------------
1 | import { Fragment } from 'react';
2 | import { useParams } from 'react-router-dom';
3 | import { useSelector } from 'react-redux';
4 | import styles from './styles/EmailCategory.module.css';
5 | import EmailOptions, { More, Refetch, SelectAll } from '../EmailOptions/EmailOptions';
6 | import EmailListItem from './EmailListItem/EmailListItem';
7 | import { CircularProgress } from '@material-ui/core';
8 |
9 | export default function EmailCategory({ inbox, sent, drafts, starred, trash, toggleIsCompose }) {
10 | const { category } = useParams();
11 | const { isLoading } = useSelector((state) => state.emailReducer);
12 | const userEmail = useSelector((state) => state.userReducer.user.email);
13 |
14 | if (isLoading) {
15 | return (
16 |
17 |
18 |
19 | );
20 | } else {
21 | switch (category) {
22 | case 'inbox':
23 | return inbox.length ? (
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | {inbox.map((item) => (
32 |
42 | ))}
43 |
44 | ) : (
45 | Inbox is empty...
46 | );
47 |
48 | case 'sent':
49 | return sent.length ? (
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | {sent.map((item) => (
58 |
68 | ))}
69 |
70 | ) : (
71 | Outbox is empty...
72 | );
73 |
74 | case 'starred':
75 | return starred.length ? (
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | {starred.map((item) => (
84 |
94 | ))}
95 |
96 | ) : (
97 | Favorites is empty...
98 | );
99 |
100 | case 'drafts':
101 | return drafts.length ? (
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | {drafts.map((item) => (
110 |
120 | ))}
121 |
122 | ) : (
123 | Drafts is empty...
124 | );
125 |
126 | case 'trash':
127 | return trash.length ? (
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 | {trash.map((item) => (
136 |
145 | ))}
146 |
147 | ) : (
148 | Trash is empty...
149 | );
150 |
151 | default:
152 | break;
153 | }
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailCategory/EmailListItem/EmailListItem.js:
--------------------------------------------------------------------------------
1 | import { useHistory, useParams } from 'react-router-dom';
2 | import styles from './styles/EmailListItem.module.css';
3 | import { Delete, MarkStar, SelectOne } from '../../EmailOptions/EmailOptions';
4 |
5 | export default function EmailCategoryItem({
6 | id,
7 | title,
8 | subject,
9 | message,
10 | date,
11 | isRead,
12 | isStarred,
13 | isTrash,
14 | isDraft,
15 | toggleIsCompose,
16 | }) {
17 | const history = useHistory();
18 | const { category } = useParams();
19 |
20 | // this function converts the date object to a sweet UI date string
21 | const dateToString = (dateObj) => {
22 | let day = new Date(dateObj).getDate();
23 | let month = new Date(dateObj).getMonth();
24 | switch (month) {
25 | case 0:
26 | return `Jan ${day}`;
27 | case 1:
28 | return `Feb ${day}`;
29 | case 2:
30 | return `Mar ${day}`;
31 | case 3:
32 | return `Apr ${day}`;
33 | case 4:
34 | return `May ${day}`;
35 | case 5:
36 | return `Jun ${day}`;
37 | case 6:
38 | return `Jul ${day}`;
39 | case 7:
40 | return `Aug ${day}`;
41 | case 8:
42 | return `Sep ${day}`;
43 | case 9:
44 | return `Oct ${day}`;
45 | case 10:
46 | return `Nov ${day}`;
47 | case 11:
48 | return `Dec ${day}`;
49 | default:
50 | return 'Loading...';
51 | }
52 | };
53 |
54 | return (
55 |
56 |
57 | {isStarred !== undefined &&
}
58 | {isTrash || isDraft ?
: ''}
59 |
60 |
63 | isDraft ? toggleIsCompose(id) : history.push(`/email/${category}/view/${id}`)
64 | }>
65 |
{title}
66 |
67 |
68 | {subject}
69 |
70 | {message}
71 |
72 |
73 |
{dateToString(date)}
74 |
75 |
76 | );
77 | }
78 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailCategory/EmailListItem/styles/EmailListItem.module.css:
--------------------------------------------------------------------------------
1 | .item {
2 | padding: 7px 5px;
3 | display: flex;
4 | align-items: center;
5 | border-bottom: 1px solid #f5f5f5;
6 | }
7 |
8 | .item:hover {
9 | border-top: 1px solid #f5f5f5;
10 | box-shadow: 0px 4px 4px -2px rgba(0, 0, 0, 0.25);
11 | position: relative;
12 | z-index: 7;
13 | }
14 |
15 | .message {
16 | display: flex;
17 | align-items: center;
18 | width: 100%;
19 | font-size: 14px;
20 | cursor: pointer;
21 | }
22 |
23 | .message > h4 {
24 | width: 200px;
25 | margin-left: 5px;
26 | overflow: hidden;
27 | text-overflow: ellipsis;
28 | }
29 |
30 | .message > p {
31 | flex: 1;
32 | }
33 |
34 | .message,
35 | .message > p {
36 | white-space: nowrap;
37 | overflow: hidden;
38 | text-overflow: ellipsis;
39 | }
40 |
41 | .message > span {
42 | width: 80px;
43 | font-size: 12px;
44 | text-align: center;
45 | white-space: nowrap;
46 | }
47 |
48 | .unread > .message > h4,
49 | .unread > .message > p > span,
50 | .unread > .message > span {
51 | font-weight: bold;
52 | }
53 |
54 | .read {
55 | background-color: #f5f5f5;
56 | }
57 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailCategory/styles/EmailCategory.module.css:
--------------------------------------------------------------------------------
1 | .center {
2 | height: 100px;
3 | padding: auto;
4 | display: grid;
5 | place-items: center;
6 | }
7 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailOptions/EmailOptions.js:
--------------------------------------------------------------------------------
1 | import { useHistory } from 'react-router-dom';
2 | import { useDispatch } from 'react-redux';
3 | import {
4 | getEmailsAction,
5 | moveToTrashAction,
6 | removeFromTrashAction,
7 | markAsUnreadAction,
8 | setFavoriteAction,
9 | unsetFavoriteAction,
10 | deleteEmailAction,
11 | } from '../../../redux/actions/emailActions';
12 | import styles from './styles/EmailOptions.module.css';
13 | import { Checkbox, IconButton, Tooltip } from '@material-ui/core';
14 | // import ChevronLeftRoundedIcon from '@material-ui/icons/ChevronLeftRounded';
15 | // import ChevronRightRoundedIcon from '@material-ui/icons/ChevronRightRounded';
16 | import KeyboardRoundedIcon from '@material-ui/icons/KeyboardRounded';
17 | import ArrowBackRoundedIcon from '@material-ui/icons/ArrowBackRounded';
18 | import RefreshRoundedIcon from '@material-ui/icons/RefreshRounded';
19 | import DraftsRoundedIcon from '@material-ui/icons/DraftsRounded';
20 | import StarRoundedIcon from '@material-ui/icons/StarRounded';
21 | import StarOutlineRoundedIcon from '@material-ui/icons/StarOutlineRounded';
22 | import DeleteRoundedIcon from '@material-ui/icons/DeleteRounded';
23 | import RestoreFromTrashRoundedIcon from '@material-ui/icons/RestoreFromTrashRounded';
24 | import DeleteForeverRoundedIcon from '@material-ui/icons/DeleteForeverRounded';
25 | import MoreVertRoundedIcon from '@material-ui/icons/MoreVertRounded';
26 |
27 | export default function EmailOptions(props) {
28 | return (
29 |
30 |
31 | {/* This is where the developer needs to insert the export functions below */}
32 | {props.children}
33 |
34 |
35 |
36 | {/*
37 |
38 |
39 |
40 |
41 |
42 |
43 | */}
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | );
52 | }
53 |
54 | export function SelectOne() {
55 | // TODO
56 | return (
57 |
60 |
61 |
62 | );
63 | }
64 |
65 | export function SelectAll() {
66 | // TODO
67 | return (
68 |
71 |
72 |
73 | );
74 | }
75 |
76 | export function GoBack() {
77 | const history = useHistory();
78 | return (
79 |
80 | history.goBack()}>
81 |
82 |
83 |
84 | );
85 | }
86 |
87 | export function Refetch() {
88 | const dispatch = useDispatch();
89 | return (
90 |
91 | dispatch(getEmailsAction())}>
92 |
93 |
94 |
95 | );
96 | }
97 |
98 | export function MarkUnread({ id }) {
99 | const dispatch = useDispatch();
100 | const history = useHistory();
101 | return (
102 |
103 | {
105 | dispatch(markAsUnreadAction(id));
106 | history.goBack();
107 | }}>
108 |
109 |
110 |
111 | );
112 | }
113 |
114 | export function MarkStar({ id, isStarred }) {
115 | const dispatch = useDispatch();
116 | if (isStarred) {
117 | return (
118 |
119 | dispatch(unsetFavoriteAction(id))}>
120 |
121 |
122 |
123 | );
124 | } else {
125 | return (
126 |
127 | dispatch(setFavoriteAction(id))}>
128 |
129 |
130 |
131 | );
132 | }
133 | }
134 |
135 | export function PlaceTrash({ id, isInTrash }) {
136 | const dispatch = useDispatch();
137 | const history = useHistory();
138 | if (isInTrash) {
139 | return (
140 |
141 | {
143 | dispatch(removeFromTrashAction(id));
144 | history.goBack();
145 | }}>
146 |
147 |
148 |
149 | );
150 | } else {
151 | return (
152 |
153 | {
155 | dispatch(moveToTrashAction(id));
156 | history.goBack();
157 | }}>
158 |
159 |
160 |
161 | );
162 | }
163 | }
164 |
165 | export function Delete({ id }) {
166 | const dispatch = useDispatch();
167 | return (
168 |
169 | dispatch(deleteEmailAction(id))}>
170 |
171 |
172 |
173 | );
174 | }
175 |
176 | export function More() {
177 | // TODO
178 | return (
179 |
182 |
183 |
184 |
185 |
186 | );
187 | }
188 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailOptions/styles/EmailOptions.module.css:
--------------------------------------------------------------------------------
1 | .component {
2 | padding: 5px;
3 | position: -webkit-sticky;
4 | position: sticky;
5 | top: 0;
6 | display: flex;
7 | align-items: center;
8 | justify-content: space-between;
9 | background-color: #fff;
10 | border-bottom: 1px solid #f5f5f5;
11 | }
12 |
13 | .wrapper {
14 | white-space: nowrap;
15 | overflow: hidden;
16 | }
17 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailPage.js:
--------------------------------------------------------------------------------
1 | import { Fragment, useState, useEffect } from 'react';
2 | import { Route } from 'react-router-dom';
3 | import { useDispatch, useSelector } from 'react-redux';
4 | import { getEmailsAction } from '../../redux/actions/emailActions';
5 | import styles from './styles/EmailPage.module.css';
6 | import Header from './Header/Header';
7 | import Sidebar from './Sidebar/Sidebar';
8 | import EmailCategory from './EmailCategory/EmailCategory';
9 | import EmailView from './EmailView/EmailView';
10 | import ComposeMail from './ComposeMail/ComposeMail';
11 |
12 | export default function EmailPage() {
13 | const dispatch = useDispatch();
14 | const mailbox = useSelector((state) => state.emailReducer.mailbox);
15 | const [inbox, setInbox] = useState([]);
16 | const [sent, setSent] = useState([]);
17 | const [starred, setStarred] = useState([]);
18 | const [drafts, setDrafts] = useState([]);
19 | const [trash, setTrash] = useState([]);
20 |
21 | // this gets all emails linked to the user, upon mount
22 | useEffect(() => {
23 | dispatch(getEmailsAction());
24 | }, [dispatch]);
25 |
26 | // this sorts all the emails by categories and time,
27 | // and sets all states accordingly.
28 | // this runs each time the mailbox (redux) was updated
29 | useEffect(() => {
30 | // filter mailbox to UI categories
31 | let inboxArr = [...mailbox.inbox],
32 | sentArr = [...mailbox.outbox],
33 | draftsArr = [...mailbox.drafts],
34 | trashArr = [...mailbox.trash],
35 | starredArr = mailbox.inbox
36 | .filter((email) => email.favorite)
37 | .concat(mailbox.outbox.filter((email) => email.favorite));
38 |
39 | // sort all categories by date
40 | inboxArr.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
41 | sentArr.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
42 | draftsArr.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
43 | trashArr.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
44 | starredArr.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
45 |
46 | // update states with changes
47 | setInbox(inboxArr);
48 | setSent(sentArr);
49 | setDrafts(draftsArr);
50 | setTrash(trashArr);
51 | setStarred(starredArr);
52 | }, [mailbox]);
53 |
54 | // these states mount/unmount certain components
55 | const [showSidebar, setShowSidebar] = useState(true);
56 | const [isCompose, setIsCompose] = useState(false);
57 | // this state holds the draft email information (if a draft was clicked for editing)
58 | const [composeDraft, setComposeDraft] = useState(undefined);
59 |
60 | const toggleShowSidebar = () => setShowSidebar(!showSidebar);
61 | const toggleIsCompose = (id) => {
62 | setIsCompose(!isCompose);
63 |
64 | // if activated by clicking a draft, set draft details in state
65 | if (id) {
66 | drafts.forEach((draft) => draft._id === id && setComposeDraft(draft));
67 | } else {
68 | setComposeDraft(undefined);
69 | }
70 | };
71 |
72 | return (
73 |
74 |
75 |
76 |
77 | {showSidebar && (
78 |
86 | )}
87 |
88 |
89 |
90 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | {isCompose && }
106 |
107 |
108 | );
109 | }
110 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailView/EmailView.js:
--------------------------------------------------------------------------------
1 | import { useState, useEffect, Fragment } from 'react';
2 | import { useParams } from 'react-router-dom';
3 | import { useDispatch } from 'react-redux';
4 | import { markAsReadAction } from '../../../redux/actions/emailActions';
5 | import styles from './styles/EmailView.module.css';
6 | import EmailOptions, { Delete, GoBack, MarkUnread, PlaceTrash } from '../EmailOptions/EmailOptions';
7 | import { Avatar } from '@material-ui/core';
8 |
9 | export default function EmailView({ inbox, sent, drafts, starred, trash }) {
10 | const dispatch = useDispatch();
11 | const { category, id } = useParams();
12 |
13 | const [emailToDisplay] = useState(() => {
14 | switch (category) {
15 | case 'inbox':
16 | return inbox.find((item) => item._id === id);
17 | case 'sent':
18 | return sent.find((item) => item._id === id);
19 | case 'drafts':
20 | return drafts.find((item) => item._id === id);
21 | case 'starred':
22 | return starred.find((item) => item._id === id);
23 | case 'trash':
24 | return trash.find((item) => item._id === id);
25 | default:
26 | break;
27 | }
28 | });
29 |
30 | // this side effect marks the email as read (if it wasn't already marked as read)
31 | useEffect(() => {
32 | if (!emailToDisplay.read) dispatch(markAsReadAction(id));
33 | }, [dispatch, emailToDisplay, id]);
34 |
35 | return (
36 |
37 |
38 |
39 |
40 | {category === 'trash' ? : }
41 |
42 |
43 |
44 |
45 |
{emailToDisplay.subject}
46 |
47 |
48 | {emailToDisplay.from}
49 |
50 | to me
51 |
52 |
{emailToDisplay.message}
53 |
54 |
55 |
56 | );
57 | }
58 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/EmailView/styles/EmailView.module.css:
--------------------------------------------------------------------------------
1 | .wrapper {
2 | width: 100%;
3 | padding: 20px 0;
4 | display: flex;
5 | justify-content: center;
6 | }
7 |
8 | .container {
9 | height: 80%;
10 | flex: 0.9;
11 | padding: 30px 15px;
12 | box-shadow: 0px 5px 15px -5px rgba(0, 0, 0, 0.75) !important;
13 | overflow: scroll;
14 | }
15 |
16 | .container > h3 {
17 | margin-left: 50px;
18 | font-size: 28px;
19 | }
20 |
21 | .container > div {
22 | margin: 15px 0;
23 | display: flex;
24 | align-items: center;
25 | }
26 |
27 | .avatar {
28 | margin-right: 10px;
29 | }
30 |
31 | .container > p {
32 | margin-left: 50px;
33 | }
34 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/AccountControls/AccountControls.js:
--------------------------------------------------------------------------------
1 | import { useHistory } from 'react-router-dom';
2 | import { useDispatch } from 'react-redux';
3 | import { logoutAction } from '../../../../redux/actions/accountActions';
4 | import styles from './styles/AccountControls.module.css';
5 | import { Avatar, Badge, Button } from '@material-ui/core';
6 |
7 | export default function AccountControls({ user, toggleShowEditImage, toggleShowProfile }) {
8 | const dispatch = useDispatch();
9 | const history = useHistory();
10 |
11 | return (
12 |
13 |
{
23 | toggleShowEditImage();
24 | toggleShowProfile();
25 | }}>
26 |
27 |
28 |
29 |
30 | {user.name.first} {user.name.last}
31 |
32 | {user.email}
33 |
34 |
35 |
36 |
37 |
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/AccountControls/styles/AccountControls.module.css:
--------------------------------------------------------------------------------
1 | .container {
2 | display: flex;
3 | flex-direction: column;
4 | align-items: center;
5 | justify-content: space-evenly;
6 |
7 | width: 400px;
8 | height: 330px;
9 | padding: 7px;
10 | background-color: #fff;
11 | border-radius: 15px;
12 | text-align: center;
13 | box-shadow: 0px 2px 10px -2px rgba(0, 0, 0, 0.75);
14 |
15 | position: absolute;
16 | bottom: -330px;
17 | right: 5px;
18 |
19 | z-index: 9;
20 | }
21 |
22 | .container > a {
23 | text-decoration: none;
24 | }
25 |
26 | .container button {
27 | padding: 7px 15px !important;
28 | background-color: #f5f5f5 !important;
29 | border: 0.5px solid #818181 !important;
30 | border-radius: 1rem !important;
31 | text-transform: none !important;
32 | }
33 |
34 | .avatar {
35 | width: 90px !important;
36 | height: 90px !important;
37 | }
38 |
39 | @media (max-width: 768px) {
40 | .container {
41 | width: 95vw;
42 | position: absolute;
43 | bottom: -330px;
44 | right: 0;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/EditImageModal/EditImageModal.js:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { useDispatch } from 'react-redux';
3 | import { uploadImageAction } from '../../../../redux/actions/accountActions';
4 | import styles from './styles/EditImageModal.module.css';
5 | import FileBase64 from 'react-file-base64';
6 | import { Avatar, Button } from '@material-ui/core';
7 |
8 | export default function EditImageModal({ toggleShowEditImage }) {
9 | const dispatch = useDispatch();
10 | const [image, setImage] = useState('');
11 |
12 | const upload = (e) => {
13 | e.preventDefault();
14 | dispatch(uploadImageAction({ image }));
15 | toggleShowEditImage();
16 | };
17 |
18 | return (
19 |
20 |
33 |
34 | );
35 | }
36 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/EditImageModal/styles/EditImageModal.module.css:
--------------------------------------------------------------------------------
1 | .modal {
2 | width: 100vw;
3 | height: 100vh;
4 |
5 | position: fixed;
6 | top: 50%;
7 | left: 50%;
8 | transform: translate(-50%, -50%);
9 | z-index: 10;
10 |
11 | display: grid;
12 | place-items: center;
13 |
14 | background-color: rgba(0, 0, 0, 0.5);
15 | }
16 |
17 | .form {
18 | width: 420px;
19 | height: 270px;
20 | padding: 0 0 20px 0;
21 | display: flex;
22 | flex-direction: column;
23 | align-items: center;
24 | justify-content: space-evenly;
25 | background-color: #fff;
26 | border-radius: 15px;
27 | }
28 |
29 | .avatar {
30 | width: 90px !important;
31 | height: 90px !important;
32 | }
33 |
34 | .form > span {
35 | margin: 0 15px 0 auto;
36 | color: tomato;
37 | font-size: 20px;
38 | cursor: pointer;
39 | }
40 |
41 | .form > label {
42 | padding: 7px 15px;
43 | background-color: #f5f5f5;
44 | border: 0.5px solid #818181;
45 | border-radius: 1rem;
46 | font-size: 14px;
47 | }
48 |
49 | .form > label > input[type='file'] {
50 | display: none;
51 | }
52 |
53 | .form > button {
54 | padding: 5px 15px !important;
55 | background-color: #f5f5f5 !important;
56 | border: 0.5px solid #818181 !important;
57 | border-radius: 1rem !important;
58 | text-transform: none !important;
59 | font-size: 14px !important;
60 | }
61 |
62 | @media (max-width: 768px) {
63 | .form {
64 | width: 95vw;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/Header.js:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { useSelector } from 'react-redux';
3 | import styles from './styles/Header.module.css';
4 | import AccountControls from './AccountControls/AccountControls';
5 | import EditImageModal from './EditImageModal/EditImageModal';
6 | import GmailLogo from './images/gmail-logo.png';
7 | import { IconButton, Avatar } from '@material-ui/core';
8 | import MenuIcon from '@material-ui/icons/Menu';
9 | import SearchIcon from '@material-ui/icons/Search';
10 | import AppsIcon from '@material-ui/icons/Apps';
11 | import NotificationsRoundedIcon from '@material-ui/icons/NotificationsRounded';
12 |
13 | export default function Header({ toggleShowSidebar }) {
14 | const { user } = useSelector((state) => state.userReducer);
15 |
16 | const [showProfile, setShowProfile] = useState(false);
17 | const [showEditImage, setShowEditImage] = useState(false);
18 |
19 | const toggleShowProfile = () => setShowProfile(!showProfile);
20 | const toggleShowEditImage = () => setShowEditImage(!showEditImage);
21 |
22 | return (
23 |
59 | );
60 | }
61 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/images/gmail-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/client/src/components/EmailPage/Header/images/gmail-logo.png
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Header/styles/Header.module.css:
--------------------------------------------------------------------------------
1 | .container {
2 | height: 90px;
3 | display: flex;
4 | align-items: center;
5 | justify-content: space-between;
6 | border-bottom: 1px solid #f5f5f5;
7 | }
8 |
9 | .side {
10 | margin: 0 10px;
11 | display: flex;
12 | align-items: center;
13 | }
14 |
15 | .side > img {
16 | height: 90px;
17 | -o-object-fit: contain;
18 | object-fit: contain;
19 | }
20 |
21 | .middle {
22 | height: 55px;
23 | padding: 10px;
24 | display: flex;
25 | flex: 0.7;
26 | align-items: center;
27 | background-color: #f5f5f5;
28 | border-radius: 5px;
29 | overflow: hidden;
30 | }
31 |
32 | .middle > input {
33 | width: 100%;
34 | padding: 10px;
35 | background-color: transparent;
36 | border: none;
37 | outline: none;
38 | font-size: medium;
39 | }
40 |
41 | .relative {
42 | position: relative;
43 | }
44 |
45 | @media (max-width: 768px) {
46 | .middle {
47 | display: none;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Sidebar/Sidebar.js:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { useHistory, useLocation } from 'react-router-dom';
3 | import styles from './styles/Sidebar.module.css';
4 | import SidebarOption from './SidebarOption/SidebarOption';
5 | import { Button } from '@material-ui/core';
6 | import AddRoundedIcon from '@material-ui/icons/Add';
7 | import InboxRoundedIcon from '@material-ui/icons/Inbox';
8 | import StarRoundedIcon from '@material-ui/icons/Star';
9 | import SendRoundedIcon from '@material-ui/icons/Send';
10 | import NoteRoundedIcon from '@material-ui/icons/Note';
11 | import DeleteRoundedIcon from '@material-ui/icons/Delete';
12 | import ExpandMoreRoundedIcon from '@material-ui/icons/ExpandMoreRounded';
13 |
14 | export default function Sidebar({
15 | toggleIsCompose,
16 | inboxLength,
17 | sentLength,
18 | starredLength,
19 | draftsLength,
20 | trashLength,
21 | }) {
22 | const history = useHistory();
23 | const location = useLocation();
24 |
25 | const [showMore, setShowMore] = useState(false);
26 | const toggleShowMore = () => setShowMore(!showMore);
27 |
28 | return (
29 |
30 |
36 |
37 |
history.push('/email/inbox')}
42 | selected={location.pathname === '/email/inbox'}
43 | />
44 | history.push('/email/starred')}
49 | selected={location.pathname === '/email/starred'}
50 | />
51 | history.push('/email/drafts')}
56 | selected={location.pathname === '/email/drafts'}
57 | />
58 | history.push('/email/sent')}
63 | selected={location.pathname === '/email/sent'}
64 | />
65 |
72 | {showMore && (
73 | <>
74 | history.push('/email/trash')}
79 | selected={location.pathname === '/email/trash'}
80 | />
81 | >
82 | )}
83 |
84 | );
85 | }
86 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Sidebar/SidebarOption/SidebarOption.js:
--------------------------------------------------------------------------------
1 | import styles from './styles/SidebarOption.module.css';
2 |
3 | export default function SidebarOption({ Icon, title, number, selected, onClick, className }) {
4 | return (
5 |
6 |
7 |
{title}
8 |
{number}
9 |
10 | );
11 | }
12 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Sidebar/SidebarOption/styles/SidebarOption.module.css:
--------------------------------------------------------------------------------
1 | .item {
2 | height: 40px;
3 | padding: 10px;
4 | display: flex;
5 | align-items: center;
6 | border-radius: 0 20px 20px 0;
7 | color: #818181;
8 | cursor: pointer;
9 | }
10 |
11 | .item > svg {
12 | padding: 5px;
13 | }
14 |
15 | .item > h3 {
16 | margin-left: 10px;
17 | flex: 1;
18 | font-size: 14px;
19 | font-weight: 400;
20 | -webkit-user-select: none;
21 | -moz-user-select: none;
22 | -ms-user-select: none;
23 | user-select: none;
24 | }
25 |
26 | .item > p {
27 | display: none;
28 | -webkit-user-select: none;
29 | -moz-user-select: none;
30 | -ms-user-select: none;
31 | user-select: none;
32 | }
33 |
34 | .item:hover,
35 | .item:hover > h3,
36 | .item:hover > p,
37 | .active,
38 | .active > h3,
39 | .active > p {
40 | background-color: #fcecec;
41 | color: #c04b37;
42 | font-weight: 700 !important;
43 | }
44 |
45 | .item:hover > p,
46 | .active > p {
47 | display: inline !important;
48 | }
49 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/Sidebar/styles/Sidebar.module.css:
--------------------------------------------------------------------------------
1 | .container {
2 | width: 260px;
3 | padding-right: 20px;
4 | }
5 |
6 | .compose {
7 | margin: 15px 0 15px 11px !important;
8 | padding: 15px !important;
9 | border-radius: 30px !important;
10 | color: #818181 !important;
11 | text-transform: capitalize !important;
12 | box-shadow: 0px 2px 5px -2px rgba(0, 0, 0, 0.75) !important;
13 | }
14 |
15 | .showMore__on > svg {
16 | transform: rotate(0deg);
17 | }
18 |
19 | .showMore__off > svg {
20 | transform: rotate(-90deg);
21 | }
22 |
23 | @media (max-width: 768px) {
24 | .container {
25 | width: 100%;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/client/src/components/EmailPage/styles/EmailPage.module.css:
--------------------------------------------------------------------------------
1 | .main {
2 | min-height: calc(100vh - 90px);
3 | display: flex;
4 | }
5 |
6 | .container {
7 | flex: 1;
8 | }
9 |
--------------------------------------------------------------------------------
/client/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import { Provider } from 'react-redux';
4 | import { store } from './redux/store';
5 | import './styles/reset.css';
6 | import App from './App';
7 |
8 | ReactDOM.render(
9 | //
10 |
11 |
12 | ,
13 | // ,
14 | document.getElementById('root'),
15 | );
16 |
--------------------------------------------------------------------------------
/client/src/redux/actions/accountActions.js:
--------------------------------------------------------------------------------
1 | import {
2 | LOGOUT,
3 | REGISTER_REQUEST,
4 | REGISTER_SUCCESS,
5 | REGISTER_ERROR,
6 | LOGIN_REQUEST,
7 | LOGIN_SUCCESS,
8 | LOGIN_ERROR,
9 | FETCH_USER_REQUEST,
10 | FETCH_USER_SUCCESS,
11 | FETCH_USER_ERROR,
12 | UPLOAD_IMAGE_REQUEST,
13 | UPLOAD_IMAGE_SUCCESS,
14 | UPLOAD_IMAGE_ERROR,
15 | } from './../constants';
16 | import { register, login, getUser, uploadImage } from './../../api';
17 |
18 | export const logoutAction = () => {
19 | return { type: LOGOUT };
20 | };
21 |
22 | export const registerAction = (form) => async (dispatch) => {
23 | dispatch({ type: REGISTER_REQUEST });
24 | try {
25 | const response = await register(form);
26 | dispatch({ type: REGISTER_SUCCESS, payload: response.data.email });
27 | } catch (error) {
28 | dispatch({ type: REGISTER_ERROR, error: error.response.data.message });
29 | }
30 | };
31 |
32 | export const loginAction = (form) => async (dispatch) => {
33 | dispatch({ type: LOGIN_REQUEST });
34 | try {
35 | const response = await login(form);
36 | dispatch({ type: LOGIN_SUCCESS, payload: response.data.token });
37 | } catch (error) {
38 | dispatch({ type: LOGIN_ERROR, error: error.response.data.message });
39 | }
40 | };
41 |
42 | export const getUserAction = () => async (dispatch, getState) => {
43 | dispatch({ type: FETCH_USER_REQUEST });
44 | try {
45 | const response = await getUser(getState().userReducer.token);
46 | dispatch({ type: FETCH_USER_SUCCESS, payload: response.data.user });
47 | } catch (error) {
48 | dispatch({ type: FETCH_USER_ERROR, error: error.response.data.message });
49 | }
50 | };
51 |
52 | export const uploadImageAction = (image) => async (dispatch, getState) => {
53 | dispatch({ type: UPLOAD_IMAGE_REQUEST });
54 | try {
55 | const response = await uploadImage(getState().userReducer.token, image);
56 | dispatch({ type: UPLOAD_IMAGE_SUCCESS, payload: response.data.profilePicture });
57 | } catch (error) {
58 | dispatch({ type: UPLOAD_IMAGE_ERROR, error });
59 | }
60 | };
61 |
--------------------------------------------------------------------------------
/client/src/redux/actions/clearErrors.js:
--------------------------------------------------------------------------------
1 | import { CLEAR_ERRORS } from './../constants';
2 |
3 | export const clearErrors = () => {
4 | return { type: CLEAR_ERRORS };
5 | };
6 |
--------------------------------------------------------------------------------
/client/src/redux/actions/emailActions.js:
--------------------------------------------------------------------------------
1 | import {
2 | FETCH_EMAILS_REQUEST,
3 | FETCH_EMAILS_SUCCESS,
4 | FETCH_EMAILS_ERROR,
5 | SEND_EMAIL_REQUEST,
6 | SEND_EMAIL_SUCCESS,
7 | SEND_EMAIL_ERROR,
8 | SAVE_DRAFT_REQUEST,
9 | SAVE_DRAFT_SUCCESS,
10 | SAVE_DRAFT_ERROR,
11 | UPDATE_DRAFT_REQUEST,
12 | UPDATE_DRAFT_SUCCESS,
13 | UPDATE_DRAFT_ERROR,
14 | EMAIL_TRASH_REQUEST,
15 | EMAIL_TRASH_SUCCESS,
16 | EMAIL_TRASH_ERROR,
17 | EMAIL_UNTRASH_REQUEST,
18 | EMAIL_UNTRASH_SUCCESS,
19 | EMAIL_UNTRASH_ERROR,
20 | TOGGLE_EMAIL_PROP_REQUEST,
21 | TOGGLE_EMAIL_PROP_SUCCESS,
22 | TOGGLE_EMAIL_PROP_ERROR,
23 | DELETE_EMAIL_REQUEST,
24 | DELETE_EMAIL_SUCCESS,
25 | DELETE_EMAIL_ERROR,
26 | } from './../constants';
27 | import {
28 | getAllEmails,
29 | sendEmail,
30 | saveDraft,
31 | updateDraft,
32 | moveToTrash,
33 | removeFromTrash,
34 | markAsRead,
35 | markAsUnread,
36 | setFavorite,
37 | unsetFavorite,
38 | deleteEmail,
39 | } from '../../api';
40 |
41 | export const getEmailsAction = () => async (dispatch, getState) => {
42 | dispatch({ type: FETCH_EMAILS_REQUEST });
43 | try {
44 | const response = await getAllEmails(getState().userReducer.token);
45 | dispatch({ type: FETCH_EMAILS_SUCCESS, payload: response.data.mailbox });
46 | } catch (error) {
47 | dispatch({ type: FETCH_EMAILS_ERROR, error });
48 | }
49 | };
50 |
51 | export const sendEmailAction = (form) => async (dispatch, getState) => {
52 | dispatch({ type: SEND_EMAIL_REQUEST });
53 | try {
54 | const response = await sendEmail(getState().userReducer.token, form);
55 | dispatch({
56 | type: SEND_EMAIL_SUCCESS,
57 | payload: { outbox: response.data.sent, inbox: response.data.received },
58 | });
59 | } catch (error) {
60 | dispatch({ type: SEND_EMAIL_ERROR, error });
61 | }
62 | };
63 |
64 | export const saveDraftAction = (form) => async (dispatch, getState) => {
65 | dispatch({ type: SAVE_DRAFT_REQUEST });
66 | try {
67 | const response = await saveDraft(getState().userReducer.token, form);
68 | dispatch({ type: SAVE_DRAFT_SUCCESS, payload: response.data.draft });
69 | } catch (error) {
70 | dispatch({ type: SAVE_DRAFT_ERROR, error });
71 | }
72 | };
73 |
74 | export const updateDraftAction = (id, form) => async (dispatch, getState) => {
75 | dispatch({ type: UPDATE_DRAFT_REQUEST });
76 | try {
77 | const response = await updateDraft(getState().userReducer.token, id, form);
78 | dispatch({ type: UPDATE_DRAFT_SUCCESS, payload: response.data.draft });
79 | } catch (error) {
80 | dispatch({ type: UPDATE_DRAFT_ERROR, error });
81 | }
82 | };
83 |
84 | export const moveToTrashAction = (id) => async (dispatch, getState) => {
85 | dispatch({ type: EMAIL_TRASH_REQUEST });
86 | try {
87 | const response = await moveToTrash(getState().userReducer.token, id);
88 | dispatch({ type: EMAIL_TRASH_SUCCESS, payload: response.data.mailbox });
89 | } catch (error) {
90 | dispatch({ type: EMAIL_TRASH_ERROR, error });
91 | }
92 | };
93 |
94 | export const removeFromTrashAction = (id) => async (dispatch, getState) => {
95 | dispatch({ type: EMAIL_UNTRASH_REQUEST });
96 | try {
97 | const response = await removeFromTrash(getState().userReducer.token, id);
98 | dispatch({ type: EMAIL_UNTRASH_SUCCESS, payload: response.data.mailbox });
99 | } catch (error) {
100 | dispatch({ type: EMAIL_UNTRASH_ERROR, error });
101 | }
102 | };
103 |
104 | export const markAsReadAction = (id) => async (dispatch, getState) => {
105 | dispatch({ type: TOGGLE_EMAIL_PROP_REQUEST });
106 | try {
107 | const response = await markAsRead(getState().userReducer.token, id);
108 | dispatch({ type: TOGGLE_EMAIL_PROP_SUCCESS, payload: response.data.email });
109 | } catch (error) {
110 | dispatch({ type: TOGGLE_EMAIL_PROP_ERROR, error });
111 | }
112 | };
113 |
114 | export const markAsUnreadAction = (id) => async (dispatch, getState) => {
115 | dispatch({ type: TOGGLE_EMAIL_PROP_REQUEST });
116 | try {
117 | const response = await markAsUnread(getState().userReducer.token, id);
118 | dispatch({ type: TOGGLE_EMAIL_PROP_SUCCESS, payload: response.data.email });
119 | } catch (error) {
120 | dispatch({ type: TOGGLE_EMAIL_PROP_ERROR, error });
121 | }
122 | };
123 |
124 | export const setFavoriteAction = (id) => async (dispatch, getState) => {
125 | dispatch({ type: TOGGLE_EMAIL_PROP_REQUEST });
126 | try {
127 | const response = await setFavorite(getState().userReducer.token, id);
128 | dispatch({ type: TOGGLE_EMAIL_PROP_SUCCESS, payload: response.data.email });
129 | } catch (error) {
130 | dispatch({ type: TOGGLE_EMAIL_PROP_ERROR, error });
131 | }
132 | };
133 |
134 | export const unsetFavoriteAction = (id) => async (dispatch, getState) => {
135 | dispatch({ type: TOGGLE_EMAIL_PROP_REQUEST });
136 | try {
137 | const response = await unsetFavorite(getState().userReducer.token, id);
138 | dispatch({ type: TOGGLE_EMAIL_PROP_SUCCESS, payload: response.data.email });
139 | } catch (error) {
140 | dispatch({ type: TOGGLE_EMAIL_PROP_ERROR, error });
141 | }
142 | };
143 |
144 | export const deleteEmailAction = (id) => async (dispatch, getState) => {
145 | dispatch({ type: DELETE_EMAIL_REQUEST });
146 | try {
147 | const response = await deleteEmail(getState().userReducer.token, id);
148 | dispatch({ type: DELETE_EMAIL_SUCCESS, payload: response.data.id });
149 | } catch (error) {
150 | dispatch({ type: DELETE_EMAIL_ERROR, error });
151 | }
152 | };
153 |
--------------------------------------------------------------------------------
/client/src/redux/constants/index.js:
--------------------------------------------------------------------------------
1 | export const CLEAR_ERRORS = 'CLEAR_ERRORS';
2 | export const LOGOUT = 'LOGOUT';
3 |
4 | export const REGISTER_REQUEST = 'REGISTER_REQUEST';
5 | export const REGISTER_SUCCESS = 'REGISTER_SUCCESS';
6 | export const REGISTER_ERROR = 'REGISTER_ERROR';
7 |
8 | export const LOGIN_REQUEST = 'LOGIN_REQUEST';
9 | export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
10 | export const LOGIN_ERROR = 'LOGIN_ERROR';
11 |
12 | export const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST';
13 | export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS';
14 | export const FETCH_USER_ERROR = 'FETCH_USER_ERROR';
15 |
16 | export const UPLOAD_IMAGE_REQUEST = 'UPLOAD_IMAGE_REQUEST';
17 | export const UPLOAD_IMAGE_SUCCESS = 'UPLOAD_IMAGE_SUCCESS';
18 | export const UPLOAD_IMAGE_ERROR = 'UPLOAD_IMAGE_ERROR';
19 |
20 | export const FETCH_EMAILS_REQUEST = 'FETCH_EMAILS_REQUEST';
21 | export const FETCH_EMAILS_SUCCESS = 'FETCH_EMAILS_SUCCESS';
22 | export const FETCH_EMAILS_ERROR = 'FETCH_EMAILS_ERROR';
23 |
24 | export const SEND_EMAIL_REQUEST = 'SEND_EMAIL_REQUEST';
25 | export const SEND_EMAIL_SUCCESS = 'SEND_EMAIL_SUCCESS';
26 | export const SEND_EMAIL_ERROR = 'SEND_EMAIL_ERROR';
27 |
28 | export const SAVE_DRAFT_REQUEST = 'SAVE_DRAFT_REQUEST';
29 | export const SAVE_DRAFT_SUCCESS = 'SAVE_DRAFT_SUCCES';
30 | export const SAVE_DRAFT_ERROR = 'SAVE_DRAFT_ERROR';
31 |
32 | export const UPDATE_DRAFT_REQUEST = 'UPDATE_DRAFT_REQUEST';
33 | export const UPDATE_DRAFT_SUCCESS = 'UPDATE_DRAFT_SUCCESS';
34 | export const UPDATE_DRAFT_ERROR = 'UPDATE_DRAFT_ERROR';
35 |
36 | export const EMAIL_TRASH_REQUEST = 'EMAIL_TRASH_REQUEST';
37 | export const EMAIL_TRASH_SUCCESS = 'EMAIL_TRASH_SUCCESS';
38 | export const EMAIL_TRASH_ERROR = 'EMAIL_TRASH_ERROR';
39 |
40 | export const EMAIL_UNTRASH_REQUEST = 'EMAIL_UNTRASH_REQUEST';
41 | export const EMAIL_UNTRASH_SUCCESS = 'EMAIL_UNTRASH_SUCCESS';
42 | export const EMAIL_UNTRASH_ERROR = 'EMAIL_UNTRASH_ERROR';
43 |
44 | export const TOGGLE_EMAIL_PROP_REQUEST = 'TOGGLE_EMAIL_PROP_REQUEST';
45 | export const TOGGLE_EMAIL_PROP_SUCCESS = 'TOGGLE_EMAIL_PROP_SUCCESS';
46 | export const TOGGLE_EMAIL_PROP_ERROR = 'TOGGLE_EMAIL_PROP_ERROR';
47 |
48 | export const DELETE_EMAIL_REQUEST = 'DELETE_EMAIL_REQUEST';
49 | export const DELETE_EMAIL_SUCCESS = 'DELETE_EMAIL_SUCCESS';
50 | export const DELETE_EMAIL_ERROR = 'DELETE_EMAIL_ERROR';
51 |
--------------------------------------------------------------------------------
/client/src/redux/reducers/emailReducer.js:
--------------------------------------------------------------------------------
1 | import {
2 | CLEAR_ERRORS,
3 | LOGOUT,
4 | FETCH_EMAILS_REQUEST,
5 | FETCH_EMAILS_SUCCESS,
6 | FETCH_EMAILS_ERROR,
7 | SEND_EMAIL_REQUEST,
8 | SEND_EMAIL_SUCCESS,
9 | SEND_EMAIL_ERROR,
10 | SAVE_DRAFT_REQUEST,
11 | SAVE_DRAFT_SUCCESS,
12 | SAVE_DRAFT_ERROR,
13 | UPDATE_DRAFT_REQUEST,
14 | UPDATE_DRAFT_SUCCESS,
15 | UPDATE_DRAFT_ERROR,
16 | EMAIL_TRASH_REQUEST,
17 | EMAIL_TRASH_SUCCESS,
18 | EMAIL_TRASH_ERROR,
19 | EMAIL_UNTRASH_REQUEST,
20 | EMAIL_UNTRASH_SUCCESS,
21 | EMAIL_UNTRASH_ERROR,
22 | TOGGLE_EMAIL_PROP_REQUEST,
23 | TOGGLE_EMAIL_PROP_SUCCESS,
24 | TOGGLE_EMAIL_PROP_ERROR,
25 | DELETE_EMAIL_REQUEST,
26 | DELETE_EMAIL_SUCCESS,
27 | DELETE_EMAIL_ERROR,
28 | } from './../constants';
29 |
30 | const initialState = {
31 | isLoading: false,
32 | mailbox: {
33 | inbox: [],
34 | outbox: [],
35 | drafts: [],
36 | trash: [],
37 | },
38 | error: '',
39 | };
40 |
41 | export const emailReducer = (state = initialState, action) => {
42 | switch (action.type) {
43 | case CLEAR_ERRORS:
44 | return {
45 | ...state,
46 | error: '',
47 | };
48 |
49 | case LOGOUT:
50 | return initialState;
51 |
52 | case FETCH_EMAILS_REQUEST:
53 | case SEND_EMAIL_REQUEST:
54 | case SAVE_DRAFT_REQUEST:
55 | case UPDATE_DRAFT_REQUEST:
56 | case EMAIL_TRASH_REQUEST:
57 | case EMAIL_UNTRASH_REQUEST:
58 | case TOGGLE_EMAIL_PROP_REQUEST:
59 | case DELETE_EMAIL_REQUEST:
60 | return {
61 | ...state,
62 | isLoading: true,
63 | };
64 |
65 | case FETCH_EMAILS_SUCCESS:
66 | case EMAIL_TRASH_SUCCESS:
67 | case EMAIL_UNTRASH_SUCCESS:
68 | return {
69 | ...state,
70 | isLoading: false,
71 | mailbox: action.payload,
72 | error: '',
73 | };
74 |
75 | case SEND_EMAIL_SUCCESS:
76 | return {
77 | ...state,
78 | isLoading: false,
79 | mailbox: {
80 | ...state.mailbox,
81 | outbox: [...state.mailbox.outbox, action.payload.outbox],
82 | inbox: [...state.mailbox.inbox, action.payload.inbox],
83 | },
84 | error: '',
85 | };
86 |
87 | case SAVE_DRAFT_SUCCESS:
88 | return {
89 | ...state,
90 | isLoading: false,
91 | mailbox: { ...state.mailbox, drafts: [...state.mailbox.drafts, action.payload] },
92 | error: '',
93 | };
94 |
95 | case UPDATE_DRAFT_SUCCESS:
96 | let copyOfDrafts = [...state.mailbox.drafts];
97 | for (let i = 0; i < copyOfDrafts.length; i++) {
98 | if (copyOfDrafts[i]._id === action.payload._id) {
99 | copyOfDrafts[i] = action.payload;
100 | break;
101 | }
102 | }
103 | return {
104 | ...state,
105 | isLoading: false,
106 | mailbox: { ...state.mailbox, drafts: copyOfDrafts },
107 | error: '',
108 | };
109 |
110 | case TOGGLE_EMAIL_PROP_SUCCESS:
111 | let copyOfInbox = [...state.mailbox.inbox],
112 | copyOfOutbox = [...state.mailbox.outbox],
113 | isEmailFound = false;
114 | // search inbox
115 | if (!isEmailFound)
116 | for (let i = 0; i < copyOfInbox.length; i++) {
117 | if (copyOfInbox[i]._id === action.payload._id) {
118 | copyOfInbox[i] = action.payload;
119 | isEmailFound = true;
120 | break;
121 | }
122 | }
123 | // search outbox
124 | if (!isEmailFound)
125 | for (let i = 0; i < copyOfOutbox.length; i++) {
126 | if (copyOfOutbox[i]._id === action.payload._id) {
127 | copyOfOutbox[i] = action.payload;
128 | isEmailFound = true;
129 | break;
130 | }
131 | }
132 | return {
133 | ...state,
134 | isLoading: false,
135 | mailbox: { ...state.mailbox, inbox: copyOfInbox, outbox: copyOfOutbox },
136 | error: '',
137 | };
138 |
139 | case DELETE_EMAIL_SUCCESS:
140 | let copyOfTrash = [...state.mailbox.trash],
141 | copyOfDrafts2 = [...state.mailbox.drafts],
142 | isEmailFound2 = false;
143 | for (let i = 0; i < copyOfTrash.length; i++) {
144 | if (copyOfTrash[i]._id === action.payload) {
145 | copyOfTrash.splice(i, 1);
146 | copyOfDrafts2 = true;
147 | break;
148 | }
149 | }
150 | if (!isEmailFound2) {
151 | for (let i = 0; i < copyOfDrafts2.length; i++) {
152 | if (copyOfDrafts2[i]._id === action.payload) {
153 | copyOfDrafts2.splice(i, 1);
154 | break;
155 | }
156 | }
157 | }
158 | return {
159 | ...state,
160 | isLoading: false,
161 | mailbox: { ...state.mailbox, trash: copyOfTrash, drafts: copyOfDrafts2 },
162 | error: '',
163 | };
164 |
165 | case FETCH_EMAILS_ERROR:
166 | case SEND_EMAIL_ERROR:
167 | case SAVE_DRAFT_ERROR:
168 | case UPDATE_DRAFT_ERROR:
169 | case EMAIL_TRASH_ERROR:
170 | case EMAIL_UNTRASH_ERROR:
171 | case TOGGLE_EMAIL_PROP_ERROR:
172 | case DELETE_EMAIL_ERROR:
173 | return {
174 | ...state,
175 | isLoading: false,
176 | error: action.error,
177 | };
178 |
179 | default:
180 | return state;
181 | }
182 | };
183 |
--------------------------------------------------------------------------------
/client/src/redux/reducers/userReducer.js:
--------------------------------------------------------------------------------
1 | import {
2 | CLEAR_ERRORS,
3 | LOGOUT,
4 | REGISTER_REQUEST,
5 | REGISTER_SUCCESS,
6 | REGISTER_ERROR,
7 | LOGIN_REQUEST,
8 | LOGIN_SUCCESS,
9 | LOGIN_ERROR,
10 | FETCH_USER_REQUEST,
11 | FETCH_USER_SUCCESS,
12 | FETCH_USER_ERROR,
13 | UPLOAD_IMAGE_REQUEST,
14 | UPLOAD_IMAGE_SUCCESS,
15 | UPLOAD_IMAGE_ERROR,
16 | } from './../constants';
17 |
18 | const initialState = {
19 | isLoading: false,
20 | isLoggedIn: false,
21 | token: window.localStorage.getItem('token'),
22 | user: {},
23 | error: '',
24 | };
25 |
26 | export const userReducer = (state = initialState, action) => {
27 | switch (action.type) {
28 | case CLEAR_ERRORS:
29 | return {
30 | ...state,
31 | error: '',
32 | };
33 |
34 | case LOGOUT:
35 | window.localStorage.setItem('token', '');
36 | console.log('🌐 Token removed from Local Storage');
37 | return initialState;
38 |
39 | case REGISTER_REQUEST:
40 | case LOGIN_REQUEST:
41 | case FETCH_USER_REQUEST:
42 | case UPLOAD_IMAGE_REQUEST:
43 | return {
44 | ...state,
45 | isLoading: true,
46 | };
47 |
48 | case REGISTER_SUCCESS:
49 | return {
50 | ...state,
51 | isLoading: false,
52 | user: { email: action.payload },
53 | error: '',
54 | };
55 |
56 | case LOGIN_SUCCESS:
57 | window.localStorage.setItem('token', action.payload);
58 | console.log('🌐 Token saved to Local Storage', action.payload);
59 | return {
60 | ...state,
61 | isLoading: false,
62 | isLoggedIn: true,
63 | token: action.payload,
64 | error: '',
65 | };
66 |
67 | case FETCH_USER_SUCCESS:
68 | return {
69 | ...state,
70 | isLoading: false,
71 | isLoggedIn: true,
72 | user: action.payload,
73 | error: '',
74 | };
75 |
76 | case UPLOAD_IMAGE_SUCCESS:
77 | return {
78 | ...state,
79 | isLoading: false,
80 | user: {
81 | ...state.user,
82 | profilePicture: action.payload,
83 | },
84 | error: '',
85 | };
86 |
87 | case REGISTER_ERROR:
88 | return {
89 | ...state,
90 | isLoading: false,
91 | user: {},
92 | error: action.error,
93 | };
94 |
95 | case LOGIN_ERROR:
96 | case FETCH_USER_ERROR:
97 | window.localStorage.setItem('token', '');
98 | console.log('🌐 Token removed from Local Storage');
99 | return {
100 | ...state,
101 | isLoading: false,
102 | isLoggedIn: false,
103 | token: '',
104 | user: {},
105 | error: action.error,
106 | };
107 |
108 | case UPLOAD_IMAGE_ERROR:
109 | return {
110 | ...state,
111 | isLoading: false,
112 | error: action.error,
113 | };
114 |
115 | default:
116 | return state;
117 | }
118 | };
119 |
--------------------------------------------------------------------------------
/client/src/redux/store.js:
--------------------------------------------------------------------------------
1 | import { combineReducers, createStore, applyMiddleware } from 'redux';
2 | import { composeWithDevTools } from 'redux-devtools-extension';
3 | import thunk from 'redux-thunk';
4 | import logger from 'redux-logger';
5 | import { userReducer } from './reducers/userReducer';
6 | import { emailReducer } from './reducers/emailReducer';
7 |
8 | const allReducers = combineReducers({
9 | userReducer,
10 | emailReducer,
11 | });
12 |
13 | export const store = createStore(allReducers, composeWithDevTools(applyMiddleware(thunk, logger)));
14 |
--------------------------------------------------------------------------------
/client/src/styles/App.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu',
3 | 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
4 | -webkit-font-smoothing: antialiased;
5 | -moz-osx-font-smoothing: grayscale;
6 | }
7 |
8 | .App {
9 | width: 100vw;
10 | min-height: 100vh;
11 | }
12 |
13 | .scroll {
14 | overflow-y: scroll;
15 | }
16 | .scroll::-webkit-scrollbar {
17 | display: none;
18 | }
19 | /*
20 | .scroll::-webkit-scrollbar-track {}
21 | .scroll::-webkit-scrollbar-button {}
22 | .scroll::-webkit-scrollbar-thumb {}
23 | */
24 |
--------------------------------------------------------------------------------
/client/src/styles/reset.css:
--------------------------------------------------------------------------------
1 | /*
2 | HTML5 Reset :: style.css
3 | ----------------------------------------------------------
4 | We have learned much from/been inspired by/taken code where offered from:
5 |
6 | Eric Meyer :: http://meyerweb.com
7 | HTML5 Doctor :: http://html5doctor.com
8 | and the HTML5 Boilerplate :: http://html5boilerplate.com
9 |
10 | -------------------------------------------------------------------------------*/
11 |
12 | /* Let's default this puppy out
13 | -------------------------------------------------------------------------------*/
14 |
15 | html,
16 | body,
17 | body div,
18 | span,
19 | object,
20 | iframe,
21 | h1,
22 | h2,
23 | h3,
24 | h4,
25 | h5,
26 | h6,
27 | p,
28 | blockquote,
29 | pre,
30 | abbr,
31 | address,
32 | cite,
33 | code,
34 | del,
35 | dfn,
36 | em,
37 | img,
38 | ins,
39 | kbd,
40 | q,
41 | samp,
42 | small,
43 | strong,
44 | sub,
45 | sup,
46 | var,
47 | b,
48 | i,
49 | dl,
50 | dt,
51 | dd,
52 | ol,
53 | ul,
54 | li,
55 | fieldset,
56 | form,
57 | label,
58 | legend,
59 | table,
60 | caption,
61 | tbody,
62 | tfoot,
63 | thead,
64 | tr,
65 | th,
66 | td,
67 | article,
68 | aside,
69 | figure,
70 | footer,
71 | header,
72 | menu,
73 | nav,
74 | section,
75 | time,
76 | mark,
77 | audio,
78 | video,
79 | details,
80 | summary {
81 | margin: 0;
82 | padding: 0;
83 | border: 0;
84 | font-size: 100%;
85 | font-weight: normal;
86 | vertical-align: baseline;
87 | background: transparent;
88 | }
89 |
90 | main,
91 | article,
92 | aside,
93 | figure,
94 | footer,
95 | header,
96 | nav,
97 | section,
98 | details,
99 | summary {
100 | display: block;
101 | }
102 |
103 | /* Handle box-sizing while better addressing child elements:
104 | http://css-tricks.com/inheriting-box-sizing-probably-slightly-better-best-practice/ */
105 | html {
106 | box-sizing: border-box;
107 | }
108 |
109 | *,
110 | *:before,
111 | *:after {
112 | box-sizing: inherit;
113 | }
114 |
115 | /* consider resetting the default cursor: https://gist.github.com/murtaugh/5247154
116 | credits to: Tim Murtaugh - https://gist.github.com/murtaugh/5247154 */
117 | html,
118 | body {
119 | cursor: default;
120 | }
121 |
122 | code {
123 | cursor: text;
124 | }
125 |
126 | /*
127 | textarea and input[type="text"] already receive
128 | "cursor: text" via browsers' base stylesheets
129 | */
130 |
131 | a,
132 | label,
133 | button,
134 | input[type='radio'],
135 | input[type='submit'],
136 | input[type='checkbox'] {
137 | cursor: pointer;
138 | }
139 |
140 | button[disabled],
141 | input[disabled] {
142 | cursor: default;
143 | }
144 |
145 | /* Responsive images and other embedded objects */
146 | /* if you don't have full control over `img` tags (if you have to overcome attributes), consider adding height: auto */
147 | img,
148 | object,
149 | embed {
150 | max-width: 100%;
151 | }
152 |
153 | /*
154 | Note: keeping IMG here will cause problems if you're using foreground images as sprites.
155 | In fact, it *will* cause problems with Google Maps' controls at small size.
156 | If this is the case for you, try uncommenting the following:
157 |
158 | #map img {
159 | max-width: none;
160 | }
161 | */
162 |
163 | /* force a vertical scrollbar to prevent a jumpy page */
164 | html {
165 | overflow-y: scroll;
166 | }
167 |
168 | /* we use a lot of ULs that aren't bulleted.
169 | you'll have to restore the bullets within content,
170 | which is fine because they're probably customized anyway */
171 | ul {
172 | list-style: none;
173 | }
174 |
175 | blockquote,
176 | q {
177 | quotes: none;
178 | }
179 |
180 | blockquote:before,
181 | blockquote:after,
182 | q:before,
183 | q:after {
184 | content: '';
185 | content: none;
186 | }
187 |
188 | a {
189 | margin: 0;
190 | padding: 0;
191 | font-size: 100%;
192 | vertical-align: baseline;
193 | background: transparent;
194 | }
195 |
196 | del {
197 | text-decoration: line-through;
198 | }
199 |
200 | abbr[title],
201 | dfn[title] {
202 | border-bottom: 1px dotted #000;
203 | cursor: help;
204 | }
205 |
206 | /* tables still need cellspacing="0" in the markup */
207 | table {
208 | border-collapse: separate;
209 | border-spacing: 0;
210 | }
211 | th {
212 | font-weight: bold;
213 | vertical-align: bottom;
214 | }
215 | td {
216 | font-weight: normal;
217 | vertical-align: top;
218 | }
219 |
220 | hr {
221 | display: block;
222 | height: 1px;
223 | border: 0;
224 | border-top: 1px solid #ccc;
225 | margin: 1em 0;
226 | padding: 0;
227 | }
228 |
229 | input,
230 | select {
231 | vertical-align: middle;
232 | }
233 |
234 | pre {
235 | white-space: pre; /* CSS2 */
236 | white-space: pre-wrap; /* CSS 2.1 */
237 | white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
238 | word-wrap: break-word; /* IE */
239 | }
240 |
241 | input[type='radio'] {
242 | vertical-align: text-bottom;
243 | }
244 | input[type='checkbox'] {
245 | vertical-align: bottom;
246 | }
247 | .ie7 input[type='checkbox'] {
248 | vertical-align: baseline;
249 | }
250 | .ie6 input {
251 | vertical-align: text-bottom;
252 | }
253 |
254 | select,
255 | input,
256 | textarea {
257 | font: 99% sans-serif;
258 | }
259 |
260 | table {
261 | font-size: inherit;
262 | font: 100%;
263 | }
264 |
265 | small {
266 | font-size: 85%;
267 | }
268 |
269 | strong {
270 | font-weight: bold;
271 | }
272 |
273 | td,
274 | td img {
275 | vertical-align: top;
276 | }
277 |
278 | /* Make sure sup and sub don't mess with your line-heights http://gist.github.com/413930
279 | This is tested to not break line-heights in:
280 | -- WinXP/IE6,
281 | -- WinXP/IE7,
282 | -- WinXP/IE8,
283 | -- Mac/FF 3.5.9,
284 | -- Mac/Chrome 5.0,
285 | -- Mac/Safari 4.0.4,
286 | assuming a base font size of 14px and a line-height of 21px, or 1.5em.
287 | Poke this, try to make it break!
288 |
289 | credits to: Ruthie BenDor - https://gist.github.com/unruthless/413930 */
290 | sub,
291 | sup {
292 | /* Specified in % so that the sup/sup is the
293 | right size relative to the surrounding text */
294 | font-size: 75%;
295 |
296 | /* Zero out the line-height so that it doesn't
297 | interfere with the positioning that follows */
298 | line-height: 0;
299 |
300 | /* Where the magic happens: makes all browsers position
301 | the sup/sup properly, relative to the surrounding text */
302 | position: relative;
303 |
304 | /* Note that if you're using Eric Meyer's reset.css, this
305 | is already set and you can remove this rule
306 | vertical-align: baseline;*/
307 | }
308 | sup {
309 | /* Move the superscripted text up */
310 | top: -0.5em;
311 | }
312 | sub {
313 | /* Move the subscripted text down, but only
314 | half as far down as the superscript moved up */
315 | bottom: -0.25em;
316 | }
317 |
318 | /* standardize any monospaced elements */
319 | pre,
320 | code,
321 | kbd,
322 | samp {
323 | font-family: monospace, sans-serif;
324 | }
325 |
326 | /* hand cursor on clickable elements */
327 | .clickable,
328 | label,
329 | input[type='button'],
330 | input[type='submit'],
331 | input[type='file'],
332 | button {
333 | cursor: pointer;
334 | }
335 |
336 | /* Webkit browsers add a 2px margin outside the chrome of form elements */
337 | button,
338 | input,
339 | select,
340 | textarea {
341 | margin: 0;
342 | }
343 |
344 | /* make buttons play nice in IE */
345 | button,
346 | input[type='button'] {
347 | width: auto;
348 | overflow: visible;
349 | }
350 |
351 | /* scale images in IE7 more attractively */
352 | .ie7 img {
353 | -ms-interpolation-mode: bicubic;
354 | }
355 |
356 | /* prevent BG image flicker upon hover
357 | (commented out as usage is rare, and the filter syntax messes with some pre-processors)
358 | .ie6 html {filter: expression(document.execCommand("BackgroundImageCache", false, true));}
359 | */
360 |
361 | /* let's clear some floats */
362 | .clearfix:after {
363 | content: ' ';
364 | display: block;
365 | clear: both;
366 | }
367 |
--------------------------------------------------------------------------------
/preview_login.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/preview_login.png
--------------------------------------------------------------------------------
/preview_mailbox.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BenElferink/mern-gmail-clone/4b1eaf02d93d6b3cf081f3b93765f74be9de9c48/preview_mailbox.png
--------------------------------------------------------------------------------
/server/.env.example:
--------------------------------------------------------------------------------
1 | MONGO_URI = "MongoDB connection URL"
2 | JWT_SECRET = "random string"
--------------------------------------------------------------------------------
/server/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | .DS_Store
3 | .env
--------------------------------------------------------------------------------
/server/api/controllers/account.js:
--------------------------------------------------------------------------------
1 | import Account from './../models/Account.js';
2 | import { validationResult } from 'express-validator';
3 | import bcrypt from 'bcrypt';
4 | import { generateToken } from './../middleware/authToken.js';
5 |
6 | export async function register(request, response, next) {
7 | try {
8 | // validate data types
9 | const validationErrors = validationResult(request);
10 | if (!validationErrors.isEmpty())
11 | return response.status(400).json({
12 | message: 'Invalid data, see response.data.errors for more information',
13 | errors: validationErrors.errors,
14 | });
15 |
16 | // check if email is taken
17 | const foundAccount = await Account.findOne({ email: request.body.email });
18 | if (foundAccount)
19 | return response
20 | .status(400)
21 | .json({ message: 'That email is already taken', email: foundAccount.email });
22 |
23 | // at this point everything is OK, proceed with creating the account
24 | // encrypt password
25 | const salt = await bcrypt.genSalt(10);
26 | const encryptedPassword = await bcrypt.hash(request.body.password, salt);
27 |
28 | // create new user
29 | const newAccount = new Account({
30 | email: request.body.email,
31 | password: encryptedPassword,
32 | name: {
33 | first: request.body.firstName,
34 | middle: request.body.middleName,
35 | last: request.body.lastName,
36 | },
37 | });
38 |
39 | // save created user
40 | const savedAccount = await newAccount.save();
41 | console.log('Account created', savedAccount);
42 |
43 | response.status(201).json({
44 | message: 'Account created',
45 | email: savedAccount.email,
46 | });
47 | } catch (error) {
48 | console.log(error);
49 | response.status(500);
50 | }
51 | }
52 |
53 | export async function login(request, response, next) {
54 | try {
55 | // validate data types
56 | const validationErrors = validationResult(request);
57 | if (!validationErrors.isEmpty())
58 | return response.status(400).json({
59 | message: 'Invalid data, see response.data.errors for more information',
60 | errors: validationErrors.errors,
61 | });
62 |
63 | // find user by email
64 | const foundAccount = await Account.findOne({ email: request.body.email });
65 | if (!foundAccount) return response.status(401).json({ message: 'Bad credentials' });
66 |
67 | // decrypt & compare password
68 | const isPasswordOk = await bcrypt.compare(request.body.password, foundAccount.password);
69 | if (!isPasswordOk) return response.status(401).json({ message: 'Bad credentials' });
70 |
71 | // at this point everything is OK, proceed with creating an authentication token
72 | // generate token
73 | const token = generateToken(foundAccount._id);
74 | console.log('Token generated', token);
75 |
76 | response.status(200).json({ message: 'Login success', token });
77 | } catch (error) {
78 | console.log(error);
79 | response.status(500);
80 | }
81 | }
82 |
83 | export async function getUser(request, response, next) {
84 | try {
85 | // find user with id (decoded from token)
86 | // deselect the: password && mailbox
87 | const foundAccount = await Account.findOne({ _id: request.user }).select('-password -mailbox');
88 | console.log('Account found', foundAccount);
89 |
90 | response.status(200).json({ message: 'Account found', user: foundAccount });
91 | } catch (error) {
92 | console.log(error);
93 | response.status(500);
94 | }
95 | }
96 |
97 | export async function updateProfilePicture(request, response, next) {
98 | try {
99 | // validate data types
100 | // const validationErrors = validationResult(request);
101 | // if (!validationErrors.isEmpty())
102 | // return response.status(400).json({
103 | // message: 'Invalid data, see response.data.errors for more information',
104 | // errors: validationErrors.errors,
105 | // });
106 |
107 | // find user with id (decoded from token)
108 | const foundAccount = await Account.findOne({ _id: request.user });
109 |
110 | // and update its image (base64) data
111 | foundAccount.profilePicture = request.body.image.base64;
112 |
113 | // save changes
114 | const savedAccount = await foundAccount.save();
115 | console.log('Image uploaded', savedAccount.profilePicture);
116 |
117 | response
118 | .status(201)
119 | .json({ message: 'Image uploaded', profilePicture: savedAccount.profilePicture });
120 | } catch (error) {
121 | console.log(error);
122 | response.status(500);
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/server/api/controllers/email.js:
--------------------------------------------------------------------------------
1 | import Email from '../models/Email.js';
2 | import Account from '../models/Account.js';
3 | import { validationResult } from 'express-validator';
4 | import txtgen from 'txtgen';
5 |
6 | export async function getAllEmails(request, response, next) {
7 | try {
8 | // find the user (by id from token) and select it's mailbox
9 | // populate all categories in mailbox with email data
10 | const { mailbox } = await Account.findOne({ _id: request.user })
11 | .select('mailbox')
12 | .populate('mailbox.inbox mailbox.outbox mailbox.drafts mailbox.trash');
13 | console.log('Emails found', mailbox);
14 |
15 | response.status(200).json({ message: 'Emails found', mailbox });
16 | } catch (error) {
17 | console.log(error);
18 | response.status(500);
19 | }
20 | }
21 |
22 | export async function sendEmail(request, response, next) {
23 | try {
24 | // validate data types
25 | const validationErrors = validationResult(request);
26 | if (!validationErrors.isEmpty())
27 | return response.status(400).json({
28 | message: 'Invalid data, see response.data.errors for more information',
29 | errors: validationErrors.errors,
30 | });
31 |
32 | // construct outgoing email
33 | const newEmailOut = new Email({
34 | from: request.body.from,
35 | to: request.body.to,
36 | subject: request.body.subject,
37 | message: request.body.message,
38 | });
39 | // save outgoing email
40 | const savedEmailOut = await newEmailOut.save();
41 | console.log('Email sent', savedEmailOut);
42 |
43 | // generate a random reply email
44 | const newEmailIn = new Email({
45 | from: request.body.to,
46 | to: request.body.from,
47 | subject: 'Re: ' + request.body.subject,
48 | message: txtgen.paragraph(),
49 | });
50 | // save random reply email
51 | const savedEmailIn = await newEmailIn.save();
52 | console.log('Reply received', savedEmailIn);
53 |
54 | response
55 | .status(201)
56 | .json({ message: 'Email sent, reply received', sent: savedEmailOut, received: savedEmailIn });
57 |
58 | // get user and update it's email ID's (outbox)
59 | const foundAccount = await Account.findOne({ _id: request.user });
60 | foundAccount.mailbox.outbox.push(savedEmailOut._id);
61 | foundAccount.mailbox.inbox.push(savedEmailIn._id);
62 | await foundAccount.save();
63 | } catch (error) {
64 | console.log(error);
65 | response.status(500);
66 | }
67 | }
68 |
69 | export async function saveDraft(request, response, next) {
70 | try {
71 | // construct new draft
72 | let newDraft = new Email({
73 | from: request.body.from,
74 | to: request.body.to,
75 | subject: request.body.subject,
76 | message: request.body.message,
77 | });
78 |
79 | // save constructed draft
80 | const savedDraft = await newDraft.save();
81 | console.log('Draft saved', savedDraft);
82 |
83 | response.status(201).json({ message: 'Draft saved', draft: savedDraft });
84 |
85 | // this runs after response has been sent to client
86 | // find user and update it's email ID's
87 | const foundAccount = await Account.findOne({ _id: request.user });
88 | foundAccount.mailbox.drafts.push(savedDraft._id);
89 | await foundAccount.save();
90 | } catch (error) {
91 | console.log(error);
92 | response.status(500);
93 | }
94 | }
95 |
96 | export const updateDraft = async (request, response, next) => {
97 | try {
98 | // find draft using id
99 | let foundDraft = await Email.findOne({ _id: request.params.id });
100 | if (!foundDraft)
101 | return response.status(404).json({ message: 'Email not found', id: request.params.id });
102 |
103 | // update it contents
104 | foundDraft.to = request.body.to;
105 | foundDraft.subject = request.body.subject;
106 | foundDraft.message = request.body.message;
107 |
108 | // and save the draft
109 | const savedDraft = await foundDraft.save();
110 | console.log('Draft updated', savedDraft);
111 |
112 | response.status(200).json({ message: 'Draft updated', draft: savedDraft });
113 | } catch (error) {
114 | console.log(error);
115 | response.status(500);
116 | }
117 | };
118 |
119 | export async function moveToTrash(request, response, next) {
120 | try {
121 | // find user by ID
122 | const foundUser = await Account.findOne({ _id: request.user });
123 |
124 | // locate email in inbox/outbox/drafts and move it to trash
125 | let { inbox, outbox, drafts, trash } = foundUser.mailbox;
126 | let isEmailFound = false;
127 |
128 | if (!isEmailFound)
129 | // search inbox
130 | for (let i = 0; i < inbox.length; i++) {
131 | if (inbox[i].equals(request.params.id)) {
132 | trash.push(inbox[i]);
133 | inbox.splice(i, 1);
134 | console.log('Moved from inbox to trash', request.params.id);
135 | isEmailFound = true;
136 | break;
137 | }
138 | }
139 |
140 | if (!isEmailFound)
141 | // search outbox
142 | for (let i = 0; i < outbox.length; i++) {
143 | if (outbox[i].equals(request.params.id)) {
144 | trash.push(outbox[i]);
145 | outbox.splice(i, 1);
146 | console.log('Moved from outbox to trash', request.params.id);
147 | isEmailFound = true;
148 | break;
149 | }
150 | }
151 |
152 | if (!isEmailFound)
153 | // search drafts
154 | for (let i = 0; i < drafts.length; i++) {
155 | if (drafts[i].equals(request.params.id)) {
156 | trash.push(drafts[i]);
157 | drafts.splice(i, 1);
158 | console.log('Moved from drafts to trash', request.params.id);
159 | isEmailFound = true;
160 | break;
161 | }
162 | }
163 |
164 | // save changes, then populate mailbox for client
165 | const savedUser = await foundUser.save();
166 | const { mailbox } = await Account.populate(
167 | savedUser,
168 | 'mailbox.inbox mailbox.outbox mailbox.drafts mailbox.trash',
169 | );
170 |
171 | response.status(200).json({ message: 'Moved to trash', mailbox });
172 | } catch (error) {
173 | console.log(error);
174 | response.status(500);
175 | }
176 | }
177 |
178 | export async function removeFromTrash(request, response, next) {
179 | try {
180 | // find user by ID
181 | const foundUser = await Account.findOne({ _id: request.user }).populate(
182 | 'mailbox.inbox mailbox.outbox mailbox.drafts mailbox.trash',
183 | );
184 |
185 | // locate email in trash, and return to it's relative category
186 | const { inbox, outbox, drafts, trash } = foundUser.mailbox;
187 | for (let i = 0; i < trash.length; i++) {
188 | // if id's match, email was found in current loop
189 | if (trash[i]._id.equals(request.params.id)) {
190 | if (trash[i].to === '' || trash[i].subject === '' || trash[i].message === '') {
191 | // email origin is drafts
192 | drafts.push(trash[i]._id);
193 | trash.splice(i, 1);
194 | console.log('Moved from trash to drafts', request.params.id);
195 | } else if (trash[i].from === foundUser.email) {
196 | // email origin is outbox
197 | outbox.push(trash[i]._id);
198 | trash.splice(i, 1);
199 | console.log('Moved from trash to outbox', request.params.id);
200 | } else {
201 | // email origin is inbox
202 | inbox.push(trash[i]._id);
203 | trash.splice(i, 1);
204 | console.log('Moved from trash to inbox', request.params.id);
205 | }
206 |
207 | break;
208 | }
209 | }
210 |
211 | // save changes, then populate mailbox for client
212 | const savedUser = await foundUser.save();
213 | const { mailbox } = await Account.populate(
214 | savedUser,
215 | 'mailbox.inbox mailbox.outbox mailbox.drafts mailbox.trash',
216 | );
217 |
218 | response.status(200).json({ message: 'Removed from trash', mailbox });
219 | } catch (error) {
220 | console.log(error);
221 | response.status(500);
222 | }
223 | }
224 |
225 | export async function toggleEmailProperty(request, response, next) {
226 | try {
227 | // find email by id,
228 | const foundEmail = await Email.findOne({ _id: request.params.id });
229 | if (!foundEmail)
230 | return response.status(404).json({ message: 'Email not found', id: request.params.id });
231 |
232 | // and update its chosen property
233 | switch (request.params.toggle) {
234 | case 'read':
235 | foundEmail.read = true;
236 | break;
237 | case 'unread':
238 | foundEmail.read = false;
239 | break;
240 | case 'favorite':
241 | foundEmail.favorite = true;
242 | break;
243 | case 'unfavorite':
244 | foundEmail.favorite = false;
245 | break;
246 | default:
247 | return response.status(404).json({ message: "Wrong params, can't parse request" });
248 | }
249 |
250 | const savedEmail = await foundEmail.save();
251 | console.log(`${request.params.toggle} status updated`, savedEmail);
252 |
253 | // return email
254 | response
255 | .status(200)
256 | .json({ message: `${request.params.toggle} status updated`, email: savedEmail });
257 | } catch (error) {
258 | console.log(error);
259 | response.status(500);
260 | }
261 | }
262 |
263 | export async function deleteEmail(request, response, next) {
264 | try {
265 | // find email by id, and update it delete it
266 | await Email.deleteOne({ _id: request.params.id });
267 | console.log('Email deleted', request.params.id);
268 |
269 | // return email ID (so client can remove the email from a state)
270 | response.status(200).json({ message: 'Email deleted', id: request.params.id });
271 |
272 | // this runs after response has been sent to client
273 | // find user and update it's email ID's
274 | const foundAccount = await Account.findOne({ _id: request.user });
275 | let isEmailFound = false;
276 | let trashbox = foundAccount.mailbox.trash;
277 | for (let i = 0; i < trashbox.length; i++) {
278 | if (trashbox[i].equals(request.params.id)) {
279 | trashbox.splice(i, 1);
280 | isEmailFound = true;
281 | break;
282 | }
283 | }
284 | if (!isEmailFound) {
285 | let drafts = foundAccount.mailbox.drafts;
286 | for (let i = 0; i < drafts.length; i++) {
287 | if (drafts[i].equals(request.params.id)) {
288 | drafts.splice(i, 1);
289 | break;
290 | }
291 | }
292 | }
293 | await foundAccount.save();
294 | } catch (error) {
295 | console.log(error);
296 | response.status(500);
297 | }
298 | }
299 |
--------------------------------------------------------------------------------
/server/api/middleware/authToken.js:
--------------------------------------------------------------------------------
1 | import jwt from 'jsonwebtoken';
2 | import dotenv from 'dotenv';
3 |
4 | dotenv.config();
5 | const secret = process.env.JWT_SECRET;
6 | // "secret key" generator ---> https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx
7 | // Reminder: make sure to set up a secret key in .env (the presented 'secret' is not production valid)
8 |
9 | export const generateToken = (id) => {
10 | return jwt.sign({ id }, new Buffer.from(secret, 'base64'), { expiresIn: '1h' });
11 | };
12 |
13 | export const authenticateToken = (request, response, next) => {
14 | try {
15 | const token = request.headers.authorization.split(' ')[1];
16 | const decoded = jwt.verify(token, new Buffer.from(secret, 'base64'));
17 | request.user = decoded.id;
18 | next();
19 | } catch (error) {
20 | console.log(error.message);
21 | response.status(401).json({ message: error.message });
22 | }
23 | };
24 |
--------------------------------------------------------------------------------
/server/api/middleware/validations.js:
--------------------------------------------------------------------------------
1 | import { body } from 'express-validator';
2 |
3 | export const registerValidations = [
4 | body(['firstName', 'lastName'], 'Name is not valid')
5 | .exists()
6 | .matches(/^[a-z ,.'-]+$/i),
7 | body('middleName', 'Name is not valid')
8 | .optional({ nullable: true, checkFalsy: true })
9 | .matches(/^[a-z ,.'-]+$/i),
10 | body('email', 'Email is not valid').exists().isEmail(),
11 | body('password', 'Password must be over 7 characters').exists().isLength({ min: 7 }),
12 | body('passwordConfirm')
13 | .exists()
14 | .custom((value, { req }) =>
15 | value === req.body.password ? true : Promise.reject('Passwords do not match'),
16 | ),
17 | ];
18 |
19 | export const loginValidations = [
20 | body('email', 'Email is not valid').exists().isEmail(),
21 | body('password', 'Password must be over 7 characters').exists().isLength({ min: 7 }),
22 | ];
23 |
24 | export const emailValidations = [
25 | body('from', 'Email is not valid').exists().isEmail(),
26 | body('to', 'Email is not valid').exists().isEmail(),
27 | body('subject', 'Subject is required').exists(),
28 | body('message', 'Message is required').exists(),
29 | ];
30 |
--------------------------------------------------------------------------------
/server/api/models/Account.js:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose';
2 |
3 | const instance = new mongoose.Schema(
4 | {
5 | email: { type: String, required: true, unique: true },
6 | password: { type: String, required: true },
7 | name: {
8 | first: { type: String, required: true },
9 | middle: { type: String },
10 | last: { type: String, required: true },
11 | },
12 | profilePicture: String,
13 | mailbox: {
14 | inbox: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Email' }],
15 | outbox: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Email' }],
16 | drafts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Email' }],
17 | trash: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Email' }],
18 | },
19 | },
20 | {
21 | timestamps: true,
22 | },
23 | );
24 |
25 | // modelName = model name ---> https://mongoosejs.com/docs/guide.html
26 | // note: use a singular name, mongoose automatically creates a collection like so -> model: 'Person' === collection: 'people'
27 | const modelName = 'Account';
28 |
29 | export default mongoose.model(modelName, instance);
30 |
--------------------------------------------------------------------------------
/server/api/models/Email.js:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose';
2 |
3 | const instance = new mongoose.Schema(
4 | {
5 | from: {
6 | type: String,
7 | required: true,
8 | },
9 | to: String,
10 | subject: String,
11 | message: String,
12 | read: {
13 | type: Boolean,
14 | default: false,
15 | },
16 | favorite: {
17 | type: Boolean,
18 | default: false,
19 | },
20 | },
21 | {
22 | timestamps: true,
23 | },
24 | );
25 |
26 | // modelName = model name ---> https://mongoosejs.com/docs/guide.html
27 | // note: use a singular name, mongoose automatically creates a collection like so -> model: 'Person' === collection: 'people'
28 | const modelName = 'Email';
29 |
30 | export default mongoose.model(modelName, instance);
31 |
--------------------------------------------------------------------------------
/server/api/routes/account.js:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import { authenticateToken } from './../middleware/authToken.js';
3 | import { registerValidations, loginValidations } from '../middleware/validations.js';
4 | import { register, login, getUser, updateProfilePicture } from '../controllers/account.js'; // import request & response function
5 |
6 | // initialize router
7 | const router = express.Router();
8 |
9 | /*
10 | request methods ---> https://www.tutorialspoint.com/http/http_methods.htm
11 | 1st param = extended url path
12 | 2nd param = middlewares (optional)
13 | 3rd param = request & response function (controller)
14 | */
15 | router.post('/register', [...registerValidations], register);
16 | router.post('/login', [...loginValidations], login);
17 | router.get('/', authenticateToken, getUser);
18 | router.put('/image', authenticateToken, updateProfilePicture);
19 |
20 | export default router;
21 |
--------------------------------------------------------------------------------
/server/api/routes/email.js:
--------------------------------------------------------------------------------
1 | import express from 'express';
2 | import { authenticateToken } from '../middleware/authToken.js';
3 | import { emailValidations } from '../middleware/validations.js';
4 | import {
5 | getAllEmails,
6 | sendEmail,
7 | saveDraft,
8 | updateDraft,
9 | moveToTrash,
10 | removeFromTrash,
11 | toggleEmailProperty,
12 | deleteEmail,
13 | } from '../controllers/email.js';
14 |
15 | // initialize router
16 | const router = express.Router();
17 |
18 | /*
19 | request methods ---> https://www.tutorialspoint.com/http/http_methods.htm
20 | 1st param = extended url path
21 | 2nd param = middlewares (optional)
22 | 3rd param = request & response function (controller)
23 | */
24 |
25 | router.get('/', authenticateToken, getAllEmails);
26 | router.post('/send', authenticateToken, [...emailValidations], sendEmail);
27 | router.post('/draft', authenticateToken, saveDraft);
28 | router.put('/draft/:id', authenticateToken, updateDraft);
29 | router.put('/:id/trash', authenticateToken, moveToTrash);
30 | router.put('/:id/untrash', authenticateToken, removeFromTrash);
31 | router.put('/:id/:toggle', authenticateToken, toggleEmailProperty);
32 | router.delete('/:id', authenticateToken, deleteEmail);
33 |
34 | export default router;
35 |
--------------------------------------------------------------------------------
/server/index.js:
--------------------------------------------------------------------------------
1 | import mongoose from 'mongoose'; // MongoDB (database)
2 | import express from 'express'; // Backend App (server)
3 | import cors from 'cors'; // HTTP headers (enable requests)
4 | import morgan from 'morgan'; // Logs incoming requests
5 | import dotenv from 'dotenv'; // Secures content
6 | // import wakeDyno from 'woke-dyno'; // Keep Heroku dynos awake
7 | import accountRoutes from './api/routes/account.js';
8 | import emailRoutes from './api/routes/email.js';
9 |
10 | // initialize app
11 | const app = express();
12 | const origin = '*';
13 |
14 | // middlewares
15 | dotenv.config(); // protected variables
16 | app.use(cors({ origin })); // enables http requests on react development server
17 | app.use(express.json({ limit: '10mb', extended: false })); // body parser
18 | app.use(express.urlencoded({ limit: '1mb', extended: false })); // url parser
19 | app.use(morgan('common')); // logs requests
20 |
21 | // configure db
22 | const MONGO_URI = process.env.MONGO_URI;
23 | const DEPRECATED_FIX = { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true };
24 |
25 | // connect to db
26 | mongoose
27 | .connect(MONGO_URI, DEPRECATED_FIX)
28 | .catch((error) => console.log('❌ MongoDB connection error', error)); // listen for errors on initial connection
29 |
30 | const db = mongoose.connection;
31 | db.on('connected', () => console.log('✅ MongoDB connected')); // connected
32 | db.on('disconnected', () => console.log('❌ MongoDB disconnected')); // disconnected
33 | db.on('error', (error) => console.log('❌ MongoDB connection error', error)); // listen for errors during the session
34 |
35 | // routes
36 | app.get('/', (request, response, next) => response.status(200).json('MERN Gmail clone'));
37 | app.use('/api/v1/account', accountRoutes);
38 | app.use('/api/v1/email', emailRoutes);
39 |
40 | // server is listening for requests
41 | const PORT = process.env.PORT || 8080;
42 | app.listen(PORT, () => {
43 | console.log(`✅ Server is listening on port: ${PORT}`);
44 | // wakeDyno('https://gmail-clone-backend.herokuapp.com').start();
45 | // wakeDyno('https://gmail-clone-frontend.herokuapp.com').start();
46 | });
47 |
--------------------------------------------------------------------------------
/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "homepage": "https://gmail-clone-backend.herokuapp.com",
3 | "name": "server",
4 | "version": "1.0.0",
5 | "main": "index.js",
6 | "type": "module",
7 | "scripts": {
8 | "start": "nodemon server.js || node index.js"
9 | },
10 | "author": "Ben Elferink",
11 | "license": "ISC",
12 | "dependencies": {
13 | "bcrypt": "^5.0.0",
14 | "cors": "^2.8.5",
15 | "dotenv": "^8.2.0",
16 | "express": "^4.17.1",
17 | "express-validator": "^6.9.2",
18 | "jsonwebtoken": "^8.5.1",
19 | "mongoose": "^5.11.15",
20 | "morgan": "^1.10.0",
21 | "txtgen": "^2.2.8"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------