修改实体类名称,并且使用链式编码

This commit is contained in:
YuCheng Hu 2022-10-02 08:53:01 -04:00
parent 9afb93a4fc
commit 854c747911
5 changed files with 108 additions and 110 deletions

View File

@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; 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.RoleRepository;
import com.ossez.spring.security.repository.UserRepository; import com.ossez.spring.security.repository.UserRepository;
@ -36,94 +36,96 @@ import com.ossez.spring.security.repository.UserRepository;
@RestController @RestController
@RequestMapping("/custom") @RequestMapping("/custom")
public class AuthController { public class AuthController {
@Autowired @Autowired
AuthenticationManager authenticationManager; AuthenticationManager authenticationManager;
@Autowired @Autowired
UserRepository userRepository; UserRepository userRepository;
@Autowired @Autowired
RoleRepository roleRepository; RoleRepository roleRepository;
@Autowired @Autowired
PasswordEncoder encoder; PasswordEncoder encoder;
@Autowired @Autowired
JwtUtils jwtUtils; JwtUtils jwtUtils;
@PostMapping("/signin") @PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate( Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication); String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt, UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
userDetails.getId(), List<String> roles = userDetails.getAuthorities().stream()
userDetails.getUsername(), .map(item -> item.getAuthority())
userDetails.getEmail(), .collect(Collectors.toList());
roles));
}
@PostMapping("/register") return ResponseEntity.ok(new JwtResponse(jwt,
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) { userDetails.getId(),
if (userRepository.existsByUsername(signUpRequest.getUsername())) { userDetails.getUsername(),
return ResponseEntity userDetails.getEmail(),
.badRequest() roles));
.body(new MessageResponse("Error: Username is already taken!"));
} }
if (userRepository.existsByEmail(signUpRequest.getEmail())) { @PostMapping("/register")
return ResponseEntity public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
.badRequest() if (userRepository.existsByUsername(signUpRequest.getUsername())) {
.body(new MessageResponse("Error: Email is already in use!")); return ResponseEntity
} .badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
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);
} }
});
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<String> strRoles = signUpRequest.getRole();
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);
}
});
}
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!"));
}
} }

View File

@ -1,47 +1,43 @@
package com.ossez.spring.security.models.entity; package com.ossez.spring.security.models.entity;
import lombok.Data; import lombok.Data;
import lombok.experimental.Accessors;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.Email; import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
/**
* Person Entity
* @author YuCheng Hu
*/
@Entity @Entity
@Table(name = "users", uniqueConstraints = {@UniqueConstraint(columnNames = "username"), @UniqueConstraint(columnNames = "email")}) @Data()
@Data @Accessors(chain = true)
public class User { @Table(name = "Person", uniqueConstraints = {@UniqueConstraint(columnNames = "username"), @UniqueConstraint(columnNames = "email")})
public class Person {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@NotBlank @NotBlank
@Size(max = 20) @Size(max = 20)
private String username; private String userName;
@NotBlank
@Size(max = 120)
private String userPassword;
@NotBlank @NotBlank
@Size(max = 50) @Size(max = 50)
@Email @Email
private String email; private String userEmail;
@NotBlank
@Size(max = 120)
private String password;
@ManyToMany(fetch = FetchType.LAZY) @ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>(); private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
} }

View File

@ -5,11 +5,11 @@ import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import com.ossez.spring.security.models.entity.User; import com.ossez.spring.security.models.entity.Person;
@Repository @Repository
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<Person, Long> {
Optional<User> findByUsername(String username); Optional<Person> findByUsername(String username);
Boolean existsByUsername(String username); Boolean existsByUsername(String username);

View File

@ -9,7 +9,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; 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; import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails { public class UserDetailsImpl implements UserDetails {
@ -35,16 +35,16 @@ public class UserDetailsImpl implements UserDetails {
this.authorities = authorities; this.authorities = authorities;
} }
public static UserDetailsImpl build(User user) { public static UserDetailsImpl build(Person user) {
List<GrantedAuthority> authorities = user.getRoles().stream() List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name())) .map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList()); .collect(Collectors.toList());
return new UserDetailsImpl( return new UserDetailsImpl(
user.getId(), user.getId(),
user.getUsername(), user.getUserName(),
user.getEmail(), user.getUserEmail(),
user.getPassword(), user.getUserPassword(),
authorities); authorities);
} }

View File

@ -7,7 +7,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; 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; import com.ossez.spring.security.repository.UserRepository;
@Service @Service
@ -18,7 +18,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override @Override
@Transactional @Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 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)); .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user); return UserDetailsImpl.build(user);