Compare commits
108 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2edcd120e3 | ||
|
|
cb29845c1a | ||
|
|
a94bc4a0a7 | ||
|
|
f03cca1b35 | ||
|
|
85c5812a00 | ||
|
|
eb54852ed3 | ||
|
|
4569122e80 | ||
|
|
db73e2c93d | ||
|
|
324febb0b2 | ||
|
|
6944110b79 | ||
|
|
aa3aa6497b | ||
|
|
bc0e7be940 | ||
|
|
2264c77055 | ||
|
|
299974e483 | ||
|
|
36f565cf83 | ||
|
|
a1ad99d821 | ||
|
|
312b7a4201 | ||
|
|
5b8325eb4d | ||
|
|
32a293fd7d | ||
|
|
283f2b7e03 | ||
|
|
3af6df6204 | ||
|
|
909453634a | ||
|
|
774d78e526 | ||
|
|
8c52211dda | ||
|
|
796c6b256a | ||
|
|
27a0b779f0 | ||
|
|
2a668c4650 | ||
|
|
ee1ffc33e2 | ||
|
|
1866dad550 | ||
|
|
fd45e04f44 | ||
|
|
04cccbe825 | ||
|
|
3bb7ccce85 | ||
|
|
90f8d73a05 | ||
|
|
7bcd917fd9 | ||
|
|
8c707db399 | ||
|
|
8cf53c126b | ||
|
|
723378424d | ||
|
|
fb4e459778 | ||
|
|
af1204e7ca | ||
|
|
f06e65b22d | ||
|
|
142356655d | ||
|
|
ce8bcead85 | ||
|
|
a41cab872f | ||
|
|
f6c0a52ab5 | ||
|
|
b9655590f3 | ||
|
|
1a841acaa2 | ||
|
|
8540360217 | ||
|
|
75979bce3d | ||
|
|
e9e8584d82 | ||
|
|
8c91a055f4 | ||
|
|
c0cc342627 | ||
|
|
733d48c4de | ||
|
|
ebae7d478e | ||
|
|
8de38c6536 | ||
|
|
5c3c54b4a9 | ||
|
|
b629a7014e | ||
|
|
562e59d588 | ||
|
|
f2333078ca | ||
|
|
2f40cf797c | ||
|
|
c349907802 | ||
|
|
bc37d68394 | ||
|
|
a895cc0647 | ||
|
|
60cf80ece7 | ||
|
|
1e86859cc1 | ||
|
|
d1d3040edb | ||
|
|
8ac43d1992 | ||
|
|
2ba6b8bc59 | ||
|
|
1e1039accd | ||
|
|
5b26c86dfe | ||
|
|
711c0fc5ee | ||
|
|
41d557dca6 | ||
|
|
2b1c80743a | ||
|
|
a205f496c9 | ||
|
|
c2b5e7bccd | ||
|
|
4e901d75ae | ||
|
|
be3e2892d2 | ||
|
|
087fb3e7ef | ||
|
|
50943d3a7c | ||
|
|
6a4ac3b31d | ||
|
|
b2ae06f7cf | ||
|
|
ab6817973d | ||
|
|
1c9a390ee7 | ||
|
|
4507903157 | ||
|
|
f47b0c4eb0 | ||
|
|
833ac944c3 | ||
|
|
f862566c54 | ||
|
|
52dc9bd1e9 | ||
|
|
cb078bf083 | ||
|
|
40e22e0392 | ||
|
|
96fcfceb88 | ||
|
|
a2000e302a | ||
|
|
b31db021cb | ||
|
|
cc755d1deb | ||
|
|
5606f0203e | ||
|
|
1d481a17ae | ||
|
|
195b59c88d | ||
|
|
cf21e5cc0f | ||
|
|
14295ca8e5 | ||
|
|
3dff3e6b96 | ||
|
|
6c90e8dc28 | ||
|
|
16df9f7e96 | ||
|
|
04080c700b | ||
|
|
b82670a2ee | ||
|
|
d36b840779 | ||
|
|
e50647784e | ||
|
|
fedda7b932 | ||
|
|
d389451be2 | ||
|
|
0df0da4bf7 |
13
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directories:
|
||||
- "/client"
|
||||
- "/server"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
31
.github/workflows/build-backend.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Build Backend (Server)
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build-backend:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: './server'
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
clean: true
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: './server/package-lock.json'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
31
.github/workflows/build-frontend.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Build Frontend (Client)
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: './client'
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
clean: true
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: './client/package-lock.json'
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
60
README.md
@@ -6,3 +6,63 @@
|
||||
- **E** = [Express.js](https://expressjs.com)
|
||||
- **R** = [React.js](https://reactjs.org)
|
||||
- **N** = [Node.js](https://nodejs.org)
|
||||
|
||||
<br />
|
||||
|
||||
# What is this template?
|
||||
|
||||
This template allows you to quick-start your Fullstack application using the MERN stack, it has a server setup with some basic authentication, and a client ready to communicate with the backend.
|
||||
|
||||
<img src='https://raw.githubusercontent.com/BenElferink/mern-template/refs/heads/images/images/preview.png' />
|
||||
|
||||
<br />
|
||||
|
||||
# How to use this template
|
||||
|
||||
### 1. Generate repository from template:
|
||||
|
||||
Click ["Use this template"](https://github.com/benelferink/mern-template/generate) to generate a
|
||||
new repo, then open your terminal and clone your new repo.
|
||||
|
||||
```
|
||||
git clone https://github.com/[your_user_name]/[your_repo_name].git
|
||||
```
|
||||
|
||||
### 2. Install dependencies:
|
||||
|
||||
Go to the `server` folder, and run `install`.
|
||||
|
||||
```
|
||||
cd ./server
|
||||
npm i
|
||||
```
|
||||
|
||||
Go to the `client` folder, and run `install`.
|
||||
|
||||
```
|
||||
cd ./client
|
||||
npm i
|
||||
```
|
||||
|
||||
### 3. Prepare MongoDB:
|
||||
|
||||
Prepare your MongoDB database (using [Atlas](https://www.mongodb.com/cloud/atlas),
|
||||
or [Community](<https://github.com/benelferink/mern-template/wiki/Install-MongoDB-Community-Server-(MacOS)>)). Then configure your database within `server/src/constants/index.js` (or `server/src/.env`), by configuring the `MONGO_URI` variable.
|
||||
|
||||
### 4. Start applications:
|
||||
|
||||
Go to the `server` folder, and run `dev`.
|
||||
|
||||
```
|
||||
cd ./server
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Go to the `client` folder, and run `dev`.
|
||||
|
||||
```
|
||||
cd ./client
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 5. Happy Coding !!!
|
||||
|
||||
1
client/.env.example
Normal file
@@ -0,0 +1 @@
|
||||
REACT_APP_BACKEND_URL = ""
|
||||
18345
client/package-lock.json
generated
Normal file
43
client/package.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "client-v2",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"start": "serve -s build"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.0",
|
||||
"@mui/material": "^6.4.8",
|
||||
"axios": "^1.8.4",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-scripts": "5.0.1",
|
||||
"zustand": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^19.0.12",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"serve": "^14.2.4"
|
||||
}
|
||||
}
|
||||
BIN
client/public/android-chrome-192x192.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
client/public/android-chrome-512x512.png
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
client/public/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
client/public/favicon-16x16.png
Normal file
|
After Width: | Height: | Size: 665 B |
BIN
client/public/favicon-32x32.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
client/public/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
38
client/public/favicon_SETUP.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Favicon SETUP
|
||||
|
||||
1. Go to [https://favicon.io](https://favicon.io)
|
||||
2. Generate an icon pack
|
||||
3. Drop all images in `/client/public/`
|
||||
4. And configure these 2 files:
|
||||
|
||||
### manifest.json:
|
||||
|
||||
```
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src":"android-chrome-192x192.png",
|
||||
"sizes":"192x192",
|
||||
"type":"image/png"
|
||||
},
|
||||
{
|
||||
"src":"android-chrome-512x512.png",
|
||||
"sizes":"512x512",
|
||||
"type":"image/png"
|
||||
}
|
||||
],
|
||||
```
|
||||
|
||||
### index.html:
|
||||
|
||||
```
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<link rel="icon" type="image/x-icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon-16x16.png" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon-32x32.png" />
|
||||
<link rel="apple-touch-icon" type="image/png" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png" />
|
||||
```
|
||||
24
client/public/index.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<!-- <meta name="author" content="" /> -->
|
||||
<!-- <meta name="description" content="" /> -->
|
||||
<!-- <meta name="keywords" content="" /> -->
|
||||
<link rel="icon" type="image/x-icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon-16x16.png" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon-32x32.png" />
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<title>Web App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root" />
|
||||
</body>
|
||||
</html>
|
||||
30
client/public/manifest.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "Web Application",
|
||||
"short_name": "Web App",
|
||||
"description": "An awesome web application!",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/android-chrome-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff",
|
||||
"developer": {
|
||||
"name": "",
|
||||
"url": ""
|
||||
}
|
||||
}
|
||||
3
client/public/robots.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
10
client/src/@types/index.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export interface Account {
|
||||
username: string
|
||||
password: string
|
||||
role: 'user' | 'admin'
|
||||
}
|
||||
|
||||
export interface FormData {
|
||||
username: Account['username']
|
||||
password: Account['password']
|
||||
}
|
||||
43
client/src/App.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import React, { Fragment } from 'react'
|
||||
import { useAuth } from 'contexts/AuthContext'
|
||||
import AuthModal from 'components/AuthModal'
|
||||
import Header from 'components/Header'
|
||||
import logo from 'assets/react.svg'
|
||||
import 'styles/ReactWelcome.css'
|
||||
|
||||
const App = () => {
|
||||
return (
|
||||
<div className='App'>
|
||||
<Header />
|
||||
<ReactWelcome />
|
||||
<LoggedInStatus />
|
||||
<AuthModal />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ReactWelcome = () => {
|
||||
return (
|
||||
<Fragment>
|
||||
<img src={logo} className='ReactWelcome-logo' alt='logo' />
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to reload.
|
||||
</p>
|
||||
<a className='ReactWelcome-link' href='https://reactjs.org' target='_blank' rel='noopener noreferrer'>
|
||||
Learn React
|
||||
</a>
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
const LoggedInStatus = () => {
|
||||
const { isLoggedIn, account } = useAuth()
|
||||
|
||||
if (isLoggedIn && !!account) {
|
||||
return <p>Hey, {account.username}! I'm happy to let you know: you are authenticated!</p>
|
||||
}
|
||||
|
||||
return <p>Don't forget to start your backend server, and then authenticate yourself.</p>
|
||||
}
|
||||
|
||||
export default App
|
||||
1
client/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 2.6 KiB |
92
client/src/components/AuthModal.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import React, { type ChangeEventHandler, Fragment, useState } from 'react'
|
||||
import { useModalStore } from 'store/useModalStore'
|
||||
import { useAuth } from 'contexts/AuthContext'
|
||||
import { Dialog, DialogTitle, TextField, Button, CircularProgress } from '@mui/material'
|
||||
import { type FormData } from '@types'
|
||||
|
||||
interface Props {}
|
||||
|
||||
const AuthModal: React.FC<Props> = () => {
|
||||
const { login, register } = useAuth()
|
||||
const { currentModal, setCurrentModal } = useModalStore()
|
||||
|
||||
const isRegisterMode = currentModal === 'REGISTER'
|
||||
const isOpen = ['AUTH', 'LOGIN', 'REGISTER'].includes(currentModal)
|
||||
const onClose = () => setCurrentModal('')
|
||||
|
||||
const [formData, setFormData] = useState<FormData>({ username: '', password: '' })
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const handleChange: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
const { name, value } = e.target
|
||||
setFormData((prev) => ({ ...prev, [name]: value }))
|
||||
}
|
||||
|
||||
const clickSubmit = async () => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
isRegisterMode ? await register(formData) : await login(formData)
|
||||
onClose()
|
||||
} catch (error: any) {
|
||||
setError(typeof error === 'string' ? error : JSON.stringify(error))
|
||||
}
|
||||
|
||||
setLoading(false)
|
||||
}
|
||||
|
||||
const isSubmitButtonDisabled = !formData['username'] || !formData['password']
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose}>
|
||||
{isRegisterMode ? <DialogTitle>Create a new account</DialogTitle> : <DialogTitle>Login to your account</DialogTitle>}
|
||||
|
||||
<TextField
|
||||
label='Username'
|
||||
name='username'
|
||||
type='text'
|
||||
value={formData['username']}
|
||||
onChange={handleChange}
|
||||
variant='filled'
|
||||
sx={{ mx: 2, my: 0.5 }}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label='Password'
|
||||
name='password'
|
||||
type='password'
|
||||
value={formData['password']}
|
||||
onChange={handleChange}
|
||||
variant='filled'
|
||||
sx={{ mx: 2, my: 0.5 }}
|
||||
required
|
||||
/>
|
||||
|
||||
{error && <span className='error'>{error}</span>}
|
||||
|
||||
{loading ? (
|
||||
<center>
|
||||
<CircularProgress color='inherit' />
|
||||
</center>
|
||||
) : isRegisterMode ? (
|
||||
<Fragment>
|
||||
<Button onClick={clickSubmit} disabled={isSubmitButtonDisabled}>
|
||||
Register
|
||||
</Button>
|
||||
<Button onClick={() => setCurrentModal('LOGIN')}>I already have an account</Button>
|
||||
</Fragment>
|
||||
) : (
|
||||
<Fragment>
|
||||
<Button onClick={clickSubmit} disabled={isSubmitButtonDisabled}>
|
||||
Login
|
||||
</Button>
|
||||
<Button onClick={() => setCurrentModal('REGISTER')}>I don't have an account</Button>
|
||||
</Fragment>
|
||||
)}
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default AuthModal
|
||||
70
client/src/components/Header.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import React, { Fragment, type MouseEventHandler, useState } from 'react'
|
||||
import { useModalStore } from 'store/useModalStore'
|
||||
import { useAuth } from 'contexts/AuthContext'
|
||||
import OnlineIndicator from 'components/OnlineIndicator'
|
||||
import { AppBar, IconButton, Avatar, Popover, List, ListSubheader, ListItemButton } from '@mui/material'
|
||||
|
||||
interface Props {}
|
||||
|
||||
const Header: React.FC<Props> = () => {
|
||||
const { isLoggedIn, account, logout } = useAuth()
|
||||
const { setCurrentModal } = useModalStore()
|
||||
|
||||
const [anchorEl, setAnchorEl] = useState<(EventTarget & HTMLButtonElement) | null>(null)
|
||||
const [popover, setPopover] = useState(false)
|
||||
|
||||
const openPopover: MouseEventHandler<HTMLButtonElement> = (e) => {
|
||||
setPopover(true)
|
||||
setAnchorEl(e.currentTarget)
|
||||
}
|
||||
|
||||
const closePopover = () => {
|
||||
setPopover(false)
|
||||
setAnchorEl(null)
|
||||
}
|
||||
|
||||
const clickLogin = () => {
|
||||
setCurrentModal('LOGIN')
|
||||
closePopover()
|
||||
}
|
||||
|
||||
const clickRegister = () => {
|
||||
setCurrentModal('REGISTER')
|
||||
closePopover()
|
||||
}
|
||||
|
||||
return (
|
||||
<AppBar className='header' position='static'>
|
||||
<h1>Web App</h1>
|
||||
|
||||
<IconButton onClick={openPopover}>
|
||||
<OnlineIndicator online={isLoggedIn}>
|
||||
<Avatar src={account?.username || ''} alt={account?.username || 'Guest'} />
|
||||
</OnlineIndicator>
|
||||
</IconButton>
|
||||
|
||||
<Popover
|
||||
anchorEl={anchorEl}
|
||||
open={popover}
|
||||
onClose={closePopover}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
|
||||
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
|
||||
>
|
||||
<List style={{ minWidth: '100px' }}>
|
||||
<ListSubheader style={{ textAlign: 'center' }}>Hello, {account?.username || 'Guest'}</ListSubheader>
|
||||
|
||||
{isLoggedIn ? (
|
||||
<ListItemButton onClick={logout}>Logout</ListItemButton>
|
||||
) : (
|
||||
<Fragment>
|
||||
<ListItemButton onClick={clickLogin}>Login</ListItemButton>
|
||||
<ListItemButton onClick={clickRegister}>Register</ListItemButton>
|
||||
</Fragment>
|
||||
)}
|
||||
</List>
|
||||
</Popover>
|
||||
</AppBar>
|
||||
)
|
||||
}
|
||||
|
||||
export default Header
|
||||
64
client/src/components/OnlineIndicator.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import React from 'react'
|
||||
import { styled } from '@mui/material/styles'
|
||||
import { Badge, Avatar } from '@mui/material'
|
||||
|
||||
const StyledBadge = styled(Badge)(({ theme }) => ({
|
||||
'& .MuiBadge-badge': {
|
||||
backgroundColor: 'black',
|
||||
color: 'black',
|
||||
boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
|
||||
'&::after': {
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
borderRadius: '50%',
|
||||
animation: 'ripple 1.2s infinite ease-in-out',
|
||||
border: '1px solid currentColor',
|
||||
content: '""',
|
||||
},
|
||||
},
|
||||
'@keyframes ripple': {
|
||||
'0%': {
|
||||
transform: 'scale(.8)',
|
||||
opacity: 1,
|
||||
},
|
||||
'100%': {
|
||||
transform: 'scale(2.4)',
|
||||
opacity: 0,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const OnlineBadge = styled(StyledBadge)({
|
||||
'& .MuiBadge-badge': {
|
||||
backgroundColor: 'var(--online)',
|
||||
color: 'var(--online)',
|
||||
},
|
||||
})
|
||||
|
||||
const OfflineBadge = styled(StyledBadge)({
|
||||
'& .MuiBadge-badge': {
|
||||
backgroundColor: 'var(--offline)',
|
||||
color: 'var(--offline)',
|
||||
},
|
||||
})
|
||||
|
||||
const OnlineIndicator = ({ online = false, children = <Avatar src='' alt='' /> }) => {
|
||||
if (online) {
|
||||
return (
|
||||
<OnlineBadge variant='dot' overlap='circular' anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}>
|
||||
{children}
|
||||
</OnlineBadge>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<OfflineBadge variant='dot' overlap='circular' anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}>
|
||||
{children}
|
||||
</OfflineBadge>
|
||||
)
|
||||
}
|
||||
|
||||
export default OnlineIndicator
|
||||
4
client/src/constants/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
// api url (where your server is hosted at)
|
||||
const BACKEND_URL = process.env.REACT_APP_BACKEND_URL || 'http://localhost:8080'
|
||||
|
||||
export { BACKEND_URL }
|
||||
113
client/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
import React, { createContext, useContext, useState, useEffect, type PropsWithChildren, useMemo } from 'react'
|
||||
import axios from 'utils/axios'
|
||||
import { type FormData, type Account } from '@types'
|
||||
|
||||
interface Context {
|
||||
token: string | null
|
||||
account: Account | null
|
||||
isLoggedIn: boolean
|
||||
register: (payload: FormData) => Promise<any>
|
||||
login: (payload: FormData) => Promise<any>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const initContext: Context = {
|
||||
token: null,
|
||||
account: null,
|
||||
isLoggedIn: false,
|
||||
register: async () => {},
|
||||
login: async () => {},
|
||||
logout: () => {},
|
||||
}
|
||||
|
||||
// init context
|
||||
const AuthContext = createContext(initContext)
|
||||
const { Provider } = AuthContext
|
||||
|
||||
// export the consumer
|
||||
export const useAuth = () => useContext(AuthContext)
|
||||
|
||||
// export the provider
|
||||
export const AuthProvider = ({ children }: PropsWithChildren) => {
|
||||
const [token, setToken] = useState(localStorage.getItem('token') || initContext.token)
|
||||
const [account, setAccount] = useState(initContext.account)
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(initContext.isLoggedIn)
|
||||
|
||||
const register = (formData: FormData) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post('/auth/register', formData)
|
||||
.then(({ data: { data: accountData, token: accessToken } }) => {
|
||||
setAccount(accountData)
|
||||
setToken(accessToken)
|
||||
setIsLoggedIn(true)
|
||||
resolve(true)
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error?.response?.data?.message || error.message)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const login = (formData: FormData) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post('/auth/login', formData)
|
||||
.then(({ data: { data: accountData, token: accessToken } }) => {
|
||||
setAccount(accountData)
|
||||
setToken(accessToken)
|
||||
setIsLoggedIn(true)
|
||||
resolve(true)
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error?.response?.data?.message || error.message)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
setIsLoggedIn(false)
|
||||
setAccount(null)
|
||||
setToken(null)
|
||||
}
|
||||
|
||||
const loginWithToken = async () => {
|
||||
try {
|
||||
const {
|
||||
data: { data: accountData, token: accessToken },
|
||||
} = await axios.get('/auth/login', {
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
|
||||
setAccount(accountData)
|
||||
setToken(accessToken)
|
||||
setIsLoggedIn(true)
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
if (error?.response?.statusCode === 401) setToken(null)
|
||||
}
|
||||
}
|
||||
|
||||
// This side effect keeps local storage updated with recent token value,
|
||||
// making sure it can be re-used upon refresh or re-open browser
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
localStorage.setItem('token', token)
|
||||
} else {
|
||||
localStorage.removeItem('token')
|
||||
}
|
||||
}, [token])
|
||||
|
||||
// This side effect runs only if we have a token, but no account or logged-in boolean.
|
||||
// This "if" statement is "true" only when refreshed, or re-opened the browser,
|
||||
// if true, it will then ask the backend for the account information (and will get them if the token hasn't expired)
|
||||
useEffect(() => {
|
||||
if (!isLoggedIn && !account && token) loginWithToken()
|
||||
}, [isLoggedIn, account, token]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const value = useMemo(() => ({ token, account, isLoggedIn, register, login, logout }), [token, account, isLoggedIn])
|
||||
|
||||
return <Provider value={value}>{children}</Provider>
|
||||
}
|
||||
19
client/src/functions/get-query-payload.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
const getQueryPayload = (queryStr?: string) => {
|
||||
if (!queryStr) {
|
||||
console.warn('query string is not defined')
|
||||
return {}
|
||||
}
|
||||
|
||||
const queryObj: Record<string, string> = {}
|
||||
const queryArr = (queryStr[0] === '?' ? queryStr.substring(1, queryStr.length) : queryStr).split('&')
|
||||
|
||||
queryArr.forEach((str) => {
|
||||
const [key, val] = str.split('=')
|
||||
|
||||
queryObj[key] = val
|
||||
})
|
||||
|
||||
return queryObj
|
||||
}
|
||||
|
||||
export default getQueryPayload
|
||||
13
client/src/functions/get-token-payload.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
const getTokenPayload = (token?: string) => {
|
||||
if (!token) {
|
||||
console.warn('token is not defined')
|
||||
return {}
|
||||
}
|
||||
|
||||
const informativePart = token.split('.')[1]
|
||||
const payload = JSON.parse(window.atob(informativePart))
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
export default getTokenPayload
|
||||
42
client/src/hooks/useLocalStorage.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
/*
|
||||
|
||||
How to use this hook:
|
||||
import useLocalStorage from './hooks/useLocalStorage';
|
||||
|
||||
function App() {
|
||||
const [example, setExample] = useLocalStorage('example_key', { example: 'anything as default' });
|
||||
|
||||
return ();
|
||||
};
|
||||
|
||||
*/
|
||||
|
||||
const getLsVal = (key: string, defaultValue: any) => {
|
||||
const storedStr = localStorage.getItem(key) || ''
|
||||
|
||||
if (!!storedStr) {
|
||||
return JSON.parse(storedStr)
|
||||
} else {
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
const setLsVal = (key: string, value: any) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
const str = JSON.stringify(value)
|
||||
|
||||
localStorage.setItem(key, str)
|
||||
}
|
||||
}
|
||||
|
||||
const useLocalStorage = (key: string, defaultValue: any = null) => {
|
||||
const [value, setValue] = useState(getLsVal(key, defaultValue))
|
||||
|
||||
useEffect(() => setLsVal(key, value), [key, value])
|
||||
|
||||
return [value, setValue]
|
||||
}
|
||||
|
||||
export default useLocalStorage
|
||||
30
client/src/hooks/useMediaQuery.Ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
/*
|
||||
|
||||
How to use this hook:
|
||||
import useMediaQuery from './hooks/useMediaQuery';
|
||||
|
||||
function App() {
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
|
||||
return ();
|
||||
};
|
||||
|
||||
*/
|
||||
|
||||
const useMediaQuery = (query: string = '(max-width: 768px)') => {
|
||||
const [matches, setMatches] = useState(window.matchMedia(query).matches)
|
||||
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(query)
|
||||
const listener = () => setMatches(media.matches)
|
||||
|
||||
media.addListener(listener)
|
||||
return () => media.removeListener(listener)
|
||||
}, [query])
|
||||
|
||||
return matches
|
||||
}
|
||||
|
||||
export default useMediaQuery
|
||||
18
client/src/index.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import CssBaseline from '@mui/material/CssBaseline'
|
||||
import { AuthProvider } from 'contexts/AuthContext'
|
||||
import App from 'App'
|
||||
import 'styles/index.css'
|
||||
|
||||
const element = document.getElementById('root') as HTMLElement
|
||||
const root = ReactDOM.createRoot(element)
|
||||
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<AuthProvider>
|
||||
<CssBaseline />
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</React.StrictMode>
|
||||
)
|
||||
1
client/src/react-app-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/// <reference types="react-scripts" />
|
||||
11
client/src/store/useModalStore.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { create } from 'zustand'
|
||||
|
||||
interface StoreState {
|
||||
currentModal: string
|
||||
setCurrentModal: (str: string) => void
|
||||
}
|
||||
|
||||
export const useModalStore = create<StoreState>((set) => ({
|
||||
currentModal: '',
|
||||
setCurrentModal: (str) => set({ currentModal: str }),
|
||||
}))
|
||||
23
client/src/styles/ReactWelcome.css
Normal file
@@ -0,0 +1,23 @@
|
||||
.ReactWelcome-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.ReactWelcome-logo {
|
||||
animation: ReactWelcome-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.ReactWelcome-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes ReactWelcome-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
63
client/src/styles/index.css
Normal file
@@ -0,0 +1,63 @@
|
||||
:root {
|
||||
--online: #44b700;
|
||||
--offline: #b74400;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
|
||||
}
|
||||
|
||||
.App {
|
||||
width: 100vw;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header {
|
||||
width: 100% !important;
|
||||
padding: 0 1rem !important;
|
||||
background-color: whitesmoke !important;
|
||||
color: black !important;
|
||||
|
||||
display: flex !important;
|
||||
flex-direction: row !important;
|
||||
align-items: center !important;
|
||||
justify-content: space-between !important;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0.5rem;
|
||||
color: red;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/*
|
||||
Extra Small Devices, Phones
|
||||
@media only screen and (min-width: 480px) {}
|
||||
*/
|
||||
|
||||
/*
|
||||
Small Devices, Tablets
|
||||
@media only screen and (min-width: 768px) {}
|
||||
*/
|
||||
|
||||
/*
|
||||
Medium Devices, Desktops
|
||||
@media only screen and (min-width: 992px) {}
|
||||
*/
|
||||
|
||||
/*
|
||||
Large Devices, Wide Screens
|
||||
@media only screen and (min-width: 1200px) {}
|
||||
*/
|
||||
8
client/src/utils/axios.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import Axios from 'axios'
|
||||
import { BACKEND_URL } from '../constants'
|
||||
|
||||
const axios = Axios.create({
|
||||
baseURL: BACKEND_URL,
|
||||
})
|
||||
|
||||
export default axios
|
||||
27
client/tsconfig.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5", // Specify ECMAScript target version
|
||||
"lib": ["dom", "dom.iterable", "esnext"], // List of library files to be included in the compilation
|
||||
"allowJs": true, // Allow JavaScript files to be compiled
|
||||
"skipLibCheck": true, // Skip type checking of all declaration files
|
||||
"esModuleInterop": true, // Disables namespace imports (import * as fs from "fs") and enables CJS/AMD/UMD style imports (import fs from "fs")
|
||||
"allowSyntheticDefaultImports": true, // Allow default imports from modules with no default export
|
||||
"strict": true, // Enable all strict type checking options
|
||||
"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.
|
||||
"module": "esnext", // Specify module code generation
|
||||
"moduleResolution": "node", // Resolve modules using Node.js style
|
||||
"isolatedModules": true, // Unconditionally emit imports for unresolved files
|
||||
"resolveJsonModule": true, // Include modules imported with .json extension
|
||||
"noEmit": true, // Do not emit output (meaning do not compile code, only perform type checking)
|
||||
"jsx": "react", // Support JSX in .tsx files
|
||||
"sourceMap": true, // Generate corrresponding .map file
|
||||
"declaration": true, // Generate corresponding .d.ts file
|
||||
"noUnusedLocals": true, // Report errors on unused locals
|
||||
"noUnusedParameters": true, // Report errors on unused parameters
|
||||
"incremental": true, // Enable incremental compilation by reading/writing information from prior compilations to a file on disk
|
||||
"noFallthroughCasesInSwitch": true, // Report errors for fallthrough cases in switch statement
|
||||
"baseUrl": "src"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "build"]
|
||||
}
|
||||
BIN
images/mern.jpeg
|
Before Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 431 KiB |
|
Before Width: | Height: | Size: 448 KiB |
|
Before Width: | Height: | Size: 807 KiB |
|
Before Width: | Height: | Size: 334 KiB |
|
Before Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 271 KiB |
16
package.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "mern-application",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"homepage": "/",
|
||||
"author": "Ben Elferink <ben.elferink@icloud.com> (https://github.com/BenElferink)",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/BenElferink/mern-template.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/BenElferink/mern-template/issues",
|
||||
"email": "ben.elferink@icloud.com"
|
||||
},
|
||||
"scripts": {}
|
||||
}
|
||||
3
server/.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
PORT = ""
|
||||
MONGO_URI = ""
|
||||
JWT_SECRET = ""
|
||||
2101
server/package-lock.json
generated
Normal file
29
server/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "commonjs",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"dev": "npx tsx src/index.ts",
|
||||
"build": "rm -rf dist && npx tsc",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcrypt": "^5.1.1",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.7",
|
||||
"express": "^4.21.2",
|
||||
"joi": "^17.13.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mongoose": "^8.15.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.9",
|
||||
"@types/node": "^22.13.12",
|
||||
"typescript": "^5.8.2"
|
||||
}
|
||||
}
|
||||
10
server/src/@types/express.d.ts
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
import 'express'
|
||||
import jwt from 'jsonwebtoken'
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
auth?: jwt.JwtPayload // { uid: string; role: string }
|
||||
}
|
||||
}
|
||||
}
|
||||
5
server/src/@types/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export interface Account {
|
||||
username: string
|
||||
password: string
|
||||
role: 'user' | 'admin'
|
||||
}
|
||||
11
server/src/constants/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
const ORIGIN = '*'
|
||||
const PORT = process.env.PORT || 8080
|
||||
|
||||
// For "MongoDB Atlas": edit MONGO_URI in -> .env file
|
||||
// For "MongoDB Community Server": edit <DB_NAME> in -> MONGO_URI below
|
||||
const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/<DB_NAME>'
|
||||
const MONGO_OPTIONS = {}
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'unsafe_secret'
|
||||
|
||||
export { ORIGIN, PORT, MONGO_URI, MONGO_OPTIONS, JWT_SECRET }
|
||||
32
server/src/controllers/auth/login-with-token.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { type RequestHandler } from 'express'
|
||||
import jwt from '../../utils/jwt'
|
||||
import Account from '../../models/Account'
|
||||
|
||||
const loginWithToken: RequestHandler = async (req, res, next) => {
|
||||
try {
|
||||
const { uid } = req.auth || {}
|
||||
|
||||
// Get account from DB, password is not verified because we're already token-authorized at this point
|
||||
const account = await Account.findOne({ _id: uid }).select('-password')
|
||||
|
||||
if (!account) {
|
||||
return next({
|
||||
statusCode: 400,
|
||||
message: 'Bad credentials',
|
||||
})
|
||||
}
|
||||
|
||||
// Generate access token
|
||||
const token = jwt.signToken({ uid: account._id, role: account.role })
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Succesfully got account',
|
||||
data: account,
|
||||
token,
|
||||
})
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default loginWithToken
|
||||
59
server/src/controllers/auth/login.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { type RequestHandler } from 'express'
|
||||
import joi from '../../utils/joi'
|
||||
import jwt from '../../utils/jwt'
|
||||
import crypt from '../../utils/crypt'
|
||||
import Account from '../../models/Account'
|
||||
|
||||
const login: RequestHandler = async (req, res, next) => {
|
||||
try {
|
||||
const validationError = await joi.validate(
|
||||
{
|
||||
username: joi.instance.string().required(),
|
||||
password: joi.instance.string().required(),
|
||||
},
|
||||
req.body
|
||||
)
|
||||
|
||||
if (validationError) {
|
||||
return next(validationError)
|
||||
}
|
||||
|
||||
const { username, password } = req.body
|
||||
|
||||
// Get account from DB, and verify existance
|
||||
const account = await Account.findOne({ username })
|
||||
|
||||
if (!account) {
|
||||
return next({
|
||||
statusCode: 400,
|
||||
message: 'Bad credentials',
|
||||
})
|
||||
}
|
||||
|
||||
// Verify password hash
|
||||
const passOk = crypt.validate(password, account.password)
|
||||
|
||||
if (!passOk) {
|
||||
return next({
|
||||
statusCode: 400,
|
||||
message: 'Bad credentials',
|
||||
})
|
||||
}
|
||||
|
||||
// Generate access token
|
||||
const token = jwt.signToken({ uid: account._id, role: account.role })
|
||||
|
||||
// Remove password from response data
|
||||
const { password: _, ...accountData } = account.toObject()
|
||||
|
||||
res.status(200).json({
|
||||
message: 'Succesfully logged-in',
|
||||
data: accountData,
|
||||
token,
|
||||
})
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default login
|
||||
56
server/src/controllers/auth/register.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { type RequestHandler } from 'express'
|
||||
import joi from '../../utils/joi'
|
||||
import jwt from '../../utils/jwt'
|
||||
import crypt from '../../utils/crypt'
|
||||
import Account from '../../models/Account'
|
||||
|
||||
const register: RequestHandler = async (req, res, next) => {
|
||||
try {
|
||||
const validationError = await joi.validate(
|
||||
{
|
||||
username: joi.instance.string().required(),
|
||||
password: joi.instance.string().required(),
|
||||
},
|
||||
req.body
|
||||
)
|
||||
|
||||
if (validationError) {
|
||||
return next(validationError)
|
||||
}
|
||||
|
||||
const { username, password } = req.body
|
||||
|
||||
// Verify account username as unique
|
||||
const found = await Account.findOne({ username })
|
||||
|
||||
if (found) {
|
||||
return next({
|
||||
statusCode: 400,
|
||||
message: 'An account already exists with that "username"',
|
||||
})
|
||||
}
|
||||
|
||||
// Encrypt password
|
||||
const hash = crypt.hash(password)
|
||||
|
||||
// Create account
|
||||
const account = new Account({ username, password: hash })
|
||||
await account.save()
|
||||
|
||||
// Generate access token
|
||||
const token = jwt.signToken({ uid: account._id, role: account.role })
|
||||
|
||||
// Exclude password from response
|
||||
const { password: _, ...data } = account.toObject()
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Succesfully registered',
|
||||
data,
|
||||
token,
|
||||
})
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default register
|
||||
28
server/src/index.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import dotenv from 'dotenv'
|
||||
dotenv.config()
|
||||
|
||||
import app from './utils/app' // (server)
|
||||
import mongo from './utils/mongo' // (database)
|
||||
import { PORT } from './constants/index'
|
||||
import authRoutes from './routes/auth'
|
||||
|
||||
const bootstrap = async () => {
|
||||
await mongo.connect()
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
res.status(200).send('Hello, world!')
|
||||
})
|
||||
|
||||
app.get('/healthz', (req, res) => {
|
||||
res.status(204).end()
|
||||
})
|
||||
|
||||
app.use('/auth', authRoutes)
|
||||
// add rest of routes here...
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`✅ Server is listening on port: ${PORT}`)
|
||||
})
|
||||
}
|
||||
|
||||
bootstrap()
|
||||
35
server/src/middlewares/check-bearer-token.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { type RequestHandler } from 'express'
|
||||
import jwt from '../utils/jwt'
|
||||
|
||||
const checkBearerToken: RequestHandler = (req, res, next) => {
|
||||
try {
|
||||
const token = req.headers.authorization?.split(' ')[1]
|
||||
|
||||
if (!token) {
|
||||
return next({
|
||||
statusCode: 400,
|
||||
message: 'Token not provided',
|
||||
})
|
||||
}
|
||||
|
||||
const auth = jwt.verifyToken(token)
|
||||
|
||||
if (!auth) {
|
||||
return next({
|
||||
statusCode: 401,
|
||||
message: 'Invalid token',
|
||||
})
|
||||
}
|
||||
|
||||
req.auth = typeof auth === 'string' ? JSON.parse(auth) : auth
|
||||
|
||||
next()
|
||||
} catch (error) {
|
||||
next({
|
||||
statusCode: 401,
|
||||
message: 'Invalid token',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default checkBearerToken
|
||||
12
server/src/middlewares/error-handler.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { type NextFunction, type Request, type Response } from 'express'
|
||||
|
||||
const errorHandler = (error: any, req: Request, res: Response, next: NextFunction) => {
|
||||
const { statusCode = 500, message = 'Internal server error', ...rest } = error
|
||||
|
||||
res.status(statusCode).json({
|
||||
message,
|
||||
...rest,
|
||||
})
|
||||
}
|
||||
|
||||
export default errorHandler
|
||||
39
server/src/models/Account.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { type Document, model, Schema } from 'mongoose'
|
||||
import { type Account } from '../@types'
|
||||
|
||||
interface I extends Document, Account {}
|
||||
|
||||
const instance = new Schema<I>(
|
||||
{
|
||||
/*
|
||||
document ID is set by default via MongoDB - the next line is deprecated!
|
||||
_id: mongoose.Schema.Types.ObjectId,
|
||||
*/
|
||||
|
||||
username: {
|
||||
type: String,
|
||||
required: true,
|
||||
lowercase: true,
|
||||
unique: true,
|
||||
},
|
||||
password: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
role: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: ['user', 'admin'],
|
||||
default: 'user',
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
)
|
||||
|
||||
// NOTE! use a singular model name, mongoose automatically creates a collection like so:
|
||||
// model: 'Account' === collection: 'accounts'
|
||||
const modelName = 'Account'
|
||||
|
||||
export default model<I>(modelName, instance)
|
||||
20
server/src/routes/auth.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import express from 'express'
|
||||
import checkBearerToken from '../middlewares/check-bearer-token'
|
||||
import errorHandler from '../middlewares/error-handler'
|
||||
import register from '../controllers/auth/register'
|
||||
import login from '../controllers/auth/login'
|
||||
import loginWithToken from '../controllers/auth/login-with-token'
|
||||
|
||||
// initialize router
|
||||
const router = express.Router()
|
||||
|
||||
// POST at route: http://localhost:8080/auth/register
|
||||
router.post('/register', [], register, errorHandler)
|
||||
|
||||
// POST at path: http://localhost:8080/auth/login
|
||||
router.post('/login', [], login, errorHandler)
|
||||
|
||||
// GET at path: http://localhost:8080/auth/account
|
||||
router.get('/login', [checkBearerToken], loginWithToken, errorHandler)
|
||||
|
||||
export default router
|
||||
13
server/src/utils/app.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import express from 'express'
|
||||
import cors from 'cors'
|
||||
import { ORIGIN } from '../constants/index'
|
||||
|
||||
// initialize app
|
||||
const app = express()
|
||||
|
||||
// middlewares
|
||||
app.use(cors({ origin: ORIGIN }))
|
||||
app.use(express.json()) // body parser
|
||||
app.use(express.urlencoded({ extended: false })) // url parser
|
||||
|
||||
export default app
|
||||
22
server/src/utils/crypt.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import bcrypt from 'bcrypt'
|
||||
|
||||
class Crypt {
|
||||
instance: typeof bcrypt = bcrypt
|
||||
|
||||
constructor() {}
|
||||
|
||||
async hash(value: string) {
|
||||
const salt = await this.instance.genSalt(10)
|
||||
const hash = await this.instance.hash(value, salt)
|
||||
|
||||
return hash
|
||||
}
|
||||
|
||||
async validate(value: string, hash: string) {
|
||||
const isOk = await bcrypt.compare(value, hash)
|
||||
|
||||
return isOk
|
||||
}
|
||||
}
|
||||
|
||||
export default new Crypt()
|
||||
22
server/src/utils/joi.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import joi from 'joi'
|
||||
|
||||
class Joi {
|
||||
instance: typeof joi = joi
|
||||
|
||||
constructor() {}
|
||||
|
||||
async validate(schema: Record<string, any>, body: Record<string, any>) {
|
||||
try {
|
||||
await this.instance.object(schema).validateAsync(body)
|
||||
} catch (error: any) {
|
||||
console.log('❌ Joi validation error:', error.message)
|
||||
|
||||
return {
|
||||
statusCode: 400,
|
||||
message: error.message,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new Joi()
|
||||
25
server/src/utils/jwt.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import jsonwebtoken from 'jsonwebtoken'
|
||||
import { JWT_SECRET } from '../constants/index'
|
||||
|
||||
class JWT {
|
||||
instance: typeof jsonwebtoken = jsonwebtoken
|
||||
secret: string
|
||||
|
||||
constructor() {
|
||||
this.secret = JWT_SECRET
|
||||
}
|
||||
|
||||
signToken(payload: Record<string, any>, expiresIn: jsonwebtoken.SignOptions['expiresIn'] = '12h') {
|
||||
const token = this.instance.sign(payload, JWT_SECRET, { expiresIn })
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
verifyToken(token: string) {
|
||||
const auth = this.instance.verify(token, JWT_SECRET)
|
||||
|
||||
return auth
|
||||
}
|
||||
}
|
||||
|
||||
export default new JWT()
|
||||
37
server/src/utils/mongo.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import mongoose from 'mongoose'
|
||||
import { MONGO_URI, MONGO_OPTIONS } from '../constants/index'
|
||||
|
||||
class Mongo {
|
||||
instance: typeof mongoose = mongoose
|
||||
mongoUri: string
|
||||
mongoOptions: mongoose.ConnectOptions
|
||||
isConnected: boolean
|
||||
|
||||
constructor() {
|
||||
this.mongoUri = MONGO_URI
|
||||
this.mongoOptions = MONGO_OPTIONS
|
||||
this.isConnected = false
|
||||
}
|
||||
|
||||
async connect() {
|
||||
if (this.isConnected) return
|
||||
|
||||
try {
|
||||
console.log('⏳ Connecting to MongoDB')
|
||||
|
||||
const db = await this.instance.connect(this.mongoUri, this.mongoOptions)
|
||||
const connection = db.connection
|
||||
|
||||
this.isConnected = connection.readyState === 1
|
||||
if (this.isConnected) console.log('✅ MongoDB connected')
|
||||
|
||||
connection.on('connected', () => console.log('✅ MongoDB connected')) // re-connected
|
||||
connection.on('disconnected', () => console.log('❌ MongoDB disconnected')) // disconnected
|
||||
connection.on('error', (error) => console.log('❌ MongoDB connection error', error)) // listen for errors during the session
|
||||
} catch (error: any) {
|
||||
console.log('❌ MongoDB connection error:', error.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new Mongo()
|
||||
15
server/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "node",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||