Skip to content

Commit

Permalink
🔀 Merge pull request #24 from FusionTech-2430/develop
Browse files Browse the repository at this point in the history
🚀 Release v1.0
  • Loading branch information
Estebans441 authored Nov 5, 2024
2 parents 142d541 + a55190c commit d95add9
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 29 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public UsersController(UserService userService) {

@PostMapping
public ResponseEntity<?> createUser(
@ModelAttribute UserCreateDTO user,
@ModelAttribute UserDTO user,
@RequestParam(value = "photo", required = false) MultipartFile photo) {
try {
UserDTO userDTO = userService.createUser(user, photo);
Expand All @@ -34,6 +34,20 @@ public ResponseEntity<?> createUser(
}
}

@PostMapping("/from-admin")
public ResponseEntity<?> createUserFromAdmin(
@ModelAttribute UserCreateDTO user,
@RequestParam(value = "photo", required = false) MultipartFile photo) {
try {
UserDTO userDTO = userService.createUserFromAdmin(user, photo);
return ResponseEntity.status(HttpStatus.CREATED).body(userDTO);
} catch (OperationException e) {
return ResponseEntity.status(e.getCode()).body(new Response(e.getCode(), e.getMessage()));
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new Response(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()));
}
}

@PostMapping("/guest")
public ResponseEntity<?> createGuestUser() {
try {
Expand Down Expand Up @@ -77,8 +91,11 @@ public ResponseEntity<?> updateUser(
@ModelAttribute UserCreateDTO user,
@RequestParam(value = "photo", required = false) MultipartFile photo) {
try {
System.out.println("Actualizando usuario");
UserDTO userDTO = userService.updateUser(id, user, photo);
return ResponseEntity.status(HttpStatus.OK).body(userDTO);
ResponseEntity<UserDTO> response = ResponseEntity.status(HttpStatus.OK).body(userDTO);
System.out.println(response.getHeaders());
return response;
} catch (OperationException e) {
return ResponseEntity.status(e.getCode()).body(new Response(e.getCode(), e.getMessage()));
} catch (RuntimeException e) {
Expand Down Expand Up @@ -106,6 +123,16 @@ public ResponseEntity<?> deactivateUser(@PathVariable String id, @RequestBody De
}
}

@PostMapping("/{id}/activate")
public ResponseEntity<?> activateUser(@PathVariable String id) {
try {
UserDTO user = userService.activateUser(id);
return ResponseEntity.status(HttpStatus.OK).body(user);
} catch (OperationException e) {
return ResponseEntity.status(e.getCode()).body(new Response(e.getCode(), e.getMessage()));
}
}

@PostMapping("/{id}/roles")
public ResponseEntity<?> addRole(@PathVariable String id, @RequestBody RolesDTO roles) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ public class UserDTO {
private String mail;
private String photo_url;
private String[] roles;
private String[] organizations;
private boolean active;

public UserDTO(User user){
Expand All @@ -26,7 +25,6 @@ public UserDTO(User user){
this.mail = user.getMail();
this.photo_url = user.getPhotoUrl();
this.roles = user.getRoles().stream().map(Rol::getIdRol).toArray(String[]::new);
// this.organizations = user.getOrganizations().stream().map(Organization::getIdOrganization).toArray(String[]::new);
this.active = user.getActive();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package co.allconnected.fussiontech.usersservice.model;

import co.allconnected.fussiontech.usersservice.dtos.UserCreateDTO;
import co.allconnected.fussiontech.usersservice.dtos.UserDTO;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -23,6 +24,15 @@ public User(UserCreateDTO dto){
this.active = true;
}

public User(UserDTO dto){
this.idUser = dto.getId_user();
this.fullname = dto.getFullname();
this.username = dto.getUsername();
this.mail = dto.getMail();
this.photoUrl = dto.getMail();
this.active = true;
}

@Id
@Column(name = "id_user", nullable = false, length = 28)
private String idUser;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class FirebaseService {
Expand All @@ -27,12 +30,18 @@ public void deleteImg(String imageName) {
bucket.get("user_photos/"+imageName).delete();
}

public String createUser(String email, String password) throws FirebaseAuthException {
public String createUser(String email, String password, String[] roles) throws FirebaseAuthException {
UserRecord.CreateRequest request = new UserRecord.CreateRequest()
.setEmail(email)
.setPassword(password);

// Add custom claims
Map<String, Object> claims = new HashMap<>();
claims.put("roles", roles);

// Create user and set custom claims
UserRecord userRecord = FirebaseAuth.getInstance().createUser(request);
FirebaseAuth.getInstance().setCustomUserClaims(userRecord.getUid(), claims);
return userRecord.getUid();
}

Expand All @@ -46,6 +55,12 @@ public void disableUser(String uid) throws FirebaseAuthException {
FirebaseAuth.getInstance().updateUser(request);
}

public void enableUser(String uid) throws FirebaseAuthException {
UserRecord.UpdateRequest request = new UserRecord.UpdateRequest(uid)
.setDisabled(false);
FirebaseAuth.getInstance().updateUser(request);
}

public void updateUser(String uid, String email, String password) throws FirebaseAuthException {
UserRecord.UpdateRequest request = new UserRecord.UpdateRequest(uid);
if (email != null)
Expand All @@ -54,4 +69,9 @@ public void updateUser(String uid, String email, String password) throws Firebas
request.setPassword(password);
FirebaseAuth.getInstance().updateUser(request);
}

public void updateCustomClaims(String uid, String[] roles) throws FirebaseAuthException {
Map<String, Object> claims = new HashMap<>();
claims.put("roles", roles);
FirebaseAuth.getInstance().setCustomUserClaims(uid, claims); }
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UserService {
Expand All @@ -36,12 +38,41 @@ public UserService(UserRepository userRepository, DeletedRepository deletedRepos
this.deletedRepository = deletedRepository;
}

public UserDTO createUser(UserCreateDTO userDto, MultipartFile photo) {
public UserDTO createUser(UserDTO userDto, MultipartFile photo) {
User user = new User(userDto);
// Add roles to user
for (String rol : userDto.getRoles()) {
Optional<Rol> rolEntity = rolService.getRol(rol);
if(rolEntity.isEmpty()) throw new OperationException(404, "Rol not found");
user.getRoles().add(rolEntity.get());
}

// Update claims
try{
firebaseService.updateCustomClaims(user.getIdUser(), userDto.getRoles());
} catch (FirebaseAuthException e) {
throw new OperationException(500, "Firebase authentication error: " + e.getMessage());
}

// Upload photo to firebase
if (photo != null) {
String photoName = user.getIdUser();
String extension = FilenameUtils.getExtension(photo.getOriginalFilename());
try{
user.setPhotoUrl(firebaseService.uploadImg(photoName, extension, photo));
} catch (IOException e) {
throw new OperationException(500, "Error uploading photo: " + e.getMessage());
}
}
return new UserDTO(userRepository.save(user));
}

public UserDTO createUserFromAdmin(UserCreateDTO userDto, MultipartFile photo) {
User user = new User(userDto);

// Create user in firebase
try {
user.setIdUser(firebaseService.createUser(userDto.mail(), userDto.password()));
user.setIdUser(firebaseService.createUser(userDto.mail(), userDto.password(), userDto.roles()));
} catch (FirebaseAuthException e) {
throw new OperationException(500, "Firebase authentication error: " + e.getMessage());
}
Expand Down Expand Up @@ -113,6 +144,20 @@ public DeletedDTO deactivateUser(String id, String reason) {
}).orElseThrow(() -> new OperationException(404, "User not found"));
}

public UserDTO activateUser(String id){
return userRepository.findById(id).map(user -> {
user.setActive(true);
user.setDeleted(null);
userRepository.save(user);
if (user.getRoles().stream().noneMatch(rol -> rol.getIdRol().equals("guest"))) try {
firebaseService.enableUser(user.getIdUser());
} catch (FirebaseAuthException e) {
throw new OperationException(500, e.getMessage());
}
return new UserDTO(user);
}).orElseThrow(() -> new OperationException(404, "User not found"));
}

public UserDTO[] getUsers(String fullname, String username, String mail, String rol, Boolean active) {
return userRepository.findUsersByFilters(fullname, username, mail, rol, active).stream()
.map(user -> user.getActive() ? new UserDTO(user) : new InactiveUserDTO(user))
Expand Down Expand Up @@ -165,13 +210,34 @@ public UserDTO addRoles(String id, String[] roles) {
Rol rolEntity = rolService.getRol(rol).orElseThrow();
user.getRoles().add(rolEntity);
}

// Update custom claims in firebase
try {
firebaseService.updateCustomClaims(user.getIdUser(), roles);
} catch (FirebaseAuthException e) {
throw new OperationException(500, "Firebase authentication error: " + e.getMessage());
}

return new UserDTO(userRepository.save(user));
}

public UserDTO removeRoles(String id, String rol) {
public UserDTO removeRoles(String id, String role) {
User user = userRepository.findById(id).orElseThrow(() -> new OperationException(404, "User not found"));
Rol rolEntity = rolService.getRol(rol).orElseThrow(() -> new OperationException(404, "Rol not found"));
Rol rolEntity = rolService.getRol(role).orElseThrow(() -> new OperationException(404, "Rol not found"));
user.getRoles().remove(rolEntity);
return new UserDTO(userRepository.save(user));
user = userRepository.save(user);

// Update custom claims in firebase
String[] roles = user.getRoles().stream()
.map(Rol::getIdRol)
.toArray(String[]::new);

try {
firebaseService.updateCustomClaims(user.getIdUser(), roles);
} catch (FirebaseAuthException e) {
throw new OperationException(500, "Firebase authentication error: " + e.getMessage());
}

return new UserDTO(user);
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ spring:
config:
import: configserver:http://${CONFIG_IP:localhost}:8888
profiles:
active: ${PROFILE:keveldev}
active: ${PROFILE:keveldev}

0 comments on commit d95add9

Please sign in to comment.