package ciai.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import ciai.exception.AccountAlreadyExistException; import ciai.model.Account; import ciai.model.Degree; import ciai.model.Professor; import ciai.model.Student; import ciai.repository.AccountRepository; import ciai.repository.DegreeRepository; import ciai.repository.ProfessorRepository; import ciai.repository.RoleRepository; import ciai.repository.StudentRepository; import tools.AccountRole; @Service public class AccountService { @Autowired AccountRepository accRep; @Autowired RoleRepository roleRep; @Autowired StudentRepository studentsRep; @Autowired DegreeRepository degreesRep; @Autowired ProfessorRepository profRep; public Account getAccountByUsername(String username) { return accRep.findByUsername(username); } public Account createAccount(String name, String username, String password, String type, String degree) throws AccountAlreadyExistException, Exception { if (getAccountByUsername(username) != null && getAccountByUsername(username + "@fct.unl.pt") == null) throw new AccountAlreadyExistException(); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); Account newAccount = null; int rt = Integer.parseInt(type); String encrypted_Password = encoder.encode(password); if(accRep.findByUsername(username) != null || accRep.findByUsername(username+"@fct.unl.pt") != null) throw new AccountAlreadyExistException(); if (rt == 0) { newAccount = new Account(username + "@fct.unl.pt", encrypted_Password, roleRep.findByDescription(AccountRole.STUDENT)); if(accRep.save(newAccount) == null) throw new AccountAlreadyExistException(); Iterable it = studentsRep.findAll(); int max = 1000; for (Student s : it) { if (max <= s.getNumber()) { max = s.getNumber() + 1; } } Long degreeId = Long.valueOf(degree); Degree dg = degreesRep.findOne(degreeId); if(dg == null){ throw new Exception(); } Student s = new Student(name, newAccount, max); s.setDegree(dg); if(studentsRep.save(s) == null) throw new AccountAlreadyExistException(); } else if (rt == 1 || rt == 2) { if (rt == 1) newAccount = new Account(username, encrypted_Password, roleRep.findByDescription(AccountRole.PROFESSOR)); else newAccount = new Account(username, encrypted_Password, roleRep.findByDescription(AccountRole.ASSISTANT)); if(accRep.save(newAccount) == null) throw new AccountAlreadyExistException(); Professor p = new Professor(name, username + "@fct.unl.pt", newAccount); if(profRep.save(p) == null) throw new AccountAlreadyExistException(); } return newAccount; } }