diff --git a/src/main/java/com/smartharvester/controller/SmartHarvesterAuthController.java b/src/main/java/com/smartharvester/controller/SmartHarvesterAuthController.java index 9e5a8ddf6fc5f9d39c689718e04a3833dcb97f2d..cc55db249f9ee977646358556c4828148fc85953 100644 --- a/src/main/java/com/smartharvester/controller/SmartHarvesterAuthController.java +++ b/src/main/java/com/smartharvester/controller/SmartHarvesterAuthController.java @@ -12,6 +12,7 @@ import com.smartharvester.security.services.UserService; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -42,7 +43,6 @@ public class SmartHarvesterAuthController { JwtUtils jwtUtils; @PostMapping("/signin") - @Tag(name = "Test") public ResponseEntity<?> authenticateUser(@Valid @RequestBody SignInRequest signInRequest) { Authentication authentication = authenticationManager.authenticate( @@ -51,9 +51,6 @@ public class SmartHarvesterAuthController { String jwt = jwtUtils.generateJwtToken(authentication); UserService userDetails = (UserService) authentication.getPrincipal(); - //List<String> role = userDetails.getAuthorities().stream() - // .map(item -> item.getAuthority()) - // .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), @@ -67,55 +64,17 @@ public class SmartHarvesterAuthController { if (userRepository.existsByEmail(signUpRequest.getEmail())) { return ResponseEntity .badRequest() - .body(new MessageResponse("Error: Username is already taken!")); - } - - if (userRepository.existsByEmail(signUpRequest.getEmail())) { - return ResponseEntity - .badRequest() - .body(new MessageResponse("Error: Email is already in use!")); + .body(new MessageResponse("Error: Username is already taken!",HttpStatus.BAD_REQUEST) + ); } // Create new user's account SmartHarvesterUser user = new SmartHarvesterUser(UUID.randomUUID().toString(), signUpRequest.getFirstName(), signUpRequest.getLastName(),signUpRequest.getEmail(), - encoder.encode(signUpRequest.getPassword()),signUpRequest.getRole()); - /* - Set<String> strRoles = signUpRequest.getRoles(); - Set<Role> roles = new HashSet<>(); - - if (strRoles == null) { - Role userRole = roleRepository.findByName(ERole.ROLE_USER) - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); - roles.add(userRole); - } else { - strRoles.forEach(role -> { - switch (role) { - case "admin": - Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); - roles.add(adminRole); - - break; - case "mod": - Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); - roles.add(modRole); - - break; - default: - Role userRole = roleRepository.findByName(ERole.ROLE_USER) - .orElseThrow(() -> new RuntimeException("Error: Role is not found.")); - roles.add(userRole); - } - }); - } - - user.setRoles(roles); - */ + encoder.encode(signUpRequest.getPassword())); userRepository.save(user); - return ResponseEntity.ok(new MessageResponse("User registered successfully!")); + return ResponseEntity.ok(new MessageResponse("User registered successfully!",HttpStatus.OK)); } } diff --git a/src/main/java/com/smartharvester/controller/SmartHarvesterUserController.java b/src/main/java/com/smartharvester/controller/SmartHarvesterUserController.java index 311212ff50148622b84a176465047aa67bd8f6f3..0829c11835ed9dfe899867552a5a2252e31998a9 100644 --- a/src/main/java/com/smartharvester/controller/SmartHarvesterUserController.java +++ b/src/main/java/com/smartharvester/controller/SmartHarvesterUserController.java @@ -7,14 +7,13 @@ import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; import com.smartharvester.dao.UserDaoRepository; -import com.smartharvester.exception.ResourceNotFoundException; -import com.smartharvester.model.openapi.OpenApi; import com.smartharvester.model.user.SmartHarvesterUser; import io.swagger.v3.oas.annotations.tags.Tag; import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.*; @@ -34,52 +33,28 @@ public class SmartHarvesterUserController { /** * Method to fetch all users. - * @return + * @return A collection of SmarHarversterUsers */ - @GetMapping("/allusers") - public String getAllUsers() { - MongoDatabase db = mongoTemplate.getDb(); - MongoIterable<String> names = db.listCollectionNames(); - names.forEach(n-> System.out.println("Name : " + n)); - Map<String, String> categotyLookUpMap = new HashMap<>(); - ObjectMapper objectMapper = new ObjectMapper(); - Map<String, String> users = new HashMap(); - names.forEach(n-> { - if (n.equals("user")) { - MongoCollection<Document> collection = db.getCollection(n); - FindIterable<Document> iterDoc = collection.find(); - Iterator it = iterDoc.iterator(); - while (it.hasNext()) { - Document theObj = (Document) it.next(); - System.out.println(theObj.getString("firstName")); - categotyLookUpMap.put(theObj.getString("firstName"), theObj.getString("lastName")); - } - } - }); - if (mongoTemplate.collectionExists("user")){ - System.out.println(categotyLookUpMap); - try { - String json = objectMapper.writeValueAsString(categotyLookUpMap); - System.out.println(json); - return json; - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - }; - return "No"; + @GetMapping("/allusers") + public Collection<SmartHarvesterUser> getAll2() { + List<SmartHarvesterUser> response = userDaoRepository.findAll(); + return response; } /** - * Method to fetch all users. - * @return + * Method to fetch a user by email. + * @param email The user's email + * @return An Optional SmartHarvesterUser object */ - @GetMapping("/allusers2") - public Collection<SmartHarvesterUser> getAll2() { - //logger.debug("Getting all OpenApi from database..."); - List<SmartHarvesterUser> response = userDaoRepository.findAll(); - return response; + @GetMapping("/user/{email}") + public ResponseEntity<Optional<SmartHarvesterUser>> getUserByEmail(@PathVariable("email") String email) + { + return Optional + .ofNullable( userDaoRepository.findByEmail(email) ) + .map( user -> ResponseEntity.ok().body(user) ) + .orElseGet( () -> ResponseEntity.notFound().build() ); } } diff --git a/src/main/java/com/smartharvester/model/login/request/SignupRequest.java b/src/main/java/com/smartharvester/model/login/request/SignupRequest.java index 604a9a10327c162608c05d3ab51b31016890b18d..b024229cab0ac01910c356ddd21bcef4ccc2a6f1 100644 --- a/src/main/java/com/smartharvester/model/login/request/SignupRequest.java +++ b/src/main/java/com/smartharvester/model/login/request/SignupRequest.java @@ -19,7 +19,6 @@ public class SignupRequest { private String lastName; @NotBlank private String email; - private String role; private CharSequence password; public String getFirstName() { @@ -54,11 +53,4 @@ public class SignupRequest { this.password = password; } - public String getRole() { - return this.role; - } - - public void setRole(String role) { - this.role = role; - } } diff --git a/src/main/java/com/smartharvester/model/login/response/MessageResponse.java b/src/main/java/com/smartharvester/model/login/response/MessageResponse.java index 53bfac15cb0cb504501eebab889780ce4a4257ef..66b8b66f85fcf19f40312814c8a0f692dc27611a 100644 --- a/src/main/java/com/smartharvester/model/login/response/MessageResponse.java +++ b/src/main/java/com/smartharvester/model/login/response/MessageResponse.java @@ -1,15 +1,15 @@ package com.smartharvester.model.login.response; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; -import java.util.Set; +import org.springframework.http.HttpStatus; public class MessageResponse { private String message; + private HttpStatus statusCode; - public MessageResponse(String message) { + + public MessageResponse(String message, HttpStatus statusCode) { this.message = message; + this.statusCode = statusCode; } public String getMessage() { @@ -19,4 +19,12 @@ public class MessageResponse { public void setMessage(String message) { this.message = message; } + + public HttpStatus getStatusCode() { + return statusCode; + } + + public void setStatusCode(HttpStatus statusCode) { + this.statusCode = statusCode; + } } diff --git a/src/main/java/com/smartharvester/model/user/SmartHarvesterUser.java b/src/main/java/com/smartharvester/model/user/SmartHarvesterUser.java index 0958e32866c7a6faf655ebfebd3ab54863fb1d93..bd75b42a4717f528ad62c6e1cdfb8a68fdc1df11 100644 --- a/src/main/java/com/smartharvester/model/user/SmartHarvesterUser.java +++ b/src/main/java/com/smartharvester/model/user/SmartHarvesterUser.java @@ -21,16 +21,14 @@ public class SmartHarvesterUser { private String email; @Field("passwordHash") private String password; - private String role; public SmartHarvesterUser(String uuid, String firstName, String lastName, String email, - String password, String role) { + String password) { this.firstName = firstName; this.lastName = lastName; this.uuid = uuid; this.email = email; this.password = password; - this.role = role; } public String getId() { @@ -81,11 +79,4 @@ public class SmartHarvesterUser { this.password = password; } - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } } diff --git a/src/main/java/com/smartharvester/security/services/UserService.java b/src/main/java/com/smartharvester/security/services/UserService.java index 6db92b80b558bc39875b2d099cbf0df50d1620c2..0496c98c3429d4422cb0ca18d84dba0a3aab2155 100644 --- a/src/main/java/com/smartharvester/security/services/UserService.java +++ b/src/main/java/com/smartharvester/security/services/UserService.java @@ -28,26 +28,22 @@ public class UserService implements UserDetails { private GrantedAuthority authority; - public UserService(String id, String firstName, String lastName, String email, String password, - GrantedAuthority authority) { + public UserService(String id, String firstName, String lastName, String email, String password) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; - this.authority = authority; } public static UserService build(SmartHarvesterUser user) { - GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole()); return new UserService( user.getId(), user.getFirstName(), user.getLastName(), user.getEmail(), - user.getPassword(), - authority); + user.getPassword()); } public String getId() {