Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
Arbona Alapont committed Oct 6, 2023
2 parents b0d6cc9 + 254aef5 commit 825b7a2
Show file tree
Hide file tree
Showing 31 changed files with 393 additions and 55 deletions.
28 changes: 28 additions & 0 deletions Ai-labar.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,34 @@
},
"response": []
},
{
"name": "adminAccess",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"password\": \"f40c05434358a62bde28b7991e16f880d059d99adb2c20242cf2db46c197e322\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "localhost:8080/users/adminAccess",
"host": [
"localhost"
],
"port": "8080",
"path": [
"users",
"adminAccess"
]
}
},
"response": []
},
{
"name": "createUser",
"request": {
Expand Down
10 changes: 5 additions & 5 deletions Backend/ai-labar/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.capgemini</groupId>
<artifactId>ai-labar</artifactId>
<version>2.3.0</version>
<name>ai-labar</name>
<description>AI-Labar Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.capgemini</groupId>
<artifactId>ai-labar</artifactId>
<version>2.3.0</version>
<name>ai-labar</name>
<description>AI-Labar Project</description>
<properties>
<java.version>11</java.version>
</properties>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package com.capgemini.ailabar;

import com.capgemini.ailabar.commons.utils.AccessPom;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class AiLabarApplication {
private static final Logger logger = LogManager.getLogger(AiLabarApplication.class);

public static void main(String[] args) {
SpringApplication.run(AiLabarApplication.class, args);
logger.info(AccessPom.showAppVersion());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.capgemini.ailabar.commons.utils;

import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

@Component
public final class AccessPom {
private AccessPom() {}
public static String showAppVersion() {
try {
File pomFile = new File("pom.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

Document document = documentBuilder.parse(pomFile);
Element rootElement = document.getDocumentElement();
NodeList versionNodeList = rootElement.getElementsByTagName("version");

if (versionNodeList.getLength() > 0) {
Node versionNode = versionNodeList.item(0);
return "AiLabar " + versionNode.getTextContent();
} else {
return "No se encontró la versión en el pom.xml";
}

} catch (Exception e) {
return e.getMessage();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public GroupsModel getGroup(GroupsModel groupsModel) {
List<String> membersList = new ArrayList<>();
membersIdList.forEach(id -> {
try {
//membersList.add(groupsRepositoryPort.getUserNameEMailByUserId(id));
membersList.add(groupsRepositoryPort.getUserNameByUserId(id));
} catch (GetGroupException getGroupException) {
throw new GetGroupException("An error occurred while retrieving group members");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,7 @@ public interface GroupsRepositoryPort {

String getUserNameByUserId(Integer id);

String getUserNameEMailByUserId(Integer id);

void insertMember(Integer groupId, Integer userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ public String getUserNameByUserId(Integer id) {
return groupsRepository.getUserNameByUserId(id);
}

@Override
public String getUserNameEMailByUserId(Integer id) {
return groupsRepository.getUserNameEMailByUserId(id);
}
@Override
public void insertMember(Integer groupId, Integer userId) {
groupsRepository.insertMember(groupId, userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public interface GroupsRepository extends JpaRepository<GroupsEntity, Integer> {

@Query("SELECT u.user FROM UsersEntity u WHERE u.id = :id")
String getUserNameByUserId(@Param("id") Integer id);

@Query("SELECT CONCAT(u.user, ' (', u.email, ')') FROM UsersEntity u WHERE u.id = :id")
String getUserNameEMailByUserId(@Param("id") Integer id);
@Modifying
@Query(value = "INSERT INTO members (group_id, user_id) VALUES (:groupId, :userId)", nativeQuery = true)
void insertMember(@Param("groupId") Integer groupId, @Param("userId") Integer userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
import java.util.List;

@Service
public class UsersService implements LoginUseCase, CreateUserUseCase, EditUserUseCase, DeleteUserUseCase,
GetUsersByMatchUseCase, EditVisualizationUseCase, GetAllUsersUseCase, GetUsersDatabaseUseCase,
EditLanguageUseCase, LogoutUseCase {
public class UsersService implements LoginUseCase, AdminAccessUseCase, CreateUserUseCase, EditUserUseCase,
DeleteUserUseCase, GetUsersByMatchUseCase, EditVisualizationUseCase, GetAllUsersUseCase,
GetUsersDatabaseUseCase, EditLanguageUseCase, LogoutUseCase {
private final LoginUseCase loginUseCase;

private final AdminAccessUseCase adminAccessUseCase;
private final CreateUserUseCase createUserUseCase;
private final EditUserUseCase editUserUseCase;
private final DeleteUserUseCase deleteUserUseCase;
Expand All @@ -23,12 +25,14 @@ public class UsersService implements LoginUseCase, CreateUserUseCase, EditUserUs
private final GetUsersDatabaseUseCase getUsersDatabaseUseCase;
private final LogoutUseCase logoutUseCase;

public UsersService(LoginUseCase loginUseCase, CreateUserUseCase createUserUseCase,
EditUserUseCase editUserUseCase, DeleteUserUseCase deleteUserUseCase,
GetUsersByMatchUseCase getUsersByMatch, EditVisualizationUseCase editVisualizationUseCase,
GetAllUsersUseCase getAllUsersUseCase, GetUsersDatabaseUseCase getUsersDatabaseUseCase ,
EditLanguageUseCase editLanguageUseCase, LogoutUseCase logoutUseCase) {
public UsersService(LoginUseCase loginUseCase, AdminAccessUseCase adminAccessUseCase,
CreateUserUseCase createUserUseCase, EditUserUseCase editUserUseCase,
DeleteUserUseCase deleteUserUseCase, GetUsersByMatchUseCase getUsersByMatch,
EditVisualizationUseCase editVisualizationUseCase, GetAllUsersUseCase getAllUsersUseCase,
GetUsersDatabaseUseCase getUsersDatabaseUseCase , EditLanguageUseCase editLanguageUseCase,
LogoutUseCase logoutUseCase) {
this.loginUseCase = loginUseCase;
this.adminAccessUseCase = adminAccessUseCase;
this.createUserUseCase = createUserUseCase;
this.editUserUseCase = editUserUseCase;
this.deleteUserUseCase = deleteUserUseCase;
Expand All @@ -48,6 +52,15 @@ public List<String> login(UsersModel usersModel, PrivateKey privateKey) {
}
}

@Override
public void adminAccess(UsersModel usersModel) {
try {
adminAccessUseCase.adminAccess(usersModel);
} catch (AdminAccessException adminAccessException) {
throw adminAccessException;
}
}

@Override
public void createUser(UsersModel usersModel) {
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.capgemini.ailabar.users.application.usecases;

import com.capgemini.ailabar.users.domain.exceptions.AdminAccessException;
import com.capgemini.ailabar.users.domain.models.UsersModel;
import com.capgemini.ailabar.users.domain.ports.in.AdminAccessUseCase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AdminAccessUseCaseImpl implements AdminAccessUseCase {
@Value("${admin.access}")
private String adminPass;

@Override
public void adminAccess(UsersModel usersModel) {
if(usersModel.getPassword().isBlank()) {
throw new AdminAccessException("Password is required");
}

if (Boolean.FALSE.equals(usersModel.getPassword().equals(adminPass))) {
throw new AdminAccessException("Wrong Password");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ public void editUser(UsersModel usersModel) {
throw new EditUserException("The new username already exists");
}

if (Boolean.TRUE.equals(usersRepositoryPort.checkEmail(usersModel.getEmail()))) {
throw new EditUserException("The email already exists");
}

UsersEntity userEntity = usersRepositoryPort.getUserByName(usersModel.getUser());

if(usersModel.getNewUser() != null && !usersModel.getNewUser().isBlank()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.capgemini.ailabar.users.application.usecases;

import com.capgemini.ailabar.commons.utils.DateTime;
import com.capgemini.ailabar.users.domain.exceptions.CreateUserException;
import com.capgemini.ailabar.users.domain.exceptions.LoginException;
import com.capgemini.ailabar.users.domain.models.UsersModel;
import com.capgemini.ailabar.users.domain.ports.in.LoginUseCase;
Expand Down Expand Up @@ -70,14 +71,33 @@ public List<String> login(UsersModel usersModel, PrivateKey privateKey) {
private String loginCap(UsersModel usersModel) {
JSONObject jsonObject = requestToCapgemini(usersModel);

if(!usersRepositoryPort.checkUser(usersModel.getUser())) {
createCapgeminiUser(usersModel, jsonObject);
JSONObject decodedClaims = readJWT(jsonObject);

String userSubName = decodedClaims.getString("sub");
String email = decodedClaims.getString("email");

if(!usersRepositoryPort.checkEmail(email)) {
// Descomentar cuando se quiera volver a registrar a los usuarios con el primer login en la aplicación
//createCapgeminiUser(usersModel, jsonObject);
throw new LoginException("Unauthorized user in the application");
}

String token = jsonObject.getString("token");

UsersEntity usersEntity = usersRepositoryPort.getUserByName(usersModel.getUser());
usersRepositoryPort.updateToken(usersEntity.getId(), token);
UsersEntity usersEntity = usersRepositoryPort.getUserByEmail(email);
if(usersEntity != null) {
if (Boolean.TRUE.equals(usersRepositoryPort.checkUser(userSubName)) && !userSubName.equals(usersModel.getUser())) {
throw new CreateUserException("The user already exists");
}

try {
usersRepositoryPort.updateUserNameAndToken(usersEntity.getId(), userSubName, token);
} catch (Exception e) {
throw new LoginException("Error updating user during login");
}
} else {
throw new LoginException("User not found");
}

return token;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.capgemini.ailabar.users.domain.exceptions;

public class AdminAccessException extends RuntimeException {
public AdminAccessException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.capgemini.ailabar.users.domain.ports.in;

import com.capgemini.ailabar.users.domain.models.UsersModel;

public interface AdminAccessUseCase {
void adminAccess(UsersModel usersModel);
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.capgemini.ailabar.users.domain.ports.out;

import com.capgemini.ailabar.users.infraestructure.entities.UsersEntity;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UsersRepositoryPort {
boolean checkAuthorization(String user, String token);

boolean checkEmail(String email);
boolean checkEmail(String user);

boolean checkUser(String user);

Expand All @@ -18,6 +17,8 @@ public interface UsersRepositoryPort {

List<String> getAllUsers();

UsersEntity getUserByEmail(String email);

UsersEntity getUserByName(String user);

List<String> getUsersByMatch(String matcher);
Expand All @@ -28,7 +29,7 @@ public interface UsersRepositoryPort {

void deleteMembersByUserId(Integer userId);

void updateToken(@Param("userId") Integer userId, @Param("newToken") String newToken);
void updateUserNameAndToken(Integer userId, String user, String newToken);

boolean login(String user, String password);
boolean login(String email, String password);
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ public List<String> getAllUsers() {
return usersRepository.getAllUsers();
}

@Override
public UsersEntity getUserByEmail(String email) {
return usersRepository.getUserByEmail(email);
}

@Override
public UsersEntity getUserByName(String user) {
return usersRepository.getUserByName(user);
Expand All @@ -71,8 +76,8 @@ public void deleteMembersByUserId(Integer userId) {
}

@Override
public void updateToken(Integer userId, String newToken) {
usersRepository.updateToken(userId, newToken);
public void updateUserNameAndToken(Integer userId, String user, String newToken) {
usersRepository.updateUserNameAndToken(userId, user, newToken);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ public ResponseEntity<SpecialResponse> login(@RequestBody UsersModel usersModel)
return new ResponseEntity<>(specialResponse(loginData, responseJson), HttpStatus.OK);
}

/*
* METHOD TO ACCESS USER CREATION
*/
@PostMapping("/adminAccess")
public ResponseEntity<SpecialResponse> adminAccess(@RequestBody UsersModel usersModel) {
JSONObject responseJson = new JSONObject();
usersService.adminAccess(usersModel);
responseJson.put("message", "Admin access successful");
return new ResponseEntity<>(specialResponse(null, responseJson), HttpStatus.OK);
}

/*
* CREATES A USER IN THE DATABASE:
* 1. In this case, the password should arrive encrypted with SHA256 from the frontend. In the backend, the password will be re-encrypted in SHA256, and a token will be generated with the user's unique name, password, and ID.
Expand Down Expand Up @@ -195,6 +206,13 @@ ResponseEntity<SpecialResponse> handlerLoginException (LoginException loginExcep
return new ResponseEntity<>(specialResponse(null, responseJson), HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(AdminAccessException.class)
ResponseEntity<SpecialResponse> handlerAdminAccessException (AdminAccessException adminAccessException){
JSONObject responseJson = new JSONObject();
responseJson.put("message", adminAccessException.getMessage());
return new ResponseEntity<>(specialResponse(null, responseJson), HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(CreateUserException.class)
ResponseEntity<SpecialResponse> handlerCreateUserException (CreateUserException createUserException){
JSONObject responseJson = new JSONObject();
Expand Down
Loading

0 comments on commit 825b7a2

Please sign in to comment.