WebService/services/userService.js
azures04 f8c1340b41 Refactor license and permission management, add services
Renamed licenceRepository.js to licenseRepository.js and updated its API to use status instead of userId for licenses. Moved permission checking logic from userRepository to permissionsRepository. Added new service layers for license, permissions, and user management, implementing error handling and business logic. Removed the old register.js service and cleaned up test.js. Updated database schema to remove userId from licenses.
2026-01-27 05:49:50 +01:00

66 lines
2.1 KiB
JavaScript

const userRepository = require("../repositories/userRepository")
const bcrypt = require("bcryptjs")
const logger = require("../modules/logger")
const { DefaultError } = require("../errors/errors")
async function register({ firstName = null, lastName = null, username, password }) {
const isUserExists = userRepository.findByUsername(username)
if (isUserExists) {
throw new DefaultError(409, "Username taken.")
}
try {
const hashedPassword = await bcrypt.hash(password, 4)
return userRepository.register(firstName, lastName, username, hashedPassword)
} catch (error) {
logger.error(error, ["Service", "yellow", "USER", "green"])
throw new DefaultError(500, "Please contact the maintainer")
}
}
async function remove(id) {
const user = userRepository.findById(id)
if (!user) {
throw new DefaultError(404, "User not found.")
}
try {
return userRepository.remove(id)
} catch (error) {
logger.error(error, ["Service", "yellow", "USER", "green"])
throw new DefaultError(500, "Please contact the maintainer")
}
}
async function changePassword(id, newPassword) {
const user = userRepository.findById(id)
if (!user) {
throw new DefaultError(404, "User not found.")
}
try {
const hashedPassword = await bcrypt.hash(newPassword, 4)
return userRepository.changePassword(id, hashedPassword)
} catch (error) {
logger.error(error, ["Service", "yellow", "USER", "green"])
throw new DefaultError(500, "Please contact the maintainer")
}
}
function findById(id) {
try {
const user = userRepository.findById(id)
if (!user) {
throw new DefaultError(404, "User not found.")
}
return user
} catch (error) {
if (error instanceof DefaultError) throw error
logger.error(error, ["Service", "yellow", "USER", "green"])
throw new DefaultError(500, "Please contact the maintainer")
}
}
module.exports = {
remove,
findById,
register,
changePassword,
}