Merge branch 'main' into new

This commit is contained in:
Leo
2024-01-21 02:37:44 +08:00
17 changed files with 722 additions and 406 deletions

View File

@ -64,7 +64,6 @@ const apikeyModel = sequelize.define(
module.exports = { apikeyModel };
/*
class AuthToken extends Model {
check(){

View File

@ -2,14 +2,12 @@ const { sequelize } = require("../database/mySql.js");
const { apikeyModel } = require("../database/model/apikeyModel.js");
const { userModel } = require("../database/model/userModel.js");
const { Op, Sequelize } = require("sequelize");
const { hashAPIKey } = require("../functions/bcrypt.js");
const { generateUUID } = require("../functions/generateUUID.js");
const { hashPassword } = require("../functions/bcrypt.js");
const { hashPassword , comparePassword , hashAPIKey } = require("../functions/bcrypt.js");
//helper function
async function getUser() {
const user = await userModel.findAll();
return user;
}
//api/v0/user/register
/* Registering new user
@ -22,15 +20,76 @@ async function addUser(user) {
//hash password
let hash = await hashPassword(user.password);
await userModel.create({
const addRes = await userModel.create({
username: user.username,
password: hash,
email: user.email,
address: user.address,
phone: user.phone,
});
if (addRes){
return true;
}
else{
return false;
}
}
//add token to db
async function addToken(userid , token) {
console.log(userid);
console.log(token);
}
async function loginUser(user) {
//look up username or email in db
const userRes = await userModel.findOne({
where: {
[Op.or]: [
{
username: user.userInfo,
},
{
email: user.userInfo,
},
],
},
})
//if user exists
if (userRes){
//compare password
let match = await comparePassword(user.password, userRes.password);
if (match){
console.log(userRes.id);
console.log(userRes.username);
//generate token
let token = await generateUUID();
//add to db
addToken(userRes.id, token);
//sucessful login
/*
1) generate token
2) store in db and localstorage (maybe hash it?)
3) return userid and username and token and store in localstorage
*/
return { token: token, userid: userRes.id, username: userRes.username };
}
else {
return false;
}
}
else{
return false;
}
}
async function getAPIKey() {
const apikey = await apikeyModel.findAll();
return apikey;
@ -44,8 +103,6 @@ async function getAPIKey() {
5) you give the user rowid-uuidv4
6) store in database
*/
async function addAPIKey(userId, permission) {
let token = await generateUUID();
let usertoken = userId + "-" + token;
@ -66,8 +123,7 @@ async function addAPIKey(userId, permission) {
}
module.exports = {
getUser,
addUser,
getAPIKey,
loginUser,
addAPIKey,
};

View File

@ -29,9 +29,14 @@ async function hashAPIKey(apikey) {
return await bcrypt.hash(apikey, saltRounds);
}
async function comparePassword(password, hash) {
return await bcrypt.compare(password, hash);
}
module.exports = {
hashPassword,
hashAPIKey,
comparePassword
};

View File

@ -0,0 +1,4 @@
/*v
1) check if token proided by JSON req is valid against db
2) if valid its passed to next()
*/

View File

@ -28,12 +28,19 @@ app.use("/", require("../routes/render")); //consumerWebsite\routes\render.js
// Catch 404 and forward to error handler. If none of the above routes are
// used, this is what will be called.
app.use(function (req, res, next) {
if (req.is("application/json")) {
var err = new Error("Not Found");
err.message = "Page not found";
err.status = 404;
next(err);
}
else{
res.status(404).render("404");
}
});
// Error handler. This is where `next()` will go on error
app.use(function (err, req, res, next) {
console.error(err.status || res.status, err.name, req.method, req.url);

View File

@ -66,7 +66,7 @@ body {
header {
font-size: 30px;
text-align: center;
color: #fff;
color: #000000;
font-weight: 600;
cursor: pointer;
}
@ -93,6 +93,7 @@ body {
margin-top: 50px;
}
form
input {
height: 60px;
@ -106,6 +107,7 @@ form
border-radius: 8px;
background: #fff;
}
.form.login
input {
border: 1px

View File

@ -12,7 +12,7 @@ app.util = (function (app) {
function actionMessage(message, $target, type, callback) {
message = message || "";
$target = $target.closest("div.card").find(".actionMessage");
$target = $target.closest("div.iot-card").find(".actionMessage");
type = type || "info";
callback = callback || function () {};
@ -29,9 +29,6 @@ app.util = (function (app) {
});
} else {
if (type) $target.addClass("bg-" + type);
message =
'<button class="action-close btn btn-sm btn-outline-dark float-right"><i class="fa-solid fa-xmark"></i></button>' +
message;
$target.html(message).slideDown("fast");
}
setTimeout(callback, 10);
@ -137,6 +134,7 @@ app.api = (function (app) {
complete: function (res, text) {
callback(
text !== "success" ? res.statusText : null,
//console.log(res.responseText),
JSON.parse(res.responseText),
res.status
);
@ -153,6 +151,14 @@ app.auth = (function (app) {
localStorage.setItem("APIToken", token);
}
function setUserId(userId) {
localStorage.setItem("userId", userId);
}
function setUsername(username) {
localStorage.setItem("username", username);
}
function getToken() {
return localStorage.getItem("APIToken");
}
@ -167,7 +173,7 @@ app.auth = (function (app) {
callback(null, false);
}
}
/*
function logIn(args, callback) {
app.api.post("auth/login", args, function (error, data) {
if (data.login) {
@ -176,9 +182,14 @@ app.auth = (function (app) {
callback(error, !!data.token);
});
}
*/
function logOut(callback) {
localStorage.removeItem("APIToken");
localStorage.removeItem("userId");
localStorage.removeItem("username");
//remove token from db NOT the api key.
callback();
}
@ -196,46 +207,50 @@ app.auth = (function (app) {
function logInRedirect() {
window.location.href =
//window.location.href = location.href.replace(location.origin+'/login', '') || '/'
location.href.replace(location.replace(`/login`)) || "/";
}
function homeRedirect() {
window.location.href = location.href.replace(location.replace(`/`)) || "/";
}
return {
getToken: getToken,
setToken: setToken,
setUserId: setUserId,
setUsername: setUsername,
isLoggedIn: isLoggedIn,
logIn: logIn,
//logIn: logIn,
logOut: logOut,
forceLogin,
logInRedirect,
homeRedirect,
};
})(app);
//ajax form submit
function formAJAX( btn, del ) {
event.preventDefault(); // avoid to execute the actual submit of the form.
var $form = $(btn).closest( '[action]' ); // gets the 'form' parent
var formData = $form.find( '[name]' ).serializeObject(); // builds query formDataing
var method = $form.attr('method') || 'post';
function formAJAX(btn, del) {
event.preventDefault(); // avoid to execute the actual submit of the form.
var $form = $(btn).closest("[action]"); // gets the 'form' parent
var formData = $form.find("[name]").serializeObject(); // builds query formDataing
var method = $form.attr("method") || "post";
// if( !$form.validate()) {
// app.util.actionMessage('Please fix the form errors.', $form, 'danger')
// return false;
// }
app.util.actionMessage(
'<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>',
$form,
'info'
);
// if( !$form.validate()) {
// app.util.actionMessage('Please fix the form errors.', $form, 'danger')
// return false;
// }
//console.log('Data being sent to', $form.attr('action'), formData)
app.util.actionMessage("Loading...", $form, "info");
app.api[method]($form.attr('action'), formData, function(error, data){
//console.log('Data back from the server', error, data)
app.util.actionMessage(data.message, $form, error ? 'danger' : 'success'); //re-populate table
if(!error){
$form.trigger("reset");
eval($form.attr('evalAJAX')); //gets JS to run after completion
}
});
}
//console.log('Data being sent to', $form.attr('action'), formData)
app.api[method]($form.attr("action"), formData, function (error, data) {
//console.log('Data back from the server', error, data)
app.util.actionMessage(data.message, $form, error ? "danger" : "success"); //re-populate table
if (!error) {
$form.trigger("reset");
eval($form.attr("evalAJAX")); //gets JS to run after completion
}
});
}

View File

@ -77,10 +77,4 @@ router.get('/contact', function(req, res, next) {
res.render('contact');
});
//404 page
router.get('*', function(req, res, next) {
res.render('404');
});
module.exports = router;

View File

@ -1,41 +1,60 @@
const { getUser, addUser } = require("../functions/apiDatabase.js");
const { addUser, loginUser } = require("../functions/apiDatabase.js");
const express = require("express");
const router = express.Router();
//get all users
router.get("/", async (req, res, next) => {
try {
const location = await getUser();
res.status(200).json(location);
} catch (error) {
console.error(error);
next(error);
}
});
// /user/register
router.post("/register", async (req, res, next) => {
try {
console.log("this is " , req.body);
await addUser(req.body);
res.status(200).json({ register: true });
let Res = await addUser(req.body);
if (Res == false) {
let error = new Error("UserRegFailed");
error.message = "The user failed to be craated";
error.status = 400;
return next(error);
}
else{
return res.json({
message: "User created successfully",
});
}
} catch (error) {
console.error(error);
next(error);
}
});
//login
router.post("/login", async (req, res, next) => {
try {
let Res = await loginUser(req.body);
if (Res == false) {
let error = new Error("User Login Failed");
error.status = 400;
return next(error);
}
else{
//pass res back to form to be set in local storage
console.log(Res);
return res.json({
message: "User login successfully",
token: Res.token,
userId: Res.userid,
username: Res.username,
});
}
} catch (error) {
console.error(error);
next(error);
}
});
//update
//delete
//getbyid
module.exports = router;
/*
curl localhost/api/v0/user/register -H "Content-Type: application/json" -X POST -d '{"username":
@ -78,4 +97,4 @@ router.get('/:uid', async function(req, res, next){
module.exports = router;
*/
*/

View File

@ -2,14 +2,11 @@
<body>
<section class="wrapper">
<div class="form signup" >
<div class="form signup iot-card">
<!--<div class="form signup card" -->
<header>Signup</header>
<!-- Return message from api -->
<div class="actionMessage" style="display:none"></div>
<!-- localhost/api/v0/user/register -->
<!-- evalAjax Fires when status is returned -->
<!-- evalAjax Fires when status 200 is returned -->
<form action="user/register" onsubmit="formAJAX(this)" evalAJAX="app.auth.logInRedirect();">
<input type="text" name="username" placeholder="Username" required />
<input type="text" name="email" placeholder="Email" required />
@ -21,7 +18,7 @@
</form>
</div>
<div class="form login">
<div class="form login iot-card">
<header>Login</header>
<div class="card-header shadow actionMessage" style="display:none"></div>
<!-- evalAjax Fires when status 200 is returned -->
@ -34,7 +31,7 @@
<input type="text" name="userInfo" placeholder="Email address | Username" required />
<input type="password" name="password" placeholder="Password" required />
<a href="/forgotPassword">Forgot password?</a>
<a href="/resetPassword">Forgot password?</a>
<input type="submit" value="Login" />
</form>
</div>