Compare commits

...

54 Commits

Author SHA1 Message Date
Kayne Ruse 96e580e56a Bumped version number 2022-08-01 10:37:51 +01:00
Kayne Ruse ca12844268 Updated dependencies 2022-08-01 10:35:58 +01:00
Kayne Ruse 76fa0649f2 Tweak cors handling 2022-07-26 13:39:04 +01:00
Kayne Ruse 3b4ac12582 Updated dependencies 2022-07-23 11:47:35 +01:00
Kayne Ruse eb55709be5 Bumped patch version 2022-06-10 17:23:41 +01:00
Kayne Ruse 446b49c9a0 Updated dependencies 2022-06-10 17:09:19 +01:00
Kayne Ruse 36c309a69c Merge remote-tracking branch 'refs/remotes/origin/main' 2022-05-30 06:46:40 +01:00
Kayne Ruse 3f55ad71cf Updated dependencies 2022-05-30 06:46:08 +01:00
Kayne Ruse f8ec31ff7e Added FUNDING.yml 2022-02-13 07:49:29 +11:00
Kayne Ruse 739311928f Library updates 2022-01-20 13:38:38 +11:00
Kayne Ruse 78cda0fe50 Enabled HTML embedding 2022-01-06 11:31:11 +00:00
Kayne Ruse 7d40005e7d Bumped version number 2022-01-02 18:12:31 +00:00
Kayne Ruse 855de182ea Mods can now add and edit the news feed 2022-01-02 18:11:43 +00:00
Kayne Ruse a96e7d9344 Updated README.md 2021-12-30 13:52:13 +00:00
Kayne Ruse 2e2799f2d3 Moved client-side markdown rendering to this server 2021-12-30 13:22:31 +00:00
Kayne Ruse da0c4bbd05 Cleaned up tools and tests 2021-12-23 13:57:52 +00:00
Kayne Ruse 6e75012376 Updated README.md 2021-12-21 19:37:38 +00:00
Kayne Ruse 5488d7a8d7 Preparing for Egg Trainer merge 2021-11-18 14:58:29 +00:00
Kayne Ruse 3bb0b2aa29 Fixed revisions table losing originalIndex when article was deleted
I've also included a migration file in the tools directory
2021-11-17 06:16:33 +00:00
Kayne Ruse c30cf80fc6 Bumped node to version 16 LTS 2021-11-17 04:42:48 +00:00
Kayne Ruse 62afef402f Updated package-lock.json 2021-11-15 22:39:21 +00:00
Kayne Ruse db61357a0f Updated documentation 2021-08-21 22:45:01 +01:00
Kayne Ruse fd1ba06b45 HOTFIX: Missing data would crash the site 2021-07-25 10:35:13 +01:00
Kayne Ruse 1b9e35539e Update package.json 2021-07-23 20:40:36 +10:00
Kayne Ruse 19a4051159 Updated packages 2021-07-23 19:23:17 +10:00
Kayne Ruse 6fee9090e7 Merged private changes 2021-07-23 19:21:21 +10:00
Kayne Ruse 5c9ee58f41 Updated .dockerignore 2021-07-23 19:12:21 +10:00
Kayne Ruse f56f1e859b Updated packages 2021-07-15 09:24:15 +10:00
Kayne Ruse 8504017cf7 Updated packages 2021-04-28 21:28:29 +10:00
Kayne Ruse 5d61cf3cdc Updated modules 2021-04-20 18:49:53 +10:00
Kayne Ruse 5d721ddea6 Updated .dockerignore 2021-04-16 16:24:58 +10:00
Kayne Ruse 733927966a Added .dockerignore 2021-04-16 13:24:03 +10:00
Kayne Ruse c38f700e93 Tweaked package.json 2021-04-10 04:59:03 +10:00
Kayne Ruse f59fc2e8e0 Tweaked .envdev 2021-04-07 02:44:13 +10:00
Kayne Ruse 70712b9a87 Ripped out unneeded stuff 2021-04-07 02:00:05 +10:00
Kayne Ruse 4ff507b0fa Funky config stuff gives me a headache 2021-04-03 03:26:36 +11:00
Kayne Ruse 7ebced9304 Tweaked Dockerfile 2021-04-03 02:34:40 +11:00
Kayne Ruse 028bcc99dd Tweaked Dockerfile 2021-04-03 02:11:02 +11:00
Kayne Ruse 74869993b0 Formatting errors 2021-04-03 01:59:02 +11:00
Kayne Ruse bac87e9c33 Working on multiplatform things 2021-04-03 01:41:44 +11:00
Kayne Ruse afa35939fa Added docker publishing 2021-04-03 01:05:41 +11:00
Kayne Ruse 1c32e42b47 Updated admin and mod flag system 2021-03-24 08:22:18 +11:00
Kayne Ruse c72c933c0b Updated libraries 2021-03-24 01:52:44 +11:00
Kayne Ruse 3c7add4807 Each microservice has received a tweak to .envdev, read more
This should make it easier to set time zones and enable database logging.

Related to krgamestudios/MERN-template#16
2021-03-22 16:42:45 +11:00
Kayne Ruse 3d73e6d612 Updated README.md 2021-03-14 04:33:49 +11:00
Kayne Ruse da62d64727 Added a nifty flag for debugging 2021-03-11 10:06:04 +11:00
Kayne Ruse 7de1083fdd Finally playing nice together 2021-03-07 15:34:35 +11:00
Kayne Ruse 1f4eae697d Irritating 2021-03-07 14:45:26 +11:00
Kayne Ruse 1b3a247d9d Oh, come on 2021-03-07 14:21:19 +11:00
Kayne Ruse 2f6a2ad94a Minor name tweak 2021-03-07 14:14:33 +11:00
Kayne Ruse 1a847ab9fe Quick config fix 2021-03-07 14:11:06 +11:00
Kayne Ruse 67a1c744ae Brought into line with JWT protocol
Resolved #2
2021-03-07 13:53:29 +11:00
Kayne Ruse f919af4248 Tweaked forkflow file 2021-03-04 09:39:49 +11:00
Kayne Ruse 4a74bac620 Added a delay to server start 2021-03-04 09:29:59 +11:00
29 changed files with 1544 additions and 2516 deletions
+10
View File
@@ -0,0 +1,10 @@
.git*
tools*
mysql*
letsencrypt*
test*
.env*
.github*
LICENSE*
+13 -3
View File
@@ -1,10 +1,20 @@
WEB_PORT=3100
WEB_ORIGIN=http://localhost:3001
DB_HOSTNAME=database
DB_DATABASE=news
DB_USERNAME=news
DB_PASSWORD=charizard
DB_PASSWORD=venusaur
# Select a "TZ database name" that suits your needs: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
DB_TIMEZONE=Australia/Sydney
QUERY_LIMIT=10
QUERY_KEY=key
# Give this any value to enable database logging (such as "true")
DB_LOGGING=
# Make sure this value matches the system that you connect to
SECRET_ACCESS=access
# Select the default number of articles returned by a GET request
QUERY_LIMIT=10
+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"]
+4 -1
View File
@@ -2,6 +2,9 @@ name: Publish Docker image
on:
release:
types: [ published ]
push:
tags:
- v1.*
jobs:
push_to_registry:
name: Push Docker Image to Docker Hub
@@ -23,7 +26,7 @@ jobs:
docker_image: krgamestudios/news-server
- name: Login to DockerHub
uses: docker/login-action@v1
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
+4 -1
View File
@@ -104,4 +104,7 @@ dist
.tern-port
# Docker generated files and folders
data/
letsencrypt/
mysql/
docker-compose.yml
startup.sql
+3 -12
View File
@@ -1,18 +1,9 @@
FROM node:15
# Change working directory
FROM node:18
WORKDIR "/app"
# Copy package.json and package-lock.json
COPY package*.json ./
# Install npm production packages
RUN npm install --production
COPY . /app
EXPOSE 3100
USER node
ENTRYPOINT ["npm", "start"]
ENTRYPOINT ["bash", "-c"]
CMD ["sleep 10 && npm start"]
+68 -38
View File
@@ -2,30 +2,53 @@
An API centric news server. Uses Sequelize and mariaDB by default.
This server is available via docker hub at krgamestudios/news-server.
# Setup
This currently runs in docker. It might need to run twice the first time.
There are multiple ways to run this app - it can run on it's own via `npm start` (for production) or `npm run dev` (for development). it can also run inside docker using `docker-compose up --build` - run `node configure-script.js` to generate docker-compose.yml and startup.sql.
To generate an authorization token, use [auth-server](https://github.com/krgamestudios/auth-server). A public-facing development auth-server is available here (tokens are valid for 10 minutes):
```
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "example@example.com",
"password": "helloworld"
}
```
# API
```
//NOTE: GET will return null if a specific article can't be found
//NOTE: GET will return an empty array if a specific article can't be found
//NOTE: you can add a "limit" query parameter to change the default limit
GET /news?limit=10
//get latest news, up to a default limit, or specify the index "id"
###
//DOCS: get latest news, up to a default limit, or specify the index "id"
GET /news/:id
//get the news starting from the beginning, up to a default limit, or specify the index "id"
###
//DOCS: get the news starting from the beginning, up to a default limit, or specify the index "id"
GET /news/archive/:id
//result (if only a single article is specified, returns just that article rather than an array):
//DOCS: result (if only a single article is specified, returns just that article rather than an array):
[
{
"index": index, //absolute index of the result
"title": title, //title of the article
"author": author, //author of the aricle
"body": body, //body of the article
"rendered": rendered //body rendered as HTML
"edits": edits //number of times this article has been edited
"createdAt": createdAt //time created
"updatedAt": updatedAt //time updated
@@ -33,13 +56,21 @@ GET /news/archive/:id
...
]
//get the latest titles, up to a default limit, or specify the index "id"
GET /news/titles/:id
//get the titles starting from the beginning, up to a default limit, or specify the index "id"
GET /news/archive/titles/:id
###
//result (if only a single article is specified, returns just that article rather than an array):
//DOCS: get the latest metadata, up to a default limit, or specify the index "id"
GET /news/metadata/:id
###
//DOCS: get the metadata starting from the beginning, up to a default limit, or specify the index "id"
GET /news/archive/metadata/:id
//DOCS: result (if only a single article is specified, returns just that article rather than an array):
[
{
"index": index, //absolute index of the result
@@ -52,52 +83,51 @@ GET /news/archive/titles/:id
...
]
//send a formatted JSON object, returns new index on success, or error on failure
###
//DOCS: send a formatted JSON object, returns new index on success, or error on failure
POST /news
Authorization: Bearer XXX
//arguments:
{
"key": key //the whitelist key, allows access to the POST routes
"title": title //title of the article
"author": author //author of the article
"body": body //body of the article
}
//result:
//DOCS: result (status 200 on success, otherwise an error status):
{
"ok": ok //true on success, otherwise false
"index": index //new index of the article, or undefined
"error": error //error encountered, or undefined
"index": index //new index of the article
}
//similar to `POST /news`, but allows overwriting an existing article
###
//DOCS: similar to `POST /news`, but allows overwriting an existing article
PATCH /news/:id
Authorization: Bearer XXX
//arguments:
{
"key": key //the whitelist key, allows access to the PATCH routes
"title": title //title of the article
"author": author //author of the article
"body": body //body of the article
"title": title //title of the article, optional
"author": author //author of the article, optional
"body": body //body of the article, optional
}
//result:
{
"ok": ok //true on success, otherwise false
"error": error //error encountered, or undefined
}
//DOCS: result: status 200 on success, otherwise an error status
//remove an article from the news feed
###
//DOCS: remove an article from the news feed
DELETE /news/:id
Authorization: Bearer XXX
//arguments:
{
"key": key //the whitelist key, allows access to the DELETE routes
}
//DOCS: result: status 200 on success, otherwise an error status
//result:
{
"ok": ok //true on success, otherwise false
"error": error //error encountered, or undefined
}
###
```
+137
View File
@@ -0,0 +1,137 @@
//setup
const readline = require('readline');
const fs = require('fs');
const crypto = require("crypto");
const uuid = (bytes = 16) => crypto.randomBytes(bytes).toString("hex");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
//manually promisify this (util didn't work)
const question = (prompt, def = null) => {
return new Promise((resolve, reject) => {
rl.question(`${prompt}${def ? ` (${def})` : ''}: `, answer => {
//loop on required
if (def === null && !answer) {
return resolve(question(prompt, def));
}
return resolve(answer || def);
});
});
};
//questions
(async () => {
//project configuration
const appName = await question('App Name', 'news');
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
const appWebOrigin = await question('Web Origin', `https://example.com`); //TODO: clean these up properly
const appPort = await question('App Port', '3100');
const appDBUser = await question('DB User', appName);
const appDBPass = await question('DB Pass', 'venusaur');
const dbRootPass = await question('DB Root Pass');
const appSecretAccess = await question('Access Token Secret', uuid(32));
const supportEmail = await question('Support Email', 'example@example.com');
//generate the files
const ymlfile = `
version: '3'
services:
${appName}:
build:
context: .
ports:
- "${appPort}"
labels:
- "traefik.enable=true"
- "traefik.http.routers.${appName}router.rule=Host(\`${appWebAddress}\`)"
- "traefik.http.routers.${appName}router.entrypoints=websecure"
- "traefik.http.routers.${appName}router.tls.certresolver=myresolver"
- "traefik.http.routers.${appName}router.service=${appName}service@docker"
- "traefik.http.services.${appName}service.loadbalancer.server.port=${appPort}"
environment:
- WEB_PORT=${appPort}
- WEB_ORIGIN=${appWebOrigin}
- DB_HOSTNAME=database
- DB_DATABASE=${appName}
- DB_USERNAME=${appDBUser}
- DB_PASSWORD=${appDBPass}
- DB_TIMEZONE=Australia/Sydney
- QUERY_LIMIT=10
- SECRET_ACCESS=${appSecretAccess}
networks:
- app-network
depends_on:
- database
database:
image: mariadb:latest
environment:
MYSQL_DATABASE: ${appName}
MYSQL_USER: ${appDBUser}
MYSQL_PASSWORD: ${appDBPass}
MYSQL_ROOT_PASSWORD: ${dbRootPass}
networks:
- app-network
volumes:
- ./mysql:/var/lib/mysql
- ./startup.sql:/docker-entrypoint-initdb.d/startup.sql:ro
traefik_${appName}:
container_name: ${appName}_traefik
image: "traefik:v2.4"
container_name: "traefik"
command:
- "--log.level=ERROR"
- "--api.insecure=false"
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--entrypoints.websecure.address=:443"
- "--certificatesresolvers.myresolver.acme.tlschallenge=true"
- "--certificatesresolvers.myresolver.acme.email=${supportEmail}"
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
ports:
- "80:80"
- "443:443"
volumes:
- "./letsencrypt:/letsencrypt"
- "/var/run/docker.sock:/var/run/docker.sock:ro"
networks:
- app-network
networks:
app-network:
driver: bridge
`;
const dockerfile = `
FROM node:18
WORKDIR "/app"
COPY package*.json ./
RUN npm install --production
COPY . /app
EXPOSE ${appPort}
USER node
ENTRYPOINT ["bash", "-c"]
CMD ["sleep 10 && npm start"]
`;
const sqlfile = `
CREATE DATABASE IF NOT EXISTS ${appName};
CREATE USER IF NOT EXISTS '${appDBUser}'@'%' IDENTIFIED BY '${appDBPass}';
GRANT ALL PRIVILEGES ON ${appName}.* TO '${appDBUser}'@'%';
`;
fs.writeFileSync('docker-compose.yml', ymlfile);
fs.writeFileSync('Dockerfile', dockerfile);
fs.writeFileSync('startup.sql', sqlfile);
})()
.then(() => rl.close())
.catch(e => console.error(e))
;
-38
View File
@@ -1,38 +0,0 @@
version: '3'
services:
app:
build:
context: .
environment:
WEB_PORT: 3100
DB_HOSTNAME: database
DB_DATABASE: news
DB_USERNAME: news
DB_PASSWORD: charizard
DB_TIMEZONE: Australia/Sydney
QUERY_LIMIT: 10
QUERY_KEY: key
networks:
- app-network
ports:
- "3100:3100"
depends_on:
- database
database:
image: mariadb:latest
environment:
MYSQL_DATABASE: news
MYSQL_USER: news
MYSQL_PASSWORD: charizard
MYSQL_ROOT_PASSWORD: root
networks:
- app-network
volumes:
- ./data:/var/lib/mysql
networks:
app-network:
driver: bridge
-110
View File
@@ -1,110 +0,0 @@
import React, { useState } from 'react';
import Select from 'react-dropdown-select';
//DOCS: props.uri is the address of a live news-server
//DOCS: props.newsKey is the key of the live news-server
const NewsEditor = props => {
let titleElement, authorElement, bodyElement;
const [articles, setArticles] = useState(null);
const [index, setIndex] = useState(null);
if (!articles) {
fetch(`${props.uri}/titles?limit=999`, { method: 'GET' })
.then(a => {
if (!a.ok) {
throw `Network error ${a.status}: ${a.statusText} ${a.url}`;
}
return a.json();
})
.then(a => setArticles(a))
.catch(e => console.error(e))
;
}
return (
<div>
<h2 className='centered'>News Editor</h2>
<div>
<label htmlFor='article'>Article: </label>
<Select
options={(articles || []).map(article => { return { label: article.title, value: article.index }; })}
onChange={values => setIndex(fetchSelection(values[0].value, titleElement, authorElement, bodyElement, props.uri))}
/>
</div>
<form onSubmit={async e => {
e.preventDefault();
await handleSubmit(index, titleElement.value, authorElement.value, bodyElement.value, props.uri, props.newsKey);
titleElement.value = authorElement.value = bodyElement.value = '';
}}>
<div>
<label htmlFor='title'>Title: </label>
<input type='text' name='title' ref={ e => titleElement = e } />
</div>
<div>
<label htmlFor='author'>Author: </label>
<input type='text' name='author' ref={ e => authorElement = e } />
</div>
<div>
<label htmlFor='body'>Body: </label>
<textarea name='body' rows='10' cols='150' ref={ e => bodyElement = e } />
</div>
<button type='submit'>Update</button>
</form>
</div>
);
};
const fetchSelection = (index, titleElement, authorElement, bodyElement, uri) => {
fetch(`${uri}/archive/${index}`, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
.then(blob => blob.json())
.then(article => {
titleElement.value = article.title;
authorElement.value = article.author;
bodyElement.value = article.body;
})
.catch(e => console.error(e))
;
return index; //this is admittedly odd
};
const handleSubmit = async (index, title, author, body, uri, newsKey) => {
title = title.trim();
author = author.trim();
body = body.trim();
uri = uri.trim();
newsKey = newsKey.trim();
//fetch POST json data
const raw = await fetch(
`${uri}/${index}`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ title: title, author: author, body: body, key: newsKey })
}
);
if (raw.ok) {
const result = await raw.json();
if (result.ok) {
alert(`Updated article index ${index}`);
} else {
alert(result.error);
}
} else {
alert(raw.statusText);
}
};
export default NewsEditor;
-42
View File
@@ -1,42 +0,0 @@
import React, { useState } from 'react';
import dateFormat from 'dateformat';
//DOCS: props.uri is the address of a live news-server
const NewsFeed = props => {
const [articles, setArticles] = useState(null);
if (!articles) {
fetch(props.uri, { method: 'GET' })
.then(a => {
if (!a.ok) {
throw `Network error ${a.status}: ${a.statusText} ${a.url}`;
}
return a.json();
})
.then(a => setArticles(a))
.catch(e => console.error(e))
;
}
return (
<div>
<h1 className='centered'>News Feed</h1>
{(articles || []).map((article, index) => {
return (
<div key={index}>
<hr />
<h2>{article.title}</h2>
<p>Written by <strong>{article.author}</strong>, {
article.edits > 0 ?
<span>Last Updated {dateFormat(articles.updatedAt, 'fullDate')} ({`${article.edits} edit${article.edits > 1 ? 's': ''}`})</span> :
<span>Published {dateFormat(articles.createdAt, 'fullDate')}</span>
}</p>
<p style={{whiteSpace: 'pre-wrap'}}>{article.body}</p>
</div>
);
})}
</div>
);
};
export default NewsFeed;
-70
View File
@@ -1,70 +0,0 @@
import React from 'react';
//DOCS: props.uri is the address of a live news-server
//DOCS: props.newsKey is the key of the live news-server
const NewsPublisher = props => {
let titleElement, authorElement, bodyElement;
return (
<div>
<h2 className='centered'>News Publisher</h2>
<form onSubmit={async e => {
e.preventDefault();
await handleSubmit(titleElement.value, authorElement.value, bodyElement.value, props.uri, props.newsKey);
titleElement.value = authorElement.value = bodyElement.value = '';
}}>
<div>
<label htmlFor='title'>Title: </label>
<input type='text' name='title' ref={ e => titleElement = e } />
</div>
<div>
<label htmlFor='author'>Author: </label>
<input type='text' name='author' ref={ e => authorElement = e } />
</div>
<div>
<label htmlFor='body'>Body: </label>
<textarea name='body' rows='10' cols='150' ref={ e => bodyElement = e } />
</div>
<button type='submit'>Publish</button>
</form>
</div>
);
};
const handleSubmit = async (title, author, body, uri, newsKey) => {
title = title.trim();
author = author.trim();
body = body.trim();
uri = uri.trim();
newsKey = newsKey.trim();
//fetch POST json data
const raw = await fetch(
uri,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ title: title, author: author, body: body, key: newsKey })
}
);
if (raw.ok) {
const result = await raw.json();
if (result.ok) {
alert(`Published article index ${result.index}`);
} else {
alert(result.error);
}
} else {
alert(raw.statusText);
}
};
export default NewsPublisher;
+1031 -2138
View File
File diff suppressed because it is too large Load Diff
+7 -6
View File
@@ -1,6 +1,6 @@
{
"name": "news-server",
"version": "1.0.0",
"version": "1.5.2",
"description": "An API centric news server. Uses Sequelize and mariaDB by default.",
"main": "server/server.js",
"scripts": {
@@ -19,14 +19,15 @@
},
"homepage": "https://github.com/krgamestudios/news-server#readme",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"dotenv": "^16.0.1",
"express": "^4.17.1",
"mariadb": "^2.5.2",
"sequelize": "^6.5.0"
"jsonwebtoken": "^8.5.1",
"mariadb": "^3.0.1",
"markdown-it": "^13.0.1",
"sequelize": "^6.6.5"
},
"devDependencies": {
"nodemon": "^2.0.7"
"nodemon": "^2.0.12"
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ const sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME
host: process.env.DB_HOSTNAME,
dialect: 'mariadb',
timezone: process.env.DB_TIMEZONE,
// logging: false
logging: process.env.DB_LOGGING ? console.log : false
});
module.exports = sequelize;
+10 -1
View File
@@ -1,7 +1,7 @@
const Sequelize = require('sequelize');
const sequelize = require('..');
module.exports = sequelize.define('articles', {
const articles = sequelize.define('articles', {
index: {
type: Sequelize.INTEGER(11),
allowNull: false,
@@ -25,8 +25,17 @@ module.exports = sequelize.define('articles', {
defaultValue: ''
},
rendered: {
type: Sequelize.TEXT,
defaultValue: ''
},
edits: {
type: Sequelize.INTEGER(11),
defaultValue: 0
}
});
sequelize.sync();
module.exports = articles;
+18 -6
View File
@@ -1,11 +1,15 @@
const Sequelize = require('sequelize');
const sequelize = require('..');
const articles = require('./articles');
sequelize.sync();
const revisions = sequelize.define('revisions', {
index: {
type: Sequelize.INTEGER(11),
allowNull: false,
autoIncrement: true,
primaryKey: true,
unique: true
},
title: {
type: Sequelize.TEXT,
defaultValue: ''
@@ -19,12 +23,20 @@ const revisions = sequelize.define('revisions', {
body: {
type: Sequelize.TEXT,
defaultValue: ''
},
rendered: {
type: Sequelize.TEXT,
defaultValue: ''
},
originalIndex: {
type: Sequelize.INTEGER(11),
default: null
}
});
//relationships
articles.hasOne(revisions, { as: 'original' });
sequelize.sync();
module.exports = revisions;
+8 -12
View File
@@ -1,12 +1,8 @@
const { Op } = require('sequelize');
const { articles, revisions } = require('../database/models');
const markdownIt = require('markdown-it')({ html: true });
const route = async (req, res) => {
//check the key
if (req.body.key != process.env.QUERY_KEY) {
return res.status(401).json({ ok: false, error: 'invalid key' });
}
//get the existing record
const record = await articles.findOne({
where: {
@@ -17,7 +13,7 @@ const route = async (req, res) => {
});
if (!record) {
return res.status(500).json({ ok: false, error: 'failed to update non-existing record' });
return res.status(500).send('Failed to update non-existing record');
}
//store the revision
@@ -25,14 +21,16 @@ const route = async (req, res) => {
title: record.title,
author: record.author,
body: record.body,
rendered: record.rendered,
originalIndex: record.index
});
//update the data
await articles.update({
title: req.body.title,
author: req.body.author,
body: req.body.body,
title: req.body.title || record.title,
author: req.body.author || record.author,
body: req.body.body || record.body,
rendered: markdownIt.render(req.body.body) || record.rendered,
edits: record.edits + 1
}, {
where: {
@@ -40,9 +38,7 @@ const route = async (req, res) => {
}
});
return res.status(200).json({
ok: true
});
return res.status(200).end();
};
module.exports = route;
+32 -11
View File
@@ -1,5 +1,9 @@
const express = require('express');
const router = express.Router();
const cors = require('cors'); //route-by-route, because some routes are available without authentication
//middleware
const authToken = require('../utilities/token-auth');
//the routes
const query = require('./query');
@@ -7,20 +11,37 @@ const publish = require('./publish');
const edit = require('./edit');
const remove = require('./remove');
//basic route management
router.get('/', query(false, false));
router.get('/:id(\\d+)', query(false, false));
router.get('/archive', query(true, false));
router.get('/archive/:id(\\d+)', query(true, false));
router.get('/titles', query(false, true));
router.get('/titles/:id(\\d+)', query(false, true));
router.get('/archive/titles', query(true, true));
router.get('/archive/titles/:id(\\d+)', query(true, true));
//basic route management (all query possibilities)
router.get('/', cors(), query(false, false));
router.get('/:id(\\d+)', cors(), query(false, false));
router.get('/archive', cors(), query(true, false));
router.get('/archive/:id(\\d+)', cors(), query(true, false));
router.get('/metadata', cors(), query(false, true));
router.get('/metadata/:id(\\d+)', cors(), query(false, true));
router.get('/archive/metadata', cors(), query(true, true));
router.get('/archive/metadata/:id(\\d+)', cors(), query(true, true));
//use middleware to authenticate the rest of the routes
router.use(cors({
credentials: true,
origin: [`${process.env.WEB_ORIGIN}`], //because auth-server
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
}));
router.use(authToken);
router.use((req, res, next) => {
if (req.user.mod) {
next();
} else {
res.status(403).end();
}
});
//authenticated routes
router.post('/', publish);
router.patch('/:id(\\d+)', edit);
router.delete('/:id(\\d+)', remove);
module.exports = router;
+16 -7
View File
@@ -1,23 +1,33 @@
const { articles } = require('../database/models');
const markdownIt = require('markdown-it')({ html: true });
const route = async (req, res) => {
//check the key
if (req.body.key != process.env.QUERY_KEY) {
return res.status(401).json({ ok: false, error: 'invalid key' });
//check for missing data
if (!req.body.title) {
return res.status(401).end("Missing title");
}
if (!req.body.author) {
return res.status(401).end("Missing author");
}
if (!req.body.body) {
return res.status(401).end("Missing body");
}
//upsert the data
const [instance, created] = await articles.upsert({
title: req.body.title,
author: req.body.author,
body: req.body.body
body: req.body.body,
rendered: markdownIt.render(req.body.body),
});
if (!created) {
return res.status(500).json({ ok: false, error: 'failed to create record' });
return res.status(500).send('Failed to create record');
}
//BUGFIX
//BUGFIX: instance doesn't have the index for some reason
const result = await articles.findOne({
order: [
['index', 'DESC']
@@ -25,7 +35,6 @@ const route = async (req, res) => {
});
return res.status(200).json({
ok: true,
// index: instance.get('index')
index: result.index
});
+6 -6
View File
@@ -2,12 +2,12 @@ const { Op } = require('sequelize');
const { articles } = require('../database/models');
//the query function that can be reused
const query = (ascending, titlesOnly) => async (req, res) => {
//specific search
const query = (ascending, metadataOnly) => async (req, res) => {
//specific search (id is defined)
if (req.params.id && typeof(parseInt(req.params.id)) === 'number') {
const result = await articles.findOne({
attributes: [
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!titlesOnly ? ['body'] : [])
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!metadataOnly ? ['body', 'rendered'] : [])
],
where: {
index: {
@@ -16,15 +16,15 @@ const query = (ascending, titlesOnly) => async (req, res) => {
}
});
//returns null if failed to find
return res.status(200).json(result);
//result is null if failed to find
return res.status(200).json(result || []);
}
//default search
else {
const result = await articles.findAndCountAll({
attributes: [
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!titlesOnly ? ['body'] : [])
'index', 'title', 'author', 'edits', 'createdAt', 'updatedAt', ...(!metadataOnly ? ['body', 'rendered'] : [])
],
order: [
['index', ascending ? 'ASC' : 'DESC']
+3 -9
View File
@@ -2,11 +2,6 @@ const { Op } = require('sequelize');
const { articles, revisions } = require('../database/models');
const route = async (req, res) => {
//check the key
if (req.body.key != process.env.QUERY_KEY) {
return res.status(401).json({ ok: false, error: 'invalid key' });
}
//get the existing record
const record = await articles.findOne({
where: {
@@ -17,7 +12,7 @@ const route = async (req, res) => {
});
if (!record) {
return res.status(500).json({ ok: false, error: 'failed to remove non-existing record' });
return res.status(500).json('Failed to remove non-existing record');
}
//store the revision
@@ -25,6 +20,7 @@ const route = async (req, res) => {
title: record.title,
author: record.author,
body: record.body,
rendered: record.rendered,
originalIndex: record.index
});
@@ -35,9 +31,7 @@ const route = async (req, res) => {
}
});
return res.status(200).json({
ok: true
});
return res.status(200).end();
};
module.exports = route;
+45 -4
View File
@@ -5,12 +5,9 @@ require('dotenv').config();
const express = require('express');
const app = express();
const server = require('http').Server(app);
const bodyParser = require('body-parser');
const cors = require('cors');
//config
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
//database connection
const database = require('./database');
@@ -27,4 +24,48 @@ app.get('*', (req, res) => {
server.listen(process.env.WEB_PORT || 3100, async (err) => {
await database.sync();
console.log(`listening to localhost:${process.env.WEB_PORT || 3100}`);
//COMPATABILITY: parse the unrendered data from the database
const markdownIt = require('markdown-it')();
const { articles, revisions } = require('./database/models');
const missingArticles = await articles.findAll({
where: {
rendered: ''
}
});
const missingRevisions = await revisions.findAll({
where: {
rendered: ''
}
});
await Promise.all(
missingArticles.map(async ma => {
ma.update({
rendered: markdownIt.render(ma.body)
}, {
where: {
index: ma.index
}
});
})
)
.then(result => {if (result.length > 0) console.log('Rendered articles in HTML'); })
;
await Promise.all(
missingRevisions.map(async mr => {
mr.update({
rendered: markdownIt.render(mr.body)
}, {
where: {
index: mr.index
}
});
})
)
.then(result => {if (result.length > 0) console.log('Rendered revisions in HTML'); })
;
});
+21
View File
@@ -0,0 +1,21 @@
const jwt = require('jsonwebtoken');
//middleware to authenticate the JWT token
module.exports = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader?.split (' ')[1]; //'Bearer token'
if (!token) {
return res.status(401).end();
}
jwt.verify(token, process.env.SECRET_ACCESS, (err, user) => {
if (err) {
return res.status(403).end();
}
req.user = user;
next();
});
};
+44
View File
@@ -0,0 +1,44 @@
#Query
GET https://dev-news.krgamestudios.com/news HTTP/1.1
###
#Login
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "example@example.com",
"password": "helloworld"
}
###
#Publish
POST https://dev-news.krgamestudios.com/news HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"title": "Hello World",
"author": "Anonymous",
"body": "Lorem ipsum."
}
###
#Edit
PATCH https://dev-news.krgamestudios.com/news/1 HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"title": "Goodnight World"
}
###
#Delete
DELETE https://dev-news.krgamestudios.com/news/1 HTTP/1.1
Content-Type: application/json
Authorization: Bearer
+44
View File
@@ -0,0 +1,44 @@
#Query
GET http://localhost:3100/news HTTP/1.1
###
#Login
POST https://dev-auth.krgamestudios.com/auth/login HTTP/1.1
Content-Type: application/json
{
"email": "example@example.com",
"password": "helloworld"
}
###
#Publish
POST http://localhost:3100/news HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"title": "Hello World",
"author": "Anonymous",
"body": "Lorem ipsum."
}
###
#Edit
PATCH http://localhost:3100/news/1 HTTP/1.1
Content-Type: application/json
Authorization: Bearer
{
"title": "Goodnight World"
}
###
#Delete
DELETE http://localhost:3100/news/1 HTTP/1.1
Content-Type: application/json
Authorization: Bearer
+4
View File
@@ -0,0 +1,4 @@
#use this while debugging
CREATE DATABASE IF NOT EXISTS news;
CREATE USER IF NOT EXISTS 'news'@'%' IDENTIFIED BY 'venusaur';
GRANT ALL PRIVILEGES ON news.* TO 'news'@'%';
+6
View File
@@ -0,0 +1,6 @@
use news;
ALTER TABLE revisions CHANGE COLUMN id `index` INTEGER(11) UNIQUE NOT NULL AUTO_INCREMENT;
ALTER TABLE revisions DROP FOREIGN KEY revisions_ibfk_1;
ALTER TABLE revisions CHANGE COLUMN originalIndex originalIndex INTEGER(11);
+4
View File
@@ -0,0 +1,4 @@
ALTER TABLE articles ADD COLUMN rendered TEXT DEFAULT "" AFTER body;
ALTER TABLE revisions ADD COLUMN rendered TEXT DEFAULT "" AFTER body;