From 854c7479114546174a997aa51e6058d676db852d Mon Sep 17 00:00:00 2001 From: YuCheng Hu Date: Sun, 2 Oct 2022 08:53:01 -0400 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=9E=E4=BD=93=E7=B1=BB?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=EF=BC=8C=E5=B9=B6=E4=B8=94=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E9=93=BE=E5=BC=8F=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../security/controllers/AuthController.java | 158 +++++++++--------- .../models/entity/{User.java => Person.java} | 40 ++--- .../security/repository/UserRepository.java | 6 +- .../security/services/UserDetailsImpl.java | 10 +- .../services/UserDetailsServiceImpl.java | 4 +- 5 files changed, 108 insertions(+), 110 deletions(-) rename src/main/java/com/ossez/spring/security/models/entity/{User.java => Person.java} (61%) diff --git a/src/main/java/com/ossez/spring/security/controllers/AuthController.java b/src/main/java/com/ossez/spring/security/controllers/AuthController.java index 16862e5..34b431c 100644 --- a/src/main/java/com/ossez/spring/security/controllers/AuthController.java +++ b/src/main/java/com/ossez/spring/security/controllers/AuthController.java @@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.ossez.spring.security.models.entity.User; +import com.ossez.spring.security.models.entity.Person; import com.ossez.spring.security.repository.RoleRepository; import com.ossez.spring.security.repository.UserRepository; @@ -36,94 +36,96 @@ import com.ossez.spring.security.repository.UserRepository; @RestController @RequestMapping("/custom") public class AuthController { - @Autowired - AuthenticationManager authenticationManager; + @Autowired + AuthenticationManager authenticationManager; - @Autowired - UserRepository userRepository; + @Autowired + UserRepository userRepository; - @Autowired - RoleRepository roleRepository; + @Autowired + RoleRepository roleRepository; - @Autowired - PasswordEncoder encoder; + @Autowired + PasswordEncoder encoder; - @Autowired - JwtUtils jwtUtils; + @Autowired + JwtUtils jwtUtils; - @PostMapping("/signin") - public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { + @PostMapping("/signin") + public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { - Authentication authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); + Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); - SecurityContextHolder.getContext().setAuthentication(authentication); - String jwt = jwtUtils.generateJwtToken(authentication); - - UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); - List roles = userDetails.getAuthorities().stream() - .map(item -> item.getAuthority()) - .collect(Collectors.toList()); + SecurityContextHolder.getContext().setAuthentication(authentication); + String jwt = jwtUtils.generateJwtToken(authentication); - return ResponseEntity.ok(new JwtResponse(jwt, - userDetails.getId(), - userDetails.getUsername(), - userDetails.getEmail(), - roles)); - } + UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); + List roles = userDetails.getAuthorities().stream() + .map(item -> item.getAuthority()) + .collect(Collectors.toList()); - @PostMapping("/register") - public ResponseEntity registerUser(@Valid @RequestBody SignupRequest signUpRequest) { - if (userRepository.existsByUsername(signUpRequest.getUsername())) { - return ResponseEntity - .badRequest() - .body(new MessageResponse("Error: Username is already taken!")); + return ResponseEntity.ok(new JwtResponse(jwt, + userDetails.getId(), + userDetails.getUsername(), + userDetails.getEmail(), + roles)); } - if (userRepository.existsByEmail(signUpRequest.getEmail())) { - return ResponseEntity - .badRequest() - .body(new MessageResponse("Error: Email is already in use!")); - } - - // Create new user's account - User user = new User(signUpRequest.getUsername(), - signUpRequest.getEmail(), - encoder.encode(signUpRequest.getPassword())); - - Set strRoles = signUpRequest.getRole(); - Set 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); + @PostMapping("/register") + public ResponseEntity registerUser(@Valid @RequestBody SignupRequest signUpRequest) { + if (userRepository.existsByUsername(signUpRequest.getUsername())) { + 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!")); + } + + // Create new user's account + Person person = new Person() + .setUserEmail(signUpRequest.getUsername()) + .setUserPassword(encoder.encode(signUpRequest.getPassword())) + .setUserEmail(signUpRequest.getEmail()); + + + Set strRoles = signUpRequest.getRole(); + Set 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); + } + }); + } + + person.setRoles(roles); + userRepository.save(person); + + return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } - - user.setRoles(roles); - userRepository.save(user); - - return ResponseEntity.ok(new MessageResponse("User registered successfully!")); - } } diff --git a/src/main/java/com/ossez/spring/security/models/entity/User.java b/src/main/java/com/ossez/spring/security/models/entity/Person.java similarity index 61% rename from src/main/java/com/ossez/spring/security/models/entity/User.java rename to src/main/java/com/ossez/spring/security/models/entity/Person.java index 85a9a1c..3da198a 100644 --- a/src/main/java/com/ossez/spring/security/models/entity/User.java +++ b/src/main/java/com/ossez/spring/security/models/entity/Person.java @@ -1,47 +1,43 @@ package com.ossez.spring.security.models.entity; import lombok.Data; - -import java.util.HashSet; -import java.util.Set; +import lombok.experimental.Accessors; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; +import java.util.HashSet; +import java.util.Set; + +/** + * Person Entity + * @author YuCheng Hu + */ @Entity -@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = "username"), @UniqueConstraint(columnNames = "email")}) -@Data -public class User { +@Data() +@Accessors(chain = true) +@Table(name = "Person", uniqueConstraints = {@UniqueConstraint(columnNames = "username"), @UniqueConstraint(columnNames = "email")}) +public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Size(max = 20) - private String username; + private String userName; + + @NotBlank + @Size(max = 120) + private String userPassword; @NotBlank @Size(max = 50) @Email - private String email; - - @NotBlank - @Size(max = 120) - private String password; + private String userEmail; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set roles = new HashSet<>(); - - public User() { - } - - public User(String username, String email, String password) { - this.username = username; - this.email = email; - this.password = password; - } - } diff --git a/src/main/java/com/ossez/spring/security/repository/UserRepository.java b/src/main/java/com/ossez/spring/security/repository/UserRepository.java index 4242f97..4d2ea68 100644 --- a/src/main/java/com/ossez/spring/security/repository/UserRepository.java +++ b/src/main/java/com/ossez/spring/security/repository/UserRepository.java @@ -5,11 +5,11 @@ import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import com.ossez.spring.security.models.entity.User; +import com.ossez.spring.security.models.entity.Person; @Repository -public interface UserRepository extends JpaRepository { - Optional findByUsername(String username); +public interface UserRepository extends JpaRepository { + Optional findByUsername(String username); Boolean existsByUsername(String username); diff --git a/src/main/java/com/ossez/spring/security/security/services/UserDetailsImpl.java b/src/main/java/com/ossez/spring/security/security/services/UserDetailsImpl.java index 7ac5d93..0a0e15b 100644 --- a/src/main/java/com/ossez/spring/security/security/services/UserDetailsImpl.java +++ b/src/main/java/com/ossez/spring/security/security/services/UserDetailsImpl.java @@ -9,7 +9,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; -import com.ossez.spring.security.models.entity.User; +import com.ossez.spring.security.models.entity.Person; import com.fasterxml.jackson.annotation.JsonIgnore; public class UserDetailsImpl implements UserDetails { @@ -35,16 +35,16 @@ public class UserDetailsImpl implements UserDetails { this.authorities = authorities; } - public static UserDetailsImpl build(User user) { + public static UserDetailsImpl build(Person user) { List authorities = user.getRoles().stream() .map(role -> new SimpleGrantedAuthority(role.getName().name())) .collect(Collectors.toList()); return new UserDetailsImpl( user.getId(), - user.getUsername(), - user.getEmail(), - user.getPassword(), + user.getUserName(), + user.getUserEmail(), + user.getUserPassword(), authorities); } diff --git a/src/main/java/com/ossez/spring/security/security/services/UserDetailsServiceImpl.java b/src/main/java/com/ossez/spring/security/security/services/UserDetailsServiceImpl.java index 3db7947..353c7d6 100644 --- a/src/main/java/com/ossez/spring/security/security/services/UserDetailsServiceImpl.java +++ b/src/main/java/com/ossez/spring/security/security/services/UserDetailsServiceImpl.java @@ -7,7 +7,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import com.ossez.spring.security.models.entity.User; +import com.ossez.spring.security.models.entity.Person; import com.ossez.spring.security.repository.UserRepository; @Service @@ -18,7 +18,7 @@ public class UserDetailsServiceImpl implements UserDetailsService { @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - User user = userRepository.findByUsername(username) + Person user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username)); return UserDetailsImpl.build(user);