Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat:reset counter #70

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 96 additions & 8 deletions assets/script.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
(function () {
const btn = document.getElementById('get');
const generate_btn = document.getElementById('get');
const changePw_btn = document.getElementById('changePw');
const reset_btn = document.getElementById('reset');
const img = document.getElementById('result');
const code = document.getElementById('code');

Expand All @@ -13,10 +15,14 @@
pixelated: document.getElementById('pixelated'),
darkmode: document.getElementById('darkmode'),
num: document.getElementById('num'),
prefix: document.getElementById('prefix')
prefix: document.getElementById('prefix'),
old_password: document.getElementById('old_password'),
new_password: document.getElementById('new_password')
};

btn.addEventListener('click', throttle(handleButtonClick, 500));
generate_btn.addEventListener('click', throttle(handleGenerateButtonClick, 500));
reset_btn.addEventListener('click', throttle(handleResetButtonClick, 500));
changePw_btn.addEventListener('click', throttle(handleChangePwButtonClick, 500));
code.addEventListener('click', selectCodeText);

const mainTitle = document.querySelector('#main_title i');
Expand All @@ -26,7 +32,8 @@
mainTitle.addEventListener('click', throttle(() => party.sparkles(document.documentElement, { count: party.variation.range(40, 100) }), 1000));
moreTheme.addEventListener('click', scrollToThemes);

function handleButtonClick() {
// When the botton 'Generate' clicked
function handleGenerateButtonClick() {
const { name, theme, padding, offset, scale, pixelated, darkmode, num } = elements;
const nameValue = name.value.trim();

Expand Down Expand Up @@ -57,14 +64,14 @@
const imgSrc = `${__global_data.site}/@${nameValue}?${query}`;

img.src = `${imgSrc}&_=${Math.random()}`;
btn.setAttribute('disabled', '');
generate_btn.setAttribute('disabled', '');

img.onload = () => {
img.scrollIntoView({ block: 'start', behavior: 'smooth' });
code.textContent = imgSrc;
code.style.visibility = 'visible';
party.confetti(btn, { count: party.variation.range(20, 40) });
btn.removeAttribute('disabled');
party.confetti(generate_btn, { count: party.variation.range(20, 40) });
generate_btn.removeAttribute('disabled');
};

img.onerror = async () => {
Expand All @@ -75,11 +82,92 @@
alert(message);
}
} finally {
btn.removeAttribute('disabled');
generate_btn.removeAttribute('disabled');
}
};
}

// When the botton 'Change Password' clicked
function handleChangePwButtonClick() {
const { name, old_password, new_password } = elements;
const nameValue = name.value.trim();
const oldPwValue = old_password.value.trim();
const newPwValue = new_password.value.trim();
if (!nameValue) {
alert('Please input counter name.');
return;
}
const postData = {
name: nameValue,
old_password: oldPwValue,
new_password: newPwValue
};
const postUrl = `${__global_data.site}/change_password`;
fetch(postUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
const errorMessage = errorData.message;
throw new Error(errorMessage);
})
} else
return response.json();
})
.then(data => {
alert(data.message || "Password changed successfully.");
location.reload();
})
.catch(error => {
console.log('Error:', error)
alert('Failed to reset the password: ' + (error.message || 'unknown error'));
});
}

// When the botton 'Reset' clicked
function handleResetButtonClick() {
const { name, old_password } = elements;
const nameValue = name.value.trim();
const oldPwValue = old_password.value.trim();
if (!nameValue) {
alert('Please input counter name.');
return;
}
const postData = {
name: nameValue,
password: oldPwValue
};
const postUrl = `${__global_data.site}/reset`;
fetch(postUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData),
})
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
const errorMessage = errorData.message;
throw new Error(errorMessage);
})
} else
return response.json();
})
.then(data => {
alert(data.message || "Counter reset successfully.");
})
.catch(error => {
console.log('Error:', error)
alert('Failed to reset the counter: ' + (error.message || 'unknown error'));
});
}

function selectCodeText(e) {
e.preventDefault();
e.stopPropagation();
Expand Down
19 changes: 17 additions & 2 deletions db/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const mongoose = require("mongoose");
const schema = new mongoose.Schema(
{
name: { type: String, required: true },
num: { type: Number, required: true }
num: { type: Number, required: true },
password: { type: String, required: true }
},
{ collection: 'tb_count', versionKey: false }
);
Expand All @@ -21,8 +22,12 @@ mongoose.connect(mongodbURL, {

const Count = mongoose.connection.model("Count", schema);

function getPassword(name) {
return Count.findOne({ name }, "-_id -num -__v").exec();
}

function getNum(name) {
return Count.findOne({ name }, "-_id -__v").exec();
return Count.findOne({ name }, "-_id -password -__v").exec();
}

function getAll() {
Expand Down Expand Up @@ -52,9 +57,19 @@ function setNumMulti(counters) {
return Count.bulkWrite(bulkOps, { ordered: false });
}

function setPassword(name, password) {
return Count.findOneAndUpdate(
{ name },
{ name, password },
{ upsert: true }
).exec();
}

module.exports = {
getNum,
getPassword,
getAll,
setNum,
setNumMulti,
setPassword
};
47 changes: 37 additions & 10 deletions db/sqlite.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ const Database = require('better-sqlite3')

const db = new Database(path.resolve(__dirname, '../count.db'))

db.exec(`CREATE TABLE IF NOT EXISTS tb_count (
id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL
UNIQUE,
name VARCHAR (32) NOT NULL
UNIQUE,
num BIGINT NOT NULL
DEFAULT (0)
);`)
db.exec(`
CREATE TABLE IF NOT EXISTS tb_count (
id INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL
UNIQUE,
name VARCHAR (32) NOT NULL
UNIQUE,
num BIGINT NOT NULL
DEFAULT (0),
password VARCHAR (32) NOT NULL
DEFAULT ''
);
`);

function getNum(name) {
return new Promise((resolve, reject) => {
Expand All @@ -23,6 +27,14 @@ function getNum(name) {
})
}

function getPassword(name) {
return new Promise((resolve, reject) => {
const stmt = db.prepare('SELECT `name`, `password` from tb_count WHERE `name` = ?')
const row = stmt.get(name)
resolve(row || { name, password: "" })
})
}

function getAll(name) {
return new Promise((resolve, reject) => {
const stmt = db.prepare('SELECT * from tb_count')
Expand Down Expand Up @@ -61,9 +73,24 @@ function setNumMulti(counters) {
})
}

function setPassword(name, password) {
return new Promise((resolve, reject) => {
const stmt = db.prepare(
`INSERT INTO tb_count(name, password)
VALUES(?, ?)
ON CONFLICT(name) DO
UPDATE SET password = excluded.password;`);

stmt.run(name, password);
resolve()
})
}

module.exports = {
getNum,
getPassword,
getAll,
setNum,
setNumMulti
setNumMulti,
setPassword
}
45 changes: 45 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ app.use(express.static("assets"));
app.use(compression());
app.use(cors());
app.set("view engine", "pug");
app.use(express.json()); //in order to use request body

app.get('/', (req, res) => {
const site = process.env.APP_SITE || `${req.protocol}://${req.get('host')}`
Expand All @@ -27,6 +28,50 @@ app.get('/', (req, res) => {
})
});

// reset the counter
// url:/reset
// Name and password are in the request body
app.post('/reset', async (req, res) => {
const { name, password } = req.body;
if (name === 'demo') {
res.status(403).json({ message: 'Invalid name' });
}
// Varify password
try {
const counter = await db.getPassword(name);
const validPassword = counter.password;

if (password === validPassword) {
__cache_counter[name] = 0;
pushDB();
res.json({ message: 'Counter reset successfully', count: __cache_counter[name] });
} else {
res.status(403).json({ message: 'Invalid password' });
}
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' })
}
});
// change password
// url:/change_password
app.post('/change_password', async (req, res) => {
const { name, old_password, new_password } = req.body;
// Varify password
try {
const counter = await db.getPassword(name);
const validPassword = counter.password;

if (old_password === validPassword) {
await db.setPassword(name, new_password)
res.json({ message: 'Password changed successfully' });
} else {
res.status(403).json({ message: 'Incorrect old password' });
}
} catch (error) {
console.log(error);
res.status(500).json({ message: 'Internal Server Error' })
}
});
// get the image
app.get(["/@:name", "/get/@:name"],
ZodValid({
Expand Down
Loading