74 lines
2.2 KiB
JavaScript
74 lines
2.2 KiB
JavaScript
import { runPrepQuery, numRows } from "../Utility/db.js";
|
|
import { Warn } from "./loggerUtility.js";
|
|
const users = {}
|
|
import jwt from 'jsonwebtoken';
|
|
const { sign, verify } = jwt;
|
|
const addUserToMemory = (userId, authToken) => {
|
|
users[userId] = {userId, authToken}
|
|
}
|
|
const removeUser = (userId) => {
|
|
if(users[userId]?.socket) {
|
|
socket.destroy()
|
|
delete users[userId]
|
|
runPrepQuery("DELETE FROM users WHERE userId = ? LIMIT 1", [userId], (r,f,e) => {})
|
|
}
|
|
}
|
|
const getUser = (userId) => {
|
|
if(users[userId]) return users[userId]
|
|
return false
|
|
}
|
|
export const getUserFromJwt = (jwt) => {
|
|
try {
|
|
const decoded = verify(jwt, process.env.JWT_SECRET)
|
|
return getUser(decoded.userId)
|
|
} catch (e) {
|
|
console.log(e)
|
|
return false
|
|
}
|
|
|
|
|
|
}
|
|
export const setUserSocket = (socket, userId) => {
|
|
socket.userId = userId
|
|
users[userId].socket = socket
|
|
}
|
|
export const addUser = (userId) => {
|
|
return new Promise((resolve, reject) => {
|
|
runPrepQuery("SELECT * FROM users WHERE userId = ? LIMIT 0,1", [userId], async (r,f,e) => {
|
|
if(!e) {
|
|
let token
|
|
if(!numRows(r)) {
|
|
token = sign({userId: userId}, process.env.JWT_SECRET)
|
|
runPrepQuery("INSERT INTO users (authToken, userId) VALUES(?,?)", [token, userId], async (r,f,e) => {
|
|
if(!e) {
|
|
return resolve({userId, authToken: token})
|
|
}
|
|
return resolve(false)
|
|
})
|
|
|
|
} else {
|
|
return resolve({userId, authToken: token})
|
|
}
|
|
}
|
|
});
|
|
})
|
|
|
|
}
|
|
export const loadUsersFromDB = () => {
|
|
return new Promise((resolve, reject) => {
|
|
runPrepQuery("SELECT * FROM users", [], async (r, f, e) => {
|
|
if (!e) {
|
|
if (numRows(r)) {
|
|
for(const row of r) {
|
|
users[row.userId] = row;
|
|
}
|
|
}
|
|
} else {
|
|
console.log(e);
|
|
}
|
|
resolve(true)
|
|
});
|
|
})
|
|
};
|
|
|