2021-10-17 20:55:00 +02:00
|
|
|
import { randomBytes } from 'crypto'
|
|
|
|
|
import jwt from 'jsonwebtoken'
|
|
|
|
|
import db from './Database.js'
|
|
|
|
|
|
|
|
|
|
export default {
|
|
|
|
|
async createAccount(name) {
|
2021-10-18 02:41:25 +02:00
|
|
|
if (typeof name !== "string")
|
|
|
|
|
return {
|
|
|
|
|
error: "Incorrect name"
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-01 03:36:30 +01:00
|
|
|
const re = /^[a-zA-Z0-9_$][a-zA-Z0-9 _$]{1,15}$/
|
2021-10-18 02:41:25 +02:00
|
|
|
if (!re.test(name))
|
|
|
|
|
return {
|
|
|
|
|
error: "Incorrect name"
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-17 20:55:00 +02:00
|
|
|
console.log("Creating user");
|
|
|
|
|
if (db.userExists(name)) {
|
|
|
|
|
console.log("User exists");
|
|
|
|
|
return {
|
|
|
|
|
error: "The name alredy occupied"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-17 21:12:42 +02:00
|
|
|
const password = randomBytes(16).toString('hex')
|
2021-10-17 20:55:00 +02:00
|
|
|
const token = jwt.sign({
|
|
|
|
|
name: name,
|
|
|
|
|
record: 0,
|
|
|
|
|
}, process.env.secret)
|
|
|
|
|
|
|
|
|
|
await db.addUser({
|
|
|
|
|
name,
|
2021-10-17 21:12:42 +02:00
|
|
|
password: password,
|
2021-10-17 20:55:00 +02:00
|
|
|
record: 0,
|
2021-10-18 02:33:29 +02:00
|
|
|
lastPlayed: 0,
|
2021-10-17 20:55:00 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
name,
|
2021-10-17 21:12:42 +02:00
|
|
|
password: password,
|
2021-10-17 20:55:00 +02:00
|
|
|
record: 0,
|
2021-10-17 21:12:42 +02:00
|
|
|
token
|
|
|
|
|
}
|
|
|
|
|
},
|
2021-10-18 02:33:29 +02:00
|
|
|
|
2021-10-17 21:12:42 +02:00
|
|
|
login(password) {
|
|
|
|
|
console.log("Logging user");
|
2021-10-18 02:41:25 +02:00
|
|
|
if (typeof password !== "string")
|
|
|
|
|
return {
|
|
|
|
|
error: "User does not exists"
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-17 21:12:42 +02:00
|
|
|
const user = db.getUserByPassword(password)
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return {
|
|
|
|
|
error: "User does not exists"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
const token = jwt.sign({
|
|
|
|
|
name: user.name,
|
|
|
|
|
record: user.record,
|
|
|
|
|
}, process.env.secret)
|
|
|
|
|
|
2021-10-18 02:33:29 +02:00
|
|
|
const { lastPlayed, ...strippedUser } = user;
|
|
|
|
|
|
2021-10-17 21:12:42 +02:00
|
|
|
return {
|
2021-10-18 02:33:29 +02:00
|
|
|
...strippedUser,
|
2021-10-17 20:55:00 +02:00
|
|
|
token
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|