ÿØÿà JFIF ` ` ÿþ
|
Server : Apache System : Linux cloud.heroica.com.br 4.18.0-553.36.1.el8_10.x86_64 #1 SMP Wed Jan 22 03:07:54 EST 2025 x86_64 User : farolpborg ( 1053) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /var/www/node_services/sebraevisitas/src/services/ |
Upload File : |
import {$Enums, PrismaClient} from "../generated/prisma";
import bcrypt from "bcryptjs";
import {sign} from "jsonwebtoken";
import UserSexo = $Enums.UserSexo;
export type CreateUserDTO = {
name: string;
login: string;
password: string;
email: string;
cpf: string;
profileImage: string;
profileId: string;
active?: boolean;
sexo:string;
datanasc:string;
escolaridade:string;
possuinomesocial:boolean;
nomesocial?:string;
confirmPassword:string;
empresa:string;
profile:string;
createdBy?:string;
};
export type UpdateUserDTO = Partial<Omit<CreateUserDTO, "login" | "email" | "cpf">> & {
// allow updating these too if needed
login?: string;
email?: string;
cpf?: string;
};
const prisma = new PrismaClient();
const sanitize = <T extends { password?: string }>(obj: T): Omit<T, "password"> => {
const { password, ...rest } = obj as any;
return rest as any;
};
const UserServices = class {
static async create(data: CreateUserDTO) {
// basic uniqueness checks (since schema has no unique constraints specified)
const [existingLogin, existingEmail, existingCpf] = await Promise.all([
prisma.user.findFirst({ where: { login: data.login } }),
prisma.user.findFirst({ where: { email: data.email } }),
prisma.user.findFirst({ where: { cpf: data.cpf } }),
]);
if (existingLogin) throw new Error("Login já cadastrado");
if (existingEmail) throw new Error("Email já cadastrado");
if (existingCpf) throw new Error("CPF já cadastrado");
const hashed = await bcrypt.hash(data.password, 10);
const getprofile = await prisma.profile.findFirst({ where: { name: data.profile } });
console.log('create user data -> ' , data)
const user = await prisma.user.create({
data: {
name: data.name,
login: data.login,
password: hashed,
email: data.email,
cpf: data.cpf,
empresa: (data as any).empresa, // optional field supported by schema
profileImage: data.profileImage,
profileId: (getprofile)?getprofile.id as string : '',
active: data.active ?? true,
escolaridade:data.escolaridade,
sexo:data.sexo as UserSexo || 'outro',
possuinomesocial:data.possuinomesocial,
nomesocial:data.nomesocial,
datanasc:data.datanasc,
createdBy:data.createdBy
},
});
return sanitize(user);
}
static async list() {
const users = await prisma.user.findMany({include:{profile:true}});
return users.map((u) => sanitize(u));
}
static async getById(id: string) {
const user = await prisma.user.findUnique({ where: { id } , include:{profile:true} });
if (!user) throw new Error("Usuário não encontrado");
return sanitize(user);
}
static async update(id: string, data: UpdateUserDTO) {
// if updating unique-like fields, ensure not conflicting with others
if (data.login) {
const exists = await prisma.user.findFirst({ where: { login: data.login, NOT: { id } } as any });
if (exists) throw new Error("Login já cadastrado");
}
if (data.email) {
const exists = await prisma.user.findFirst({ where: { email: data.email, NOT: { id } } as any });
if (exists) throw new Error("Email já cadastrado");
}
if (data.cpf) {
const exists = await prisma.user.findFirst({ where: { cpf: data.cpf, NOT: { id } } as any });
if (exists) throw new Error("CPF já cadastrado");
}
const toUpdate: any = { ...data };
if (data.password) {
toUpdate.password = await bcrypt.hash(data.password, 10);
}
const updated = await prisma.user.update({ where: { id }, data: toUpdate });
return sanitize(updated);
}
static async remove(id: string) {
await prisma.user.delete({ where: { id } });
return { success: true };
}
static async login(cpf: string, password: string) {
try{
console.log('Login services')
const user = await prisma.user.findFirst({ where: { cpf }, include: { profile: true} });
console.log(user)
if (!user || !user.active) throw new Error("Credenciais inválidas");
const ok = await bcrypt.compare(password, user.password);
if (!ok) throw new Error("Credenciais inválidas");
const token = sign({
user:user.name,
email:user.email
},
process.env.JWT_HASH || 'secret',
{
subject:user.id,
expiresIn:'30d'
})
// Do not issue JWT if not required; return sanitized user for now
console.log(token)
return sanitize({...user, token});
}catch (e:any){
console.log('Erro login ' , e)
throw e;
}
}
static async setUserProfile(userId:string , profileId:string ) {
const user_exists = await prisma.user.findFirst({ where: { id: userId } });
if(!user_exists){
throw new Error("Usuário não encontrado");
}
const profile_exists = await prisma.profile.findFirst({ where: { id: profileId } });
if(!profile_exists){
throw new Error("Perfil não encontrado");
}
return prisma.user.update({
where: {id: userId},
data: {profileId: profileId}
}
);
}
};
export default UserServices