Compare commits

..

71 Commits

Author SHA1 Message Date
Kayne Ruse faacb8b8c7 Fixed CORS configuration 2025-07-29 14:40:24 +10:00
Kayne Ruse c48fcba994 Commented out MacOS check in configure-script.js 2025-07-29 12:49:50 +10:00
Kayne Ruse 56e3151db0 Fixed a missing import 2025-07-29 11:02:02 +10:00
Kayne Ruse 8aeaa46332 Updated dependencies, removed server demo 2025-07-26 04:03:32 +10:00
Ratstail91 cd34f0db5c Fully tested the remote database
Added default host for the admin account
2024-05-03 09:22:45 +10:00
Ratstail91 ab9e7456fb UNTESTED: Updated all dependencies 2024-05-03 07:07:32 +10:00
Ratstail91 90a4fc1a6a UNTESTED: Added database port as a configurable option
Also updated license field in package.json
2024-04-15 21:02:58 +10:00
Ratstail91 42fa9e27e7 Updated dependencies 2024-04-15 17:11:18 +10:00
Ratstail91 0c462d0e6c Tweaks to token provider 2023-12-24 06:43:42 +11:00
Ratstail91 fce018d19b Fixed Date API bug 2023-12-24 02:48:53 +11:00
Ratstail91 6717dbdef6 Missed a reference to page limit 2023-12-24 00:30:11 +11:00
Ratstail91 39c3e55bd5 Updated to support PAGE_SIZE in news-server 2023-12-23 23:40:10 +11:00
Ratstail91 c4c836edb7 Updated libraries, docker engine version, docker distro version
Also updated copyright year, since it's nearly time.
2023-12-23 22:40:41 +11:00
Kayne Ruse fe089e13f1 Gotcha! 2023-06-27 04:24:50 +10:00
Kayne Ruse c3a322fe2a Updated dependencies, bumped patch version 2023-06-26 23:02:57 +10:00
Kayne Ruse bac1063de5 Fixed a logout bug 2023-06-26 22:26:27 +10:00
Kayne Ruse 2dcafd200d Updated dependencies 2023-05-29 07:59:12 +10:00
Kayne Ruse a18ea7fe67 Updated dependencies 2023-05-03 21:25:21 +10:00
Kayne Ruse b6e8d7ad7a Updated dependencies 2023-03-25 02:08:25 +11:00
Kayne Ruse 1c4d87622c A few updates 2023-03-19 01:24:13 +11:00
Kayne Ruse 2d9f29e694 Updated dependencies 2023-02-21 09:30:23 +11:00
Kayne Ruse 4b6eb2271c Updated dependencies, License 2023-01-12 08:09:04 +11:00
Kayne Ruse 56fc50d3b9 Bumped version number 2023-01-04 12:57:53 +00:00
Kayne Ruse d29e3397a6 Switched to a slim docker distro 2023-01-04 23:52:11 +11:00
Kayne Ruse 335c7008aa Bumped version number 2022-12-31 19:19:38 +00:00
Kayne Ruse e89b0645ca Fixed URLSearchParams 2022-12-04 12:08:12 +00:00
Kayne Ruse 36e79a513f Fixed reset page 2022-12-04 11:48:23 +00:00
Kayne Ruse 6ef0affcf6 Fixed useEffect() usage 2022-12-01 12:48:04 +00:00
Kayne Ruse cb0c1284bf You're now kicked out to the root page when the refresh token expires 2022-12-01 12:05:43 +00:00
Kayne Ruse 5cf4b66894 Fixed redirect issue 2022-11-29 04:53:29 +00:00
Kayne Ruse 45cf281c91 Updated dependencies 2022-11-13 02:07:15 +00:00
Kayne Ruse 2794b4c724 Updated dependencies 2022-11-13 01:56:14 +00:00
Kayne Ruse b1f49a4166 Removed a dependency 2022-08-01 11:09:35 +01:00
Kayne Ruse 4cbf67dcbb Updated dependencies 2022-08-01 10:34:35 +01:00
Kayne Ruse fd29385cf8 Update README.md 2022-07-28 03:47:23 +10:00
Kayne Ruse 8e81dccef6 Added cookies 2022-07-26 10:18:49 +01:00
Kayne Ruse adeb8c4267 Updated dependencies 2022-07-23 11:45:33 +01:00
Kayne Ruse eb6c3a40d7 Added hook array to auth config 2022-06-15 23:50:58 +01:00
Kayne Ruse 4d4a0b5401 Updated dependencies 2022-06-10 17:07:56 +01:00
Kayne Ruse 490860159e Cleaned up usage of fetch 2022-06-10 16:53:42 +01:00
Kayne Ruse ed01fe6db5 Addressed #34 2022-05-30 06:16:10 +01:00
Kayne Ruse cfb8d20ad2 Merge remote-tracking branch 'refs/remotes/origin/main' 2022-05-30 06:10:20 +01:00
Kayne Ruse d44cae397d Updated dependencies, addressed #33 2022-05-30 06:10:01 +01:00
Kayne Ruse b97fff05b3 Added FUNDING.yml 2022-02-13 07:49:49 +11:00
Kayne Ruse 22703bfbcb Swapped day and month around 2022-01-09 15:02:06 +00:00
Kayne Ruse 14a3c9eabe Added timestamps to the chatbox 2022-01-09 06:39:13 +00:00
Kayne Ruse 8e90a4a540 Trying a fix 2022-01-08 04:59:21 +00:00
Kayne Ruse 1d3c94a1aa Shortened the code with a ternary 2022-01-06 14:26:30 +00:00
Kayne Ruse ca5e79ccf3 Merge pull request #32 from kcampbelljr/macos-docs
Macos docs
2022-01-07 01:15:36 +11:00
Kayne Ruse 03acce1907 Removed an unused dependency 2022-01-06 14:00:51 +00:00
Keith Campbell c0b7280533 removed macos, updated code on original configure script, testing.. 2022-01-05 23:23:09 -05:00
Keith Campbell 2925cce7ca created a copy of the configure script and made the changes needed for now, should we add a macos check to the original configure script instead? 2022-01-04 23:51:02 -05:00
Kayne Ruse b90670b922 Tweaked credits 2022-01-03 19:21:57 +00:00
Kayne Ruse 290f25f898 Added prox to the credits 2022-01-03 08:45:27 +00:00
Kayne Ruse 3cdef433f9 Tweaked moderator privileges 2022-01-02 18:11:11 +00:00
Kayne Ruse 53c8ddab54 Removed rehype-raw 2021-12-30 14:28:10 +00:00
Kayne Ruse 4e94c5338d Removed client-side markdown rendering 2021-12-30 13:21:34 +00:00
Kayne Ruse 55ff5765c6 Swapped out a library 2021-12-27 03:34:00 +00:00
Kayne Ruse d486059430 Updated webpack.config.js 2021-12-26 16:12:23 +00:00
Kayne Ruse 9d8c948dbb Updated dependencies 2021-12-24 07:37:43 +00:00
Kayne Ruse b21fa8db9e Tweaked webpack.config.js 2021-12-20 13:52:43 +00:00
Kayne Ruse c130b74e2d Added an example proxy route to webpack.config.js 2021-12-20 07:33:01 +00:00
Kayne Ruse d37b93d5f7 Updated webpack-dev-server to 4.6.0 2021-12-20 07:07:36 +00:00
Kayne Ruse 829cb2e3da Disabled source map in prod 2021-12-20 06:19:23 +00:00
Kayne Ruse 29f0dbb1ca Fixed HTTPS redirection 2021-12-15 18:39:37 +00:00
Kayne Ruse 13ad7d2435 Updated README.md 2021-12-11 16:57:48 +00:00
Kayne Ruse e30853e0cd Updated configure-script.js 2021-12-11 11:38:17 +00:00
Kayne Ruse 1e16a96f86 Updated README.md 2021-12-11 05:01:10 +00:00
Kayne Ruse cff73107b2 Updated package-lock.json 2021-11-17 06:13:41 +00:00
Kayne Ruse 76417747b3 Bumped node to version 16 LTS 2021-11-17 04:58:08 +00:00
Kayne Ruse b8323723ed Updated package-lock.json 2021-11-15 22:37:51 +00:00
44 changed files with 5274 additions and 16918 deletions
+2
View File
@@ -1,6 +1,8 @@
WEB_PORT=3000 WEB_PORT=3000
DB_HOSTNAME=localhost DB_HOSTNAME=localhost
DB_PORTNAME=3306
DB_DATABASE=template DB_DATABASE=template
DB_USERNAME=template DB_USERNAME=template
DB_PASSWORD=pikachu DB_PASSWORD=pikachu
+5
View File
@@ -0,0 +1,5 @@
# These are supported funding model platforms
patreon: krgamestudios
ko_fi: krgamestudios
custom: ["https://www.paypal.com/donate/?hosted_button_id=73Q82T2ZHV8AA"]
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2021 Kayne Ruse, KR Game Studios Copyright (c) 2021-2023 Kayne Ruse, KR Game Studios
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
+6 -3
View File
@@ -7,7 +7,7 @@ The primary technology involved is:
* React * React
* Nodejs * Nodejs
* MariaDB (with Sequelize) * MariaDB (with Sequelize)
* Docker (with docker-compose) * Docker (with docker compose)
This template is designed to support the development of persistent browser based games (PBBGs), but it, and it's component microservices, can be used elsewhere. This template is designed to support the development of persistent browser based games (PBBGs), but it, and it's component microservices, can be used elsewhere.
@@ -31,7 +31,7 @@ A clean install is this easy:
git clone https://github.com/krgamestudios/MERN-template.git git clone https://github.com/krgamestudios/MERN-template.git
cd MERN-template cd MERN-template
node configure-script.js node configure-script.js
docker-compose up --build docker compose up --build
``` ```
# Setup Development # Setup Development
@@ -39,11 +39,12 @@ docker-compose up --build
To set up this template in development mode: To set up this template in development mode:
1. Ensure mariadb is running in your development environment 1. Ensure mariadb is running in your development environment
2. Run `mariadb sql/create_database.sql` as the root user 2. Run `mariadb tools/create_database.sql` as the root user
3. Run `npm install` 3. Run `npm install`
4. Run `cp .envdev .env` and enter your details into the `.env` file 4. Run `cp .envdev .env` and enter your details into the `.env` file
5. Execute `npm run dev` 5. Execute `npm run dev`
6. Navigate to `http://localhost:3001` in your web browser 6. Navigate to `http://localhost:3001` in your web browser
7. Repeat this process for each microservice (linked above)
# Features List # Features List
@@ -56,6 +57,8 @@ To set up this template in development mode:
- Account deletion - Account deletion
- Password management - Password management
- JSON web token authentication - JSON web token authentication
- HttpOnly cookies for security
- Optional post validation hook
- Fully Featured News Blog (as a microservice) - Fully Featured News Blog (as a microservice)
- Publish, edit or delete articles as needed - Publish, edit or delete articles as needed
- Secured via admin panel - Secured via admin panel
+9 -10
View File
@@ -1,15 +1,14 @@
//polyfills
import 'regenerator-runtime/runtime';
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom/client';
import App from './pages/app'; import App from './pages/app';
import TokenProvider from './pages/utilities/token-provider'; import TokenProvider from './pages/utilities/token-provider';
ReactDOM.render( ReactDOM
<TokenProvider> .createRoot(document.getElementById('root'))
<App /> .render(
</TokenProvider>, <TokenProvider>
document.querySelector('#root') <App />
); </TokenProvider>
)
;
-10
View File
@@ -1,10 +0,0 @@
<header>
<h1 class="text centered">Credits</h1>
</header>
## MERN-template
The MERN-template developed by Kayne Ruse, KR Game Studios
[https://github.com/krgamestudios/MERN-template](https://github.com/krgamestudios/MERN-template)
-4
View File
@@ -1,4 +0,0 @@
<header>
<h1 class="text centered">Privacy Policy</h1>
</header>
+3 -9
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useContext, useRef } from 'react'; import React, { useEffect, useContext, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
@@ -13,7 +13,7 @@ const Account = props => {
//misplaced? //misplaced?
if (!authTokens.accessToken) { if (!authTokens.accessToken) {
return <Redirect to='/' />; return <Navigate to='/' />;
} }
//refs //refs
@@ -23,12 +23,7 @@ const Account = props => {
//grab the user's info //grab the user's info
useEffect(() => { useEffect(() => {
authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/account`, { authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/account`)
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then(blob => blob.json()) .then(blob => blob.json())
.then(json => contactRef.current.checked = json.contact) .then(json => contactRef.current.checked = json.contact)
.catch(e => console.error(e)) .catch(e => console.error(e))
@@ -88,7 +83,6 @@ const update = async (password, retype, contact, tokenFetch) => {
const result = await tokenFetch(`${process.env.AUTH_URI}/auth/account`, { const result = await tokenFetch(`${process.env.AUTH_URI}/auth/account`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
+11 -12
View File
@@ -1,5 +1,5 @@
import React, { useContext, useRef } from 'react'; import React, { useContext, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
@@ -13,7 +13,7 @@ const Login = props => {
//misplaced? //misplaced?
if (authTokens.accessToken) { if (authTokens.accessToken) {
return <Redirect to='/' />; return <Navigate to='/' />;
} }
//refs //refs
@@ -31,17 +31,16 @@ const Login = props => {
async evt => { async evt => {
//on submit //on submit
evt.preventDefault(); evt.preventDefault();
const [err, newTokens] = await handleSubmit(emailRef.current.value, passwordRef.current.value); const [err, accessToken] = await handleSubmit(emailRef.current.value, passwordRef.current.value);
if (err) { if (err) {
alert(err); alert(err);
} }
//save auth tokens and redirect //save auth tokens and redirect
if (newTokens) { if (accessToken) {
authTokens.setAccessToken(newTokens.accessToken); authTokens.setAccessToken(accessToken);
authTokens.setRefreshToken(newTokens.refreshToken);
props.history.push('/'); return <Navigate to='/' />;
} }
} }
}> }>
@@ -72,13 +71,13 @@ const handleSubmit = async (email, password) => {
const result = await fetch(`${process.env.AUTH_URI}/auth/login`, { const result = await fetch(`${process.env.AUTH_URI}/auth/login`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
email, email,
password, password,
}) }),
credentials: 'include'
}); });
//handle errors //handle errors
@@ -89,8 +88,8 @@ const handleSubmit = async (email, password) => {
} }
//return the new auth tokens //return the new auth tokens
const newTokens = await result.json(); const accessToken = await result.text();
return [null, newTokens]; return [null, accessToken];
}; };
//returns an error message, or null on success //returns an error message, or null on success
@@ -38,7 +38,6 @@ const handleSubmit = async (password, authTokens) => {
const result = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/account`, { const result = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/account`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
@@ -52,14 +51,7 @@ const handleSubmit = async (password, authTokens) => {
//force a logout //force a logout
const result2 = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/logout`, { const result2 = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/logout`, {
method: 'DELETE', method: 'DELETE'
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: authTokens.refreshToken
})
}); });
if (!result2.ok) { if (!result2.ok) {
@@ -67,7 +59,6 @@ const handleSubmit = async (password, authTokens) => {
} }
authTokens.setAccessToken(''); authTokens.setAccessToken('');
authTokens.setRefreshToken('');
return [null]; return [null];
}; };
+1 -9
View File
@@ -12,14 +12,7 @@ const Logout = () => {
{ /* Logout logs you out of the server too */ } { /* Logout logs you out of the server too */ }
<Link to='/' onClick={async () => { <Link to='/' onClick={async () => {
const result = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/logout`, { //NOTE: this gets overwritten as a bugfix const result = await authTokens.tokenFetch(`${process.env.AUTH_URI}/auth/logout`, { //NOTE: this gets overwritten as a bugfix
method: 'DELETE', method: 'DELETE'
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
token: authTokens.refreshToken
})
}); });
//any problems? //any problems?
@@ -27,7 +20,6 @@ const Logout = () => {
console.error(await result.text()); console.error(await result.text());
} else { } else {
authTokens.setAccessToken(''); authTokens.setAccessToken('');
authTokens.setRefreshToken('');
} }
}}>Logout</Link> }}>Logout</Link>
</> </>
+7 -5
View File
@@ -1,5 +1,5 @@
import React, { useContext, useRef } from 'react'; import React, { useContext, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
@@ -9,12 +9,15 @@ import { TokenContext } from '../utilities/token-provider';
const validateEmail = require('../../../common/utilities/validate-email'); const validateEmail = require('../../../common/utilities/validate-email');
const Recover = props => { const Recover = props => {
//history
const navigate = useNavigate();
//context //context
const authTokens = useContext(TokenContext); const authTokens = useContext(TokenContext);
//misplaced? //misplaced?
if (authTokens.accessToken) { if (authTokens.accessToken) {
return <Redirect to='/' />; navigate("/");
} }
//refs //refs
@@ -39,7 +42,7 @@ const Recover = props => {
//redirect //redirect
if (redirect) { if (redirect) {
props.history.push('/'); navigate("/");
} }
} }
}> }>
@@ -66,8 +69,7 @@ const handleSubmit = async (email) => {
const result = await fetch(`${process.env.AUTH_URI}/auth/recover`, { const result = await fetch(`${process.env.AUTH_URI}/auth/recover`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
email email
+13 -12
View File
@@ -1,21 +1,23 @@
import React, { useContext, useRef } from 'react'; import React, { useContext, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import queryString from 'query-string';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
import { TokenContext } from '../utilities/token-provider'; import { TokenContext } from '../utilities/token-provider';
const Reset = props => { const Reset = props => {
//params
const [params, setParams] = useSearchParams(); //the URLSearchParams API
//history
const navigate = useNavigate();
//context //context
const authTokens = useContext(TokenContext); const authTokens = useContext(TokenContext);
//query
const query = queryString.parse(props.location.search);
//misplaced? //misplaced?
if (authTokens.accessToken || !query.email || !query.token) { if (authTokens.accessToken || !params.has('email') || !params.has('token')) {
return <Redirect to='/' />; navigate("/");
} }
//refs //refs
@@ -31,7 +33,7 @@ const Reset = props => {
<h1 className='text centered'>Reset Password</h1> <h1 className='text centered'>Reset Password</h1>
<form className='constrained' onSubmit={async evt => { <form className='constrained' onSubmit={async evt => {
evt.preventDefault(); evt.preventDefault();
const [err, redirect] = await update(passwordRef.current.value, retypeRef.current.value, query); const [err, redirect] = await update(passwordRef.current.value, retypeRef.current.value, params);
if (err) { if (err) {
alert(err); alert(err);
@@ -42,7 +44,7 @@ const Reset = props => {
//redirect //redirect
if (redirect) { if (redirect) {
props.history.push('/'); navigate("/");
} }
}}> }}>
<input type='password' name='password' placeholder='New Password' ref={passwordRef} /> <input type='password' name='password' placeholder='New Password' ref={passwordRef} />
@@ -56,7 +58,7 @@ const Reset = props => {
); );
}; };
const update = async (password, retype, query) => { const update = async (password, retype, params) => {
if (password != retype) { if (password != retype) {
return ['Passwords do not match']; return ['Passwords do not match'];
} }
@@ -65,10 +67,9 @@ const update = async (password, retype, query) => {
return ['Password is too short']; return ['Password is too short'];
} }
const result = await fetch(`${process.env.AUTH_URI}/auth/reset?email=${query.email}&token=${query.token}`, { const result = await fetch(`${process.env.AUTH_URI}/auth/reset?email=${params.get('email')}&token=${params.get('token')}`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
+7 -5
View File
@@ -1,5 +1,5 @@
import React, { useContext, useRef } from 'react'; import React, { useContext, useRef } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
@@ -10,12 +10,15 @@ const validateEmail = require('../../../common/utilities/validate-email');
const validateUsername = require('../../../common/utilities/validate-username'); const validateUsername = require('../../../common/utilities/validate-username');
const Signup = props => { const Signup = props => {
//history
const navigate = useNavigate();
//context //context
const authTokens = useContext(TokenContext); const authTokens = useContext(TokenContext);
//misplaced? //misplaced?
if (authTokens.accessToken) { if (authTokens.accessToken) {
return <Redirect to='/' />; navigate("/");
} }
//refs //refs
@@ -44,7 +47,7 @@ const Signup = props => {
//redirect //redirect
if (redirect) { if (redirect) {
props.history.push('/'); navigate("/");
} }
} }
}> }>
@@ -83,8 +86,7 @@ const handleSubmit = async (email, username, password, retype, contact) => {
const result = await fetch(`${process.env.AUTH_URI}/auth/signup`, { const result = await fetch(`${process.env.AUTH_URI}/auth/signup`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
email, email,
+2 -8
View File
@@ -1,13 +1,10 @@
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
import { TokenContext } from '../utilities/token-provider'; import { TokenContext } from '../utilities/token-provider';
import NewsPublisher from './panels/news-publisher';
import NewsEditor from './panels/news-editor';
import GrantAdmin from './panels/grant-admin'; import GrantAdmin from './panels/grant-admin';
import GrantMod from './panels/grant-mod'; import GrantMod from './panels/grant-mod';
@@ -17,7 +14,7 @@ const Admin = props => {
//misplaced? (admin only) //misplaced? (admin only)
if (!authTokens.accessToken || !authTokens.getPayload().admin) { if (!authTokens.accessToken || !authTokens.getPayload().admin) {
return <Redirect to='/' />; return <Navigate to='/' />;
} }
return ( return (
@@ -26,9 +23,6 @@ const Admin = props => {
<div className='page panel'> <div className='page panel'>
<div className='central panel'> <div className='central panel'>
<h1 className='text centered'>Administration Tools</h1> <h1 className='text centered'>Administration Tools</h1>
<NewsPublisher />
<br />
<NewsEditor />
<br /> <br />
<GrantAdmin /> <GrantAdmin />
<br /> <br />
+10 -2
View File
@@ -1,10 +1,13 @@
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body'; import ApplyToBody from '../utilities/apply-to-body';
import { TokenContext } from '../utilities/token-provider'; import { TokenContext } from '../utilities/token-provider';
import NewsPublisher from './panels/news-publisher';
import NewsEditor from './panels/news-editor';
import ChatReports from './panels/chat-reports'; import ChatReports from './panels/chat-reports';
import BanUser from './panels/ban-user'; import BanUser from './panels/ban-user';
@@ -14,7 +17,7 @@ const Mod = props => {
//misplaced? (admin only) //misplaced? (admin only)
if (!authTokens.accessToken || !(authTokens.getPayload().admin || authTokens.getPayload().mod)) { if (!authTokens.accessToken || !(authTokens.getPayload().admin || authTokens.getPayload().mod)) {
return <Redirect to='/' />; return <Navigate to='/' />;
} }
return ( return (
@@ -23,7 +26,12 @@ const Mod = props => {
<div className='page panel'> <div className='page panel'>
<div className='central panel'> <div className='central panel'>
<h1 className='text centered'>Moderation Tools</h1> <h1 className='text centered'>Moderation Tools</h1>
<NewsPublisher />
<br />
<NewsEditor />
<br />
<BanUser /> <BanUser />
<br />
<ChatReports /> <ChatReports />
<Link to='/' className='text centered'>Return Home</Link> <Link to='/' className='text centered'>Return Home</Link>
</div> </div>
@@ -42,8 +42,7 @@ const handleButtonPress = async (username, tokenFetch) => {
const result = await tokenFetch(`${process.env.AUTH_URI}/admin/banuser`, { const result = await tokenFetch(`${process.env.AUTH_URI}/admin/banuser`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
username username
@@ -7,21 +7,13 @@ const ChatReports = props => {
const authTokens = useContext(TokenContext); const authTokens = useContext(TokenContext);
useEffect(async () => { useEffect(() => {
const result = await authTokens.tokenFetch(`${process.env.CHAT_URI}/admin/reports`, { authTokens.tokenFetch(`${process.env.CHAT_URI}/admin/reports`)
method: 'GET', .then(res => res.json())
headers: { .then(json => {
'Access-Control-Allow-Origin': '*' setReports(json);
} })
}); ;
if (!result.ok) {
const err = `${result.status}: ${await result.text()}`;
console.log(err);
alert(err);
} else {
setReports(await result.json());
}
}, []); }, []);
return ( return (
@@ -59,8 +51,7 @@ const deleteReportsFor = (chatlogIndex, tokenFetch, setReports) => {
tokenFetch(`${process.env.CHAT_URI}/admin/reports`, { tokenFetch(`${process.env.CHAT_URI}/admin/reports`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ chatlogIndex }) body: JSON.stringify({ chatlogIndex })
}); });
@@ -51,8 +51,7 @@ const handleButtonPress = async (username, tokenFetch, method) => {
const result = await tokenFetch(`${process.env.AUTH_URI}/admin/admin`, { const result = await tokenFetch(`${process.env.AUTH_URI}/admin/admin`, {
method: method, method: method,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
username username
@@ -51,8 +51,7 @@ const handleButtonPress = async (username, tokenFetch, method) => {
const result = await tokenFetch(`${process.env.AUTH_URI}/admin/mod`, { const result = await tokenFetch(`${process.env.AUTH_URI}/admin/mod`, {
method: method, method: method,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
username username
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useContext, useRef } from 'react'; import React, { useState, useEffect, useContext, useRef } from 'react';
import Select from 'react-dropdown-select'; import Select from 'react-select';
import { TokenContext } from '../../utilities/token-provider'; import { TokenContext } from '../../utilities/token-provider';
@@ -17,38 +17,23 @@ const NewsEditor = props => {
const [index, setIndex] = useState(null); const [index, setIndex] = useState(null);
//run once //run once
useEffect(async () => { useEffect(() => {
const result = await fetch(`${process.env.NEWS_URI}/news/metadata?limit=999`, { fetch(`${process.env.NEWS_URI}/news/metadata?page_size=999`)
method: 'GET', .then(res => res.json())
headers: { .then(json => {
'Content-Type': 'application/json', setArticles(json)
'Access-Control-Allow-Origin': '*' })
}, ;
});
if (!result.ok) {
const err = `${result.status}: ${await result.text()}`;
console.log(err);
alert(err);
} else {
setArticles(await result.json());
}
}, []); }, []);
return ( return (
<div className='panel'> <div className='panel'>
<h2 className='text centered'>News Editor</h2> <h2 className='text centered'>News Editor</h2>
<Select <Select
options={articles.map(article => { return { label: article.title, value: article.index }; })} options={articles.map(article => { return { label: article.title, index: article.index }; })}
onChange={async values => { onChange={async ({index}) => {
//fetch this article //fetch this article
const index = values[0].value; const result = await fetch(`${process.env.NEWS_URI}/news/archive/${index}`);
const result = await fetch(`${process.env.NEWS_URI}/news/archive/${index}`, {
headers: {
'Access-Control-Allow-Origin': '*'
}
});
if (!result.ok) { if (!result.ok) {
const err = `${result.status}: ${await result.text()}`; const err = `${result.status}: ${await result.text()}`;
@@ -109,8 +94,7 @@ const handleSubmit = async (title, author, body, index, tokenFetch) => {
const result = await tokenFetch(`${process.env.NEWS_URI}/news/${index}`, { const result = await tokenFetch(`${process.env.NEWS_URI}/news/${index}`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
title, title,
@@ -28,7 +28,7 @@ const NewsPublisher = props => {
<input type='text' name='title' placeholder='Title' ref={titleRef} /> <input type='text' name='title' placeholder='Title' ref={titleRef} />
<input type='text' name='author' placeholder='Author' ref={authorRef} /> <input type='text' name='author' placeholder='Author' ref={authorRef} />
<textarea name='body' rows='10' cols='150' placeholder='Body of the article goes here...' ref={bodyRef} /> <textarea name='body' rows='10' cols='150' placeholder='Body of the article goes here...' ref={bodyRef} />
<button type='submit'>Publish</button> <button type='submit'>Publish</button>
</form> </form>
</div> </div>
@@ -46,8 +46,7 @@ const handleSubmit = async (title, author, body, tokenFetch) => {
{ {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ body: JSON.stringify({
title, title,
+34 -22
View File
@@ -1,12 +1,8 @@
//react //react
import React, { useContext } from 'react'; import React, { useContext, Suspense, lazy } from 'react';
import { BrowserRouter, Switch } from 'react-router-dom'; import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { TokenContext } from './utilities/token-provider'; import { TokenContext } from './utilities/token-provider';
//library components
import LazyRoute from './utilities/lazy-route';
import MarkdownPage from './utilities/markdown-page';
//styling //styling
import '../styles/styles.css'; import '../styles/styles.css';
@@ -14,33 +10,49 @@ import '../styles/styles.css';
import Footer from './panels/footer'; import Footer from './panels/footer';
import PopupChat from './panels/popup-chat'; import PopupChat from './panels/popup-chat';
//lazy wrappers
const Homepage = lazy(() => import('./homepage'));
const Signup = lazy(() => import('./accounts/signup'));
const Login = lazy(() => import('./accounts/login'));
const Account = lazy(() => import('./accounts/account'));
const Dashboard = lazy(() => import('./dashboard'));
const Recover = lazy(() => import('./accounts/recover'));
const Reset = lazy(() => import('./accounts/reset'));
const Admin = lazy(() => import('./administration/admin'));
const Mod = lazy(() => import('./administration/mod'));
const PrivacyPolicy = lazy(() => import('./static/privacy-policy'));
const Credits = lazy(() => import('./static/credits'));
const NotFound = lazy(() => import('./not-found'));
const App = props => { const App = props => {
const authTokens = useContext(TokenContext); const authTokens = useContext(TokenContext);
//default render //default render
return ( return (
<BrowserRouter> <BrowserRouter>
<Switch> <Suspense>
<LazyRoute exact path='/' component={() => import('./homepage')} /> <Routes>
<Route exact path='/' element={<Homepage />} />
<LazyRoute path='/signup' component={() => import('./accounts/signup')} /> <Route path='/signup' element={<Signup />} />
<LazyRoute path='/login' component={() => import('./accounts/login')} /> <Route path='/login' element={<Login />} />
<LazyRoute path='/account' component={() => import('./accounts/account')} /> <Route path='/account' element={<Account />} />
<LazyRoute path='/dashboard' component={() => import('./dashboard')} /> <Route path='/dashboard' element={<Dashboard />} />
<LazyRoute path='/recover' component={() => import('./accounts/recover')} /> <Route path='/recover' element={<Recover />} />
<LazyRoute path='/reset' component={() => import('./accounts/reset')} /> <Route path='/reset' element={<Reset />} />
<LazyRoute path='/admin' component={() => import('./administration/admin')} /> <Route path='/admin' element={<Admin />} />
<LazyRoute path='/mod' component={() => import('./administration/mod')} /> <Route path='/mod' element={<Mod />} />
<LazyRoute path='/privacypolicy' component={async () => () => <MarkdownPage content={require('../markdown/privacy-policy.md').default} />} /> <Route path='/privacypolicy' element={<PrivacyPolicy />} />
<LazyRoute path='/credits' component={async () => () => <MarkdownPage content={require('../markdown/credits.md').default} />} /> <Route path='/credits' element={<Credits />} />
<LazyRoute path='*' component={() => import('./not-found')} /> <Route path='*' element={<NotFound />} />
</Switch> </Routes>
{ authTokens.accessToken ? <PopupChat /> : <></> } </Suspense>
<Footer /> { authTokens.accessToken ? <PopupChat /> : <></> }
<Footer />
</BrowserRouter> </BrowserRouter>
); );
}; };
+2 -3
View File
@@ -1,11 +1,10 @@
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from './utilities/apply-to-body'; import ApplyToBody from './utilities/apply-to-body';
import { TokenContext } from './utilities/token-provider'; import { TokenContext } from './utilities/token-provider';
import MarkdownPanel from './utilities/markdown-panel';
import Logout from './accounts/panels/logout'; import Logout from './accounts/panels/logout';
const Dashboard = props => { const Dashboard = props => {
@@ -14,7 +13,7 @@ const Dashboard = props => {
//misplaced? //misplaced?
if (!authTokens.accessToken) { if (!authTokens.accessToken) {
return <Redirect to='/' />; return <Navigate to='/' />;
} }
return ( return (
+2 -3
View File
@@ -1,11 +1,10 @@
import React, { useContext } from 'react'; import React, { useContext } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Link, Navigate } from 'react-router-dom';
import ApplyToBody from './utilities/apply-to-body'; import ApplyToBody from './utilities/apply-to-body';
import { TokenContext } from './utilities/token-provider'; import { TokenContext } from './utilities/token-provider';
import MarkdownPanel from './utilities/markdown-panel';
import NewsFeed from './panels/news-feed'; import NewsFeed from './panels/news-feed';
const HomePage = props => { const HomePage = props => {
@@ -14,7 +13,7 @@ const HomePage = props => {
//misplaced? //misplaced?
if (authTokens.accessToken) { if (authTokens.accessToken) {
return <Redirect to='/dashboard' />; return <Navigate to='/dashboard' />;
} }
return ( return (
+1 -1
View File
@@ -13,7 +13,7 @@ const Break = () => {
const Footer = () => { const Footer = () => {
return ( return (
<footer> <footer>
<p className='text centered'>© <a href='https://krgamestudios.com'>KR Game Studios</a> 2020-2021<Break /><Link to='/privacypolicy'>Privacy Policy</Link><Break /><Link to='/credits'>Credits</Link></p> <p className='text centered'>© <a href='https://krgamestudios.com'>KR Game Studios</a> 2020-2024<Break /><Link to='/privacypolicy'>Privacy Policy</Link><Break /><Link to='/credits'>Credits</Link></p>
</footer> </footer>
); );
}; };
+1 -8
View File
@@ -1,8 +1,6 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import dateFormat from 'dateformat'; import dateFormat from 'dateformat';
import MarkdownPanel from '../utilities/markdown-panel';
const NewsFeed = props => { const NewsFeed = props => {
const [articles, setArticles] = useState([]); const [articles, setArticles] = useState([]);
const aborter = useRef(new AbortController()); //BUGFIX: double-renders = double fetches + react update after unmount const aborter = useRef(new AbortController()); //BUGFIX: double-renders = double fetches + react update after unmount
@@ -10,11 +8,6 @@ const NewsFeed = props => {
useEffect(() => { useEffect(() => {
//this... um... //this... um...
fetch(`${process.env.NEWS_URI}/news`, { fetch(`${process.env.NEWS_URI}/news`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
signal: aborter.current.signal //oh dear signal: aborter.current.signal //oh dear
}) })
.then(blob => blob.json()) .then(blob => blob.json())
@@ -40,7 +33,7 @@ const NewsFeed = props => {
<span>Published {dateFormat(article.createdAt, 'fullDate')}</span> <span>Published {dateFormat(article.createdAt, 'fullDate')}</span>
}</em></p> }</em></p>
<br /> <br />
<MarkdownPanel style={{whiteSpace: 'pre-wrap'}} content={article.body} /> <div dangerouslySetInnerHTML={{ __html: article.rendered }} />
</div> </div>
); );
})} })}
+33 -3
View File
@@ -78,7 +78,7 @@ const handleSend = (inputRef, pushChatlog, username, accessToken) => {
}); });
if (!inputRef.current.value.startsWith('/')) { if (!inputRef.current.value.startsWith('/')) {
pushChatlog({ username: username, text: inputRef.current.value }); pushChatlog({ createdAt: (new Date(Date.now())).toISOString(), username: username, text: inputRef.current.value });
} }
inputRef.current.value = ''; inputRef.current.value = '';
@@ -86,7 +86,36 @@ const handleSend = (inputRef, pushChatlog, username, accessToken) => {
//render each line //render each line
const processLine = (line, index, accessToken) => { const processLine = (line, index, accessToken) => {
let content = <div className='content'>{line.username ? <span className='username'>{line.username}: </span> : ''}{line.text ? <span className='text'>{line.text}</span> : ''}</div>; //utility functions
const isValidDate = d => {
return d instanceof Date && !isNaN(d);
};
const isToday = d => {
const now = new Date(Date.now());
return d.getDate() == now.getDate() && d.getMonth() == now.getMonth() && d.getFullYear() == now.getFullYear();
};
const isThisYear = d => {
const now = new Date(Date.now());
return d.getFullYear() == now.getFullYear();
};
//parse the date
const date = new Date(line.createdAt);
//split it up so we can format each field individually
const year = `${date.getFullYear()}`;
const month = `${date.getMonth() + 1}`;
const day = `${date.getDate()}`;
const hours = `${date.getHours()}`;
const minutes = `${date.getMinutes()}`.padStart(2, '0');
//combine into the final timestamp
const timestamp = !isValidDate(date) ? '' : isToday(date) ? `${hours}:${minutes}` : isThisYear(date) ? `${month}/${day}` : `${year}`;
//generate the content string
let content = <div className='content row'>{timestamp.length > 0 ? <span className='timestamp col'>{timestamp}</span> : null }<span className='inner col'>{line.username ? <span className='username'>{line.username}: </span> : ''}{line.text ? <span className='text'>{line.text}</span> : ''}</span></div>;
//decorators //decorators
if (line.emphasis) { if (line.emphasis) {
@@ -97,7 +126,8 @@ const processLine = (line, index, accessToken) => {
content = <strong>{content}</strong>; content = <strong>{content}</strong>;
} }
return <li key={index} className='line'>{content}<a className='report' onClick={() => processReport(line, accessToken)}>!!!</a></li>;
return <li key={index} className='line table noCollapse'>{content}<a className='report' onClick={() => processReport(line, accessToken)}>!!!</a></li>;
}; };
const processReport = (line, accessToken) => { const processReport = (line, accessToken) => {
+18
View File
@@ -0,0 +1,18 @@
import React from 'react';
import { Link } from 'react-router-dom';
const Static = props => {
return (
<div className='page central'>
<header>
<h1 className='text centered'>Credits</h1>
</header>
<h2 className='text centered'>MERN-template</h2>
<p>The <a href='https://github.com/krgamestudios/MERN-template'>MERN-template</a> developed by Kayne Ruse, KR Game Studios</p>
<Link className='text centered' to='/'>Return Home</Link>
</div>
);
};
export default Static;
+16
View File
@@ -0,0 +1,16 @@
import React from 'react';
import { Link } from 'react-router-dom';
const Static = props => {
return (
<div className='page central'>
<header>
<h1 className="text centered">Privacy Policy</h1>
<Link className='text centered' to='/'>Return Home</Link>
</header>
</div>
);
};
export default Static;
-13
View File
@@ -1,13 +0,0 @@
import React from 'react';
import { Route } from 'react-router-dom';
import loadable from '@loadable/component';
const LazyRoute = props => {
const { component, ...lazyProps } = props;
const lazyComponent = loadable(component);
return <Route {...lazyProps} component={lazyComponent} />
};
export default LazyRoute;
-22
View File
@@ -1,22 +0,0 @@
import React from 'react';
import { Link } from 'react-router-dom';
import ApplyToBody from '../utilities/apply-to-body';
import MarkdownPanel from './markdown-panel';
const MarkdownPage = props => {
return (
<>
<ApplyToBody className='dashboard' />
<div className='page'>
<div className='central panel'>
<MarkdownPanel uri={props.uri} content={props.content} />
<Link to='/' className='text centered'>Return Home</Link>
</div>
</div>
</>
)
};
export default MarkdownPage;
-35
View File
@@ -1,35 +0,0 @@
import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
const Markdown = props => {
//content?
let [contentHook, setContentHook] = useState(null);
//check arguments
if (!props.content) {
if (!props.uri) {
throw 'Markdown requires either content or uri prop';
}
//once
useEffect(() => {
fetch(props.uri)
.then(blob => blob.text())
.then(blob => setContentHook(blob))
.catch(e => console.error(e))
;
}, []);
}
//assume raw info
else if (!contentHook) {
setContentHook(props.content);
}
return (
<ReactMarkdown rehypePlugins={[rehypeRaw]} props={{...props}}>{contentHook}</ReactMarkdown>
);
};
export default Markdown;
+29 -28
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect, createContext } from 'react'; import React, { useState, useEffect, createContext } from 'react';
import decode from 'jwt-decode'; import { jwtDecode } from 'jwt-decode';
export const TokenContext = createContext(); export const TokenContext = createContext();
@@ -8,19 +8,22 @@ export const TokenContext = createContext();
const TokenProvider = props => { const TokenProvider = props => {
//state to be used //state to be used
const [accessToken, setAccessToken] = useState(''); const [accessToken, setAccessToken] = useState('');
const [refreshToken, setRefreshToken] = useState('');
//make the access and refresh tokens persist between reloads //force a logout under certain conditions
const forceLogout = () => {
localStorage.removeItem("accessToken");
setAccessToken("");
};
//make the access token persist between reloads
useEffect(() => { useEffect(() => {
setAccessToken(localStorage.getItem("accessToken") || ''); setAccessToken(localStorage.getItem("accessToken") || '');
setRefreshToken(localStorage.getItem("refreshToken") || '');
}, []); }, []);
//update the stored copies //update the stored copies
useEffect(() => { useEffect(() => {
localStorage.setItem("accessToken", accessToken); localStorage.setItem("accessToken", accessToken);
localStorage.setItem("refreshToken", refreshToken); }, [accessToken]);
}, [accessToken, refreshToken]);
//wrap the default fetch function //wrap the default fetch function
const tokenFetch = async (url, options) => { const tokenFetch = async (url, options) => {
@@ -28,7 +31,7 @@ const TokenProvider = props => {
let bearer = accessToken; let bearer = accessToken;
//if expired (10 minutes, normally) //if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now(); const expired = new Date(jwtDecode(accessToken).exp) < Date.now() / 1000;
if (expired) { if (expired) {
//BUGFIX: if logging out, just skip over the refresh token //BUGFIX: if logging out, just skip over the refresh token
@@ -36,30 +39,26 @@ const TokenProvider = props => {
return fetch(url, { return fetch(url, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Authorization': `Bearer ${bearer}` 'Authorization': `Bearer ${bearer}`
}, },
body: JSON.stringify({ credentials: 'include'
token: refreshToken
})
}); });
} }
//ping the auth server for a new token //ping the auth server for a new access token
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, { const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Authorization': `Bearer ${bearer}`
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ credentials: 'include'
token: refreshToken
})
}); });
//any errors, throw them //any errors, throw them
if (!response.ok) { if (!response.ok) {
if (response.status == 403) {
forceLogout();
}
throw `${response.status}: ${await response.text()}`; throw `${response.status}: ${await response.text()}`;
} }
@@ -67,7 +66,6 @@ const TokenProvider = props => {
const newAuth = await response.json(); const newAuth = await response.json();
setAccessToken(newAuth.accessToken); setAccessToken(newAuth.accessToken);
setRefreshToken(newAuth.refreshToken);
bearer = newAuth.accessToken; bearer = newAuth.accessToken;
} }
@@ -77,30 +75,34 @@ const TokenProvider = props => {
headers: { headers: {
...(options || { headers: {} }).headers, ...(options || { headers: {} }).headers,
'Authorization': `Bearer ${bearer}` 'Authorization': `Bearer ${bearer}`
} },
credentials: 'include'
}); });
}; };
//access the refreshed token via callback //access the refreshed token via callback
const tokenCallback = async (cb) => { const tokenCallback = async (cb) => {
//use this?
let bearer = accessToken;
//if expired (10 minutes, normally) //if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now(); const expired = new Date(jwtDecode(accessToken).exp) < Date.now() / 1000;
if (expired) { if (expired) {
//ping the auth server for a new token //ping the auth server for a new token
const response = await fetch(`${process.env.AUTH_URI}/auth/token`, { const response = await fetch(`${process.env.AUTH_URI}/auth/token`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Authorization': `Bearer ${bearer}`
'Access-Control-Allow-Origin': '*'
}, },
body: JSON.stringify({ credentials: 'include'
token: refreshToken
})
}); });
//any errors, throw them //any errors, throw them
if (!response.ok) { if (!response.ok) {
if (response.status == 403) {
forceLogout();
}
throw `${response.status}: ${await response.text()}`; throw `${response.status}: ${await response.text()}`;
} }
@@ -108,7 +110,6 @@ const TokenProvider = props => {
const newAuth = await response.json(); const newAuth = await response.json();
setAccessToken(newAuth.accessToken); setAccessToken(newAuth.accessToken);
setRefreshToken(newAuth.refreshToken);
//finally //finally
return cb(newAuth.accessToken); return cb(newAuth.accessToken);
@@ -118,7 +119,7 @@ const TokenProvider = props => {
}; };
return ( return (
<TokenContext.Provider value={{ accessToken, refreshToken, setAccessToken, setRefreshToken, tokenFetch, tokenCallback, getPayload: () => decode(accessToken) }}> <TokenContext.Provider value={{ accessToken, setAccessToken, tokenFetch, tokenCallback, getPayload: () => jwtDecode(accessToken) }}>
{props.children} {props.children}
</TokenContext.Provider> </TokenContext.Provider>
) )
+10
View File
@@ -77,6 +77,16 @@
display: flex; display: flex;
} }
.chat .timestamp {
max-width: 44px;
}
.chat .inner {
flex: 1 !important;
display: inline-block !important;
flex-direction: row !important;
}
.chat .username { .chat .username {
font-weight: bold; font-weight: bold;
} }
+1 -1
View File
@@ -22,6 +22,6 @@
<meta property="og:description" content="" /> <meta property="og:description" content="" />
</head> </head>
<body> <body>
<div id = "root"></div> <div id="root"></div>
</body> </body>
</html> </html>
+153 -37
View File
@@ -36,7 +36,7 @@ const question = (prompt, def = null) => {
Currently, all microservices are mandatory; you'll have to mess with the result Currently, all microservices are mandatory; you'll have to mess with the result
and the source code if you wish to be more selective. Microservices currently and the source code if you wish to be more selective. Microservices currently
impelented are: implemented are:
* auth-server * auth-server
* news-server * news-server
@@ -46,24 +46,89 @@ See https://github.com/krgamestudios/MERN-template/wiki for help.
` `
); );
// //determine local computer address for mac user vs everyone else
// let macUser = '';
// while (macUser.toLowerCase() !== 'yes' && macUser.toLowerCase() !== 'no') {
// macUser = await question('Will the MERN-Template be running locally on a MacOS system? (yes or no, this only alters startup.sql)', '');
// }
// const localAddress = macUser === 'yes' ? 'localhost' : '%';
const localAddress = '%';
//project configuration //project configuration
const projectName = await question('Project Name', 'template'); const projectName = await question('Project Name', 'template');
const projectWebAddress = await question('Project Web Address', 'example.com'); const projectWebAddress = await question('Project Web Address', 'example.com');
const corsWebOrigin = await question('CORS Web Origin', `https://${projectWebAddress}`);
let projectDBLocation = '';
while (typeof projectDBLocation != 'string' || /^[le]/i.test(projectDBLocation[0]) == false) {
projectDBLocation = await question('Project [l]ocal or [e]xternal database?');
}
let projectDBHost = '';
let projectDBPort = '';
if (/^[l]/i.test(projectDBLocation[0])) {
projectDBHost = 'database';
projectDBPort = '3306';
}
else {
projectDBHost = await question('Project DB Host');
projectDBPort = await question('Project DB Port', '3306');
}
const projectDBUser = await question('Project DB Username', projectName); const projectDBUser = await question('Project DB Username', projectName);
const projectDBPass = await question('Project DB Password', 'pikachu'); const projectDBPass = await question('Project DB Password', 'pikachu');
//news configuration //news configuration
const newsName = await question('News Name', 'news'); const newsName = await question('News Name', 'news');
const newsWebAddress = await question('News Web Address', `${newsName}.${projectWebAddress}`); const newsWebAddress = await question('News Web Address', `${newsName}.${projectWebAddress}`);
const newsDBUser = await question('News DB Username', newsName);
let newsDBLocation = '';
while (typeof newsDBLocation != 'string' || /^[le]/i.test(newsDBLocation[0]) == false) {
newsDBLocation = await question('News [l]ocal or [e]xternal database?');
}
let newsDBHost = '';
let newsDBPort = '';
if (/^[l]/i.test(newsDBLocation[0])) {
newsDBHost = 'database';
newsDBPort = '3306';
}
else {
newsDBHost = await question('News DB Host');
newsDBPort = await question('News DB Port', '3306');
}
const newsDBUser = await question('News DB Username', newsName);
const newsDBPass = await question('News DB Password', 'venusaur'); const newsDBPass = await question('News DB Password', 'venusaur');
//auth configuration //auth configuration
const authName = await question('Auth Name', 'auth'); const authName = await question('Auth Name', 'auth');
const authWebAddress = await question('Auth Web Address', `${authName}.${projectWebAddress}`); const authWebAddress = await question('Auth Web Address', `${authName}.${projectWebAddress}`);
const authPostValidationHookArray = await question('Auth Post Validation Hook Array', '');
const authResetAddress = await question('Auth Reset Addr', `${projectWebAddress}/reset`); const authResetAddress = await question('Auth Reset Addr', `${projectWebAddress}/reset`);
const authDBUser = await question('Auth DB Username', authName);
let authDBLocation = '';
while (typeof authDBLocation != 'string' || /^[le]/i.test(authDBLocation[0]) == false) {
authDBLocation = await question('Auth [l]ocal or [e]xternal database?');
}
let authDBHost = '';
let authDBPort = '';
if (/^[l]/i.test(authDBLocation[0])) {
authDBHost = 'database';
authDBPort = '3306';
}
else {
authDBHost = await question('Auth DB Host');
authDBPort = await question('Auth DB Port', '3306');
}
const authDBUser = await question('Auth DB Username', authName);
const authDBPass = await question('Auth DB Password', 'charizard'); const authDBPass = await question('Auth DB Password', 'charizard');
const emailSMTP = await question('Email SMTP', 'smtp.example.com'); const emailSMTP = await question('Email SMTP', 'smtp.example.com');
@@ -74,7 +139,25 @@ See https://github.com/krgamestudios/MERN-template/wiki for help.
//chat goes here //chat goes here
const chatName = await question('Chat Name', 'chat'); const chatName = await question('Chat Name', 'chat');
const chatWebAddress = await question('Chat Web Address', `${chatName}.${projectWebAddress}`); const chatWebAddress = await question('Chat Web Address', `${chatName}.${projectWebAddress}`);
const chatDBUser = await question('Chat DB Username', chatName);
let chatDBLocation = '';
while (typeof chatDBLocation != 'string' || /^[le]/i.test(chatDBLocation[0]) == false) {
chatDBLocation = await question('Chat [l]ocal or [e]xternal database?');
}
let chatDBHost = '';
let chatDBPort = '';
if (/^[l]/i.test(chatDBLocation[0])) {
chatDBHost = 'database';
chatDBPort = '3306';
}
else {
chatDBHost = await question('Chat DB Host');
chatDBPort = await question('Chat DB Port', '3306');
}
const chatDBUser = await question('Chat DB Username', chatName);
const chatDBPass = await question('Chat DB Password', 'blastoise'); const chatDBPass = await question('Chat DB Password', 'blastoise');
//database configuration //database configuration
@@ -90,32 +173,34 @@ See https://github.com/krgamestudios/MERN-template/wiki for help.
//MUST be at least 8 chars //MUST be at least 8 chars
let tmpPass = ''; let tmpPass = '';
let tmpHost = '';
while (defaultUser && tmpPass.length < 8) { while (defaultUser && tmpPass.length < 8) {
console.log('--All passwords must be at least 8 characters long--'); console.log('--All passwords must be at least 8 characters long--');
tmpPass = await question('Default Admin Pass', ''); tmpPass = await question('Default Admin Pass', '');
tmpHost = await question('Default Admin Host', '');
} }
const defaultPass = tmpPass; const defaultPass = tmpPass;
const defaultHost = tmpHost;
if (defaultUser) { if (defaultUser) {
console.log(`Default user email will be: ${defaultUser}@${authWebAddress}`); console.log(`Default user email will be: ${defaultUser}@${defaultHost}`);
} }
//traefic configuration //traefic configuration
const supportEmail = await question('Support Email', emailUser); const supportEmail = await question('Support Email', emailUser);
//misc. configuration //misc. configuration
const projectPort = 3000; const projectPort = '3000';
const newsPort = 3100; const newsPort = '3100';
const authPort = 3200; const authPort = '3200';
const chatPort = 3300; const chatPort = '3300';
const ymlfile = ` const ymlfile = `
version: "3.6"
services: services:
${projectName}: ${projectName}:
build: . build: .
ports: ports:
- "${projectPort}" - ${projectPort}
labels: labels:
- traefik.enable=true - traefik.enable=true
- traefik.http.routers.${projectName}router.rule=Host(\`${projectWebAddress}\`) - traefik.http.routers.${projectName}router.rule=Host(\`${projectWebAddress}\`)
@@ -124,8 +209,10 @@ services:
- traefik.http.routers.${projectName}router.service=${projectName}service@docker - traefik.http.routers.${projectName}router.service=${projectName}service@docker
- traefik.http.services.${projectName}service.loadbalancer.server.port=${projectPort} - traefik.http.services.${projectName}service.loadbalancer.server.port=${projectPort}
environment: environment:
- WEB_ORIGIN=${corsWebOrigin}
- WEB_PORT=${projectPort} - WEB_PORT=${projectPort}
- DB_HOSTNAME=database - DB_HOSTNAME=${projectDBHost}
- DB_PORTNAME=${projectDBPort}
- DB_DATABASE=${projectName} - DB_DATABASE=${projectName}
- DB_USERNAME=${projectDBUser} - DB_USERNAME=${projectDBUser}
- DB_PASSWORD=${projectDBPass} - DB_PASSWORD=${projectDBPass}
@@ -134,10 +221,13 @@ services:
- AUTH_URI=https://${authWebAddress} - AUTH_URI=https://${authWebAddress}
- CHAT_URI=https://${chatWebAddress} - CHAT_URI=https://${chatWebAddress}
- SECRET_ACCESS=${accessToken} - SECRET_ACCESS=${accessToken}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
depends_on: depends_on:${ projectDBHost != 'database' ? '' : `
- database - database`}
- traefik - traefik
${newsName}: ${newsName}:
@@ -152,18 +242,23 @@ services:
- traefik.http.routers.${newsName}router.service=${newsName}service@docker - traefik.http.routers.${newsName}router.service=${newsName}service@docker
- traefik.http.services.${newsName}service.loadbalancer.server.port=${newsPort} - traefik.http.services.${newsName}service.loadbalancer.server.port=${newsPort}
environment: environment:
- WEB_ORIGIN=${corsWebOrigin}
- WEB_PORT=${newsPort} - WEB_PORT=${newsPort}
- DB_HOSTNAME=database - DB_HOSTNAME=${newsDBHost}
- DB_PORTNAME=${newsDBPort}
- DB_DATABASE=${newsName} - DB_DATABASE=${newsName}
- DB_USERNAME=${newsDBUser} - DB_USERNAME=${newsDBUser}
- DB_PASSWORD=${newsDBPass} - DB_PASSWORD=${newsDBPass}
- DB_TIMEZONE=${dbTimeZone} - DB_TIMEZONE=${dbTimeZone}
- QUERY_LIMIT=10 - PAGE_SIZE=10
- SECRET_ACCESS=${accessToken} - SECRET_ACCESS=${accessToken}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
depends_on: depends_on:${ newsDBHost != 'database' ? '' : `
- database - database`}
- traefik - traefik
${authName}: ${authName}:
@@ -178,11 +273,14 @@ services:
- traefik.http.routers.${authName}router.service=${authName}service@docker - traefik.http.routers.${authName}router.service=${authName}service@docker
- traefik.http.services.${authName}service.loadbalancer.server.port=${authPort} - traefik.http.services.${authName}service.loadbalancer.server.port=${authPort}
environment: environment:
- WEB_ORIGIN=${corsWebOrigin}
- WEB_PROTOCOL=https - WEB_PROTOCOL=https
- WEB_ADDRESS=${authWebAddress} - WEB_ADDRESS=${authWebAddress}
- HOOK_POST_VALIDATION_ARRAY=${authPostValidationHookArray}
- WEB_RESET_ADDRESS=${authResetAddress} - WEB_RESET_ADDRESS=${authResetAddress}
- WEB_PORT=${authPort} - WEB_PORT=${authPort}
- DB_HOSTNAME=database - DB_HOSTNAME=${authDBHost}
- DB_PORTNAME=${authDBPort}
- DB_DATABASE=${authName} - DB_DATABASE=${authName}
- DB_USERNAME=${authDBUser} - DB_USERNAME=${authDBUser}
- DB_PASSWORD=${authDBPass} - DB_PASSWORD=${authDBPass}
@@ -192,13 +290,17 @@ services:
- MAIL_PASSWORD=${emailPass} - MAIL_PASSWORD=${emailPass}
- MAIL_PHYSICAL=${emailPhysical} - MAIL_PHYSICAL=${emailPhysical}
- ADMIN_DEFAULT_USERNAME=${defaultUser} - ADMIN_DEFAULT_USERNAME=${defaultUser}
- ADMIN_DEFAULT_HOSTNAME=${defaultHost}
- ADMIN_DEFAULT_PASSWORD=${defaultPass} - ADMIN_DEFAULT_PASSWORD=${defaultPass}
- SECRET_ACCESS=${accessToken} - SECRET_ACCESS=${accessToken}
- SECRET_REFRESH=${refreshToken} - SECRET_REFRESH=${refreshToken}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
depends_on: depends_on:${ authDBHost != 'database' ? '' : `
- database - database`}
- traefik - traefik
${chatName}: ${chatName}:
@@ -213,19 +315,25 @@ services:
- traefik.http.routers.${chatName}router.service=${chatName}service@docker - traefik.http.routers.${chatName}router.service=${chatName}service@docker
- traefik.http.services.${chatName}service.loadbalancer.server.port=${chatPort} - traefik.http.services.${chatName}service.loadbalancer.server.port=${chatPort}
environment: environment:
- WEB_ORIGIN=${corsWebOrigin}
- WEB_PORT=${chatPort} - WEB_PORT=${chatPort}
- DB_HOSTNAME=database - DB_HOSTNAME=${chatDBHost}
- DB_PORTNAME=${chatDBPort}
- DB_DATABASE=${chatName} - DB_DATABASE=${chatName}
- DB_USERNAME=${chatDBUser} - DB_USERNAME=${chatDBUser}
- DB_PASSWORD=${chatDBPass} - DB_PASSWORD=${chatDBPass}
- DB_TIMEZONE=${dbTimeZone} - DB_TIMEZONE=${dbTimeZone}
- SECRET_ACCESS=${accessToken} - SECRET_ACCESS=${accessToken}
volumes:
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
depends_on: depends_on:${ chatDBHost != 'database' ? '' : `
- database - database`}
- traefik - traefik
${ [projectDBHost, newsDBHost, authDBHost, chatDBHost].some(x => x == "database") == false ? '' : `
database: database:
image: mariadb image: mariadb
restart: always restart: always
@@ -234,28 +342,35 @@ services:
volumes: volumes:
- ./mysql:/var/lib/mysql - ./mysql:/var/lib/mysql
- ./startup.sql:/docker-entrypoint-initdb.d/startup.sql:ro - ./startup.sql:/docker-entrypoint-initdb.d/startup.sql:ro
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
`}
traefik: traefik:
image: traefik:v2.4 image: traefik:latest
container_name: traefik container_name: traefik
command: command:
- --log.level=ERROR - --log.level=ERROR
- --api.insecure=false - --api.insecure=false
- --providers.docker=true - --providers.docker=true
- --providers.docker.exposedbydefault=false - --providers.docker.exposedbydefault=false
- --entrypoints.web.address=:80
- --entrypoints.web.http.redirections.entryPoint.to=websecure
- --entrypoints.web.http.redirections.entryPoint.scheme=https
- --entrypoints.web.http.redirections.entrypoint.permanent=true
- --entrypoints.websecure.address=:443 - --entrypoints.websecure.address=:443
- --certificatesresolvers.myresolver.acme.tlschallenge=true - --certificatesresolvers.myresolver.acme.tlschallenge=true
- --certificatesresolvers.myresolver.acme.email=${supportEmail} - --certificatesresolvers.myresolver.acme.email=${supportEmail}
- --certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json - --certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json
- traefik.docker.network=app-network
ports: ports:
- 80:80 - 80:80
- 443:443 - 443:443
volumes: volumes:
- ./letsencrypt:/letsencrypt - ./letsencrypt:/letsencrypt
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
networks: networks:
- app-network - app-network
@@ -265,10 +380,10 @@ networks:
`; `;
const dockerfile = ` const dockerfile = `
FROM node:15 FROM node:22-bookworm-slim
WORKDIR "/app" WORKDIR "/app"
COPY . /app COPY . /app
RUN mkdir /app/public RUN mkdir -p /app/public
RUN chown node:node /app/public RUN chown node:node /app/public
RUN npm install --production RUN npm install --production
EXPOSE ${projectPort} EXPOSE ${projectPort}
@@ -279,24 +394,25 @@ CMD ["sleep 10 && npm start"]
const sqlfile = ` const sqlfile = `
CREATE DATABASE IF NOT EXISTS ${projectName}; CREATE DATABASE IF NOT EXISTS ${projectName};
CREATE USER IF NOT EXISTS '${projectDBUser}'@'%' IDENTIFIED BY '${projectDBPass}'; CREATE USER IF NOT EXISTS '${projectDBUser}'@'${localAddress}' IDENTIFIED BY '${projectDBPass}';
GRANT ALL PRIVILEGES ON ${projectName}.* TO '${projectDBUser}'@'%'; GRANT ALL PRIVILEGES ON ${projectName}.* TO '${projectDBUser}'@'${localAddress}';
CREATE DATABASE IF NOT EXISTS ${newsName}; CREATE DATABASE IF NOT EXISTS ${newsName};
CREATE USER IF NOT EXISTS '${newsDBUser}'@'%' IDENTIFIED BY '${newsDBPass}'; CREATE USER IF NOT EXISTS '${newsDBUser}'@'${localAddress}' IDENTIFIED BY '${newsDBPass}';
GRANT ALL PRIVILEGES ON ${newsName}.* TO '${newsDBUser}'@'%'; GRANT ALL PRIVILEGES ON ${newsName}.* TO '${newsDBUser}'@'${localAddress}';
CREATE DATABASE IF NOT EXISTS ${authName}; CREATE DATABASE IF NOT EXISTS ${authName};
CREATE USER IF NOT EXISTS '${authDBUser}'@'%' IDENTIFIED BY '${authDBPass}'; CREATE USER IF NOT EXISTS '${authDBUser}'@'${localAddress}' IDENTIFIED BY '${authDBPass}';
GRANT ALL PRIVILEGES ON ${authName}.* TO '${authDBUser}'@'%'; GRANT ALL PRIVILEGES ON ${authName}.* TO '${authDBUser}'@'${localAddress}';
CREATE DATABASE IF NOT EXISTS ${chatName}; CREATE DATABASE IF NOT EXISTS ${chatName};
CREATE USER IF NOT EXISTS '${chatDBUser}'@'%' IDENTIFIED BY '${chatDBPass}'; CREATE USER IF NOT EXISTS '${chatDBUser}'@'${localAddress}' IDENTIFIED BY '${chatDBPass}';
GRANT ALL PRIVILEGES ON ${chatName}.* TO '${chatDBUser}'@'%'; GRANT ALL PRIVILEGES ON ${chatName}.* TO '${chatDBUser}'@'${localAddress}';
FLUSH PRIVILEGES; FLUSH PRIVILEGES;
`; `;
fs.writeFileSync('docker-compose.yml', ymlfile); fs.writeFileSync('docker-compose.yml', ymlfile);
fs.writeFileSync('Dockerfile', dockerfile); fs.writeFileSync('Dockerfile', dockerfile);
fs.writeFileSync('startup.sql', sqlfile); fs.writeFileSync('startup.sql', sqlfile);
+4799 -16488
View File
File diff suppressed because it is too large Load Diff
+32 -37
View File
@@ -1,6 +1,6 @@
{ {
"name": "mern-template", "name": "mern-template",
"version": "1.0.5", "version": "1.5.1",
"description": "A website template using the MERN stack.", "description": "A website template using the MERN stack.",
"main": "server/server.js", "main": "server/server.js",
"scripts": { "scripts": {
@@ -8,9 +8,9 @@
"build": "npm run build:server && npm run build:client", "build": "npm run build:server && npm run build:client",
"build:server": "exit 0", "build:server": "exit 0",
"build:client": "webpack --env=production --config webpack.config.js", "build:client": "webpack --env=production --config webpack.config.js",
"dev": "concurrently npm:watch:server npm:watch:client", "dev": "concurrently npm:dev:server npm:dev:client",
"watch:server": "nodemon ./* --ext js,jsx,json --ignore 'node_modules/*'", "dev:server": "nodemon --ext js,jsx,json --ignore 'node_modules/*'",
"watch:client": "webpack serve --env=development --config webpack.config.js", "dev:client": "webpack serve --config webpack.config.js",
"analyze": "webpack --env=production --env=analyze --config webpack.config.js" "analyze": "webpack --env=production --env=analyze --config webpack.config.js"
}, },
"repository": { "repository": {
@@ -18,45 +18,40 @@
"url": "git+https://github.com/KRGameStudios/MERN-template.git" "url": "git+https://github.com/KRGameStudios/MERN-template.git"
}, },
"author": "Kayne Ruse", "author": "Kayne Ruse",
"license": "ISC", "license": "Zlib",
"bugs": { "bugs": {
"url": "https://github.com/KRGameStudios/MERN-template/issues" "url": "https://github.com/KRGameStudios/MERN-template/issues"
}, },
"homepage": "https://github.com/KRGameStudios/MERN-template#readme", "homepage": "https://github.com/KRGameStudios/MERN-template#readme",
"dependencies": { "dependencies": {
"@babel/core": "^7.14.8", "@babel/core": "^7.28.0",
"@babel/preset-env": "^7.14.8", "@babel/preset-env": "^7.28.0",
"@babel/preset-react": "^7.14.5", "@babel/preset-react": "^7.27.1",
"@loadable/component": "^5.15.0", "babel-loader": "^10.0.0",
"babel-loader": "^8.2.2", "clean-webpack-plugin": "^4.0.0",
"clean-webpack-plugin": "^3.0.0", "compression-webpack-plugin": "^11.1.0",
"compression-webpack-plugin": "^8.0.1", "concurrently": "^9.2.0",
"concurrently": "^6.2.0", "css-loader": "^7.1.2",
"css-loader": "^6.2.0", "dateformat": "^5.0.3",
"dateformat": "^4.5.1", "dotenv": "^17.2.1",
"dotenv": "^10.0.0", "express": "^5.1.0",
"express": "^4.17.1", "html-webpack-plugin": "^5.6.3",
"html-webpack-plugin": "^5.3.2", "jwt-decode": "^4.0.0",
"jwt-decode": "^3.1.2", "mariadb": "^3.4.5",
"mariadb": "^2.5.4", "react": "^19.1.0",
"query-string": "^7.0.1", "react-dom": "^19.1.0",
"raw-loader": "^4.0.2", "react-router": "^7.7.1",
"react": "^17.0.2", "react-router-dom": "^7.7.1",
"react-dom": "^17.0.2", "react-select": "^5.10.2",
"react-dropdown-select": "^4.7.4", "sequelize": "^6.37.7",
"react-markdown": "^6.0.2", "socket.io-client": "^4.8.1",
"react-router": "^5.2.0", "style-loader": "^4.0.0",
"react-router-dom": "^5.2.0", "webpack": "^5.100.2",
"rehype-raw": "^5.1.0", "webpack-bundle-analyzer": "^4.10.2",
"sequelize": "^6.6.5", "webpack-cli": "^6.0.1"
"socket.io-client": "^4.1.3",
"style-loader": "^3.2.1",
"webpack": "^5.46.0",
"webpack-bundle-analyzer": "^4.4.2",
"webpack-cli": "^4.7.2"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.12", "nodemon": "^3.1.10",
"webpack-dev-server": "^3.11.2" "webpack-dev-server": "^5.2.2"
} }
} }
+2 -3
View File
@@ -2,11 +2,10 @@ const Sequelize = require('sequelize');
const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, { const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
host: process.env.DB_HOSTNAME, host: process.env.DB_HOSTNAME,
port: process.env.DB_PORTNAME,
dialect: 'mariadb', dialect: 'mariadb',
timezone: process.env.DB_TIMEZONE, timezone: process.env.DB_TIMEZONE,
logging: process.env.DB_LOGGING ? console.log : false logging: process.env.DB_LOGGING ? console.log : false
}); });
sequelize.sync(); module.exports = sequelize;
module.exports = sequelize;
+4 -3
View File
@@ -13,14 +13,14 @@ const server = require('http').Server(app);
app.use(express.json()); app.use(express.json());
//handle compressed files (middleware) //handle compressed files (middleware)
app.get('*.js', (req, res, next) => { app.get('/{*any}.js', (req, res, next) => {
req.url = req.url + '.gz'; req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip'); res.set('Content-Encoding', 'gzip');
res.set('Content-Type', 'text/javascript'); res.set('Content-Type', 'text/javascript');
next(); next();
}); });
app.get('*.css', (req, res, next) => { app.get('/{*any}.css', (req, res, next) => {
req.url = req.url + '.gz'; req.url = req.url + '.gz';
res.set('Content-Encoding', 'gzip'); res.set('Content-Encoding', 'gzip');
res.set('Content-Type', 'text/css'); res.set('Content-Type', 'text/css');
@@ -34,7 +34,7 @@ const database = require('./database');
app.use('/', express.static(path.resolve(__dirname, '..', 'public'))); app.use('/', express.static(path.resolve(__dirname, '..', 'public')));
//fallback to the index file //fallback to the index file
app.get('*', (req, res) => { app.get('/{*any}', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'public' , 'index.html')); res.sendFile(path.resolve(__dirname, '..', 'public' , 'index.html'));
}); });
@@ -42,4 +42,5 @@ app.get('*', (req, res) => {
server.listen(process.env.WEB_PORT || 3000, async (err) => { server.listen(process.env.WEB_PORT || 3000, async (err) => {
await database.sync(); await database.sync();
console.log(`listening to localhost:${process.env.WEB_PORT || 3000}`); console.log(`listening to localhost:${process.env.WEB_PORT || 3000}`);
console.log(`database located at ${process.env.DB_HOSTNAME || '<default>'}:${process.env.DB_PORTNAME || '<default>'}`);
}); });
-10
View File
@@ -1,10 +0,0 @@
#This file only needs to be run once, during initial development setup
#This file isnt needed for actual deployment
#Create the development database
CREATE DATABASE IF NOT EXISTS template;
USE template;
#Create the database user
CREATE USER IF NOT EXISTS 'template'@'%' IDENTIFIED BY 'pikachu';
GRANT ALL PRIVILEGES ON template.* TO 'template'@'%';
+5
View File
@@ -0,0 +1,5 @@
#use this while debugging
CREATE DATABASE template;
CREATE USER 'template'@'%' IDENTIFIED BY 'pikachu';
GRANT ALL PRIVILEGES ON template.* TO 'template'@'%';
+29 -47
View File
@@ -19,7 +19,7 @@ module.exports = ({ production, analyze }) => {
filename: '[name].[chunkhash].js', filename: '[name].[chunkhash].js',
sourceMapFilename: '[name].[chunkhash].js.map' sourceMapFilename: '[name].[chunkhash].js.map'
}, },
devtool: production ? 'source-map' : 'eval-source-map', devtool: production ? false : 'eval-source-map',
resolve: { resolve: {
extensions: ['.js', '.jsx'] extensions: ['.js', '.jsx']
}, },
@@ -33,7 +33,6 @@ module.exports = ({ production, analyze }) => {
loader: 'babel-loader', loader: 'babel-loader',
options: { options: {
presets: ['@babel/preset-env', '@babel/preset-react'], presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: ['@babel/plugin-syntax-dynamic-import']
} }
} }
] ]
@@ -42,23 +41,15 @@ module.exports = ({ production, analyze }) => {
test: /\.(css)$/, test: /\.(css)$/,
use: ['style-loader', 'css-loader'] use: ['style-loader', 'css-loader']
}, },
{
test: /\.(md)$/,
use: [
{
loader: 'raw-loader'
},
],
},
] ]
}, },
plugins: [ plugins: [
new DefinePlugin({ new DefinePlugin({
'process.env': { 'process.env': {
'PRODUCTION': production, 'PRODUCTION': production,
'NEWS_URI': production ? `"${process.env.NEWS_URI}"` : '"https://dev-news.krgamestudios.com"', 'NEWS_URI': production ? `"${process.env.NEWS_URI}"` : '"http://localhost:3100"',
'AUTH_URI': production ? `"${process.env.AUTH_URI}"` : '"https://dev-auth.krgamestudios.com"', 'AUTH_URI': production ? `"${process.env.AUTH_URI}"` : '"http://localhost:3200"',
'CHAT_URI': production ? `"${process.env.CHAT_URI}"` : '"https://dev-chat.krgamestudios.com"', 'CHAT_URI': production ? `"${process.env.CHAT_URI}"` : '"http://localhost:3300"',
} }
}), }),
new CleanWebpackPlugin({ new CleanWebpackPlugin({
@@ -83,41 +74,32 @@ module.exports = ({ production, analyze }) => {
}) })
], ],
devServer: { devServer: {
contentBase: path.resolve(__dirname, 'public'),
compress: true,
port: 3001,
proxy: {
'/api/': 'http://localhost:3000/'
},
overlay: {
errors: true
},
stats: {
colors: true,
hash: false,
version: false,
timings: false,
assets: false,
chunks: false,
modules: false,
reasons: false,
children: false,
source: false,
errors: true,
errorDetails: false,
warnings: true,
publicPath: false
},
host: '0.0.0.0',
disableHostCheck: true,
clientLogLevel: 'silent',
historyApiFallback: true,
hot: true, hot: true,
injectHot: true host: 'localhost',
}, port: 3001,
watchOptions: { client: {
ignored: /(node_modules)/ overlay: {
errors: true,
warnings: true,
},
},
watchFiles: {
options: {
ignored: ['node_modules/**']
}
},
proxy: [
{
context: ['/api'],
target: 'http://localhost:3000',
}
],
static: '/public',
historyApiFallback: true
} }
} }
}; };