Skip to content
Snippets Groups Projects
Commit 1de7b94e authored by Paulo Pimenta's avatar Paulo Pimenta
Browse files

User Authentication API

parent 2527893d
No related branches found
No related tags found
No related merge requests found
......@@ -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));
}
}
......@@ -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() );
}
}
......@@ -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;
}
}
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;
}
}
......@@ -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;
}
}
......@@ -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() {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment