今天主要會記錄註冊功能的 API 實作,跟登入比較不一樣要特別注意的是,註冊要做 username 的唯一性檢查,如果有重複則不能使用該名稱新增資料內容。以下是實做的內容:
在 payload 這個 package 中建立 RegisterDto.class
建立註冊時會需要用到的資料,如此才能跟 DB 做對應
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class RegisterDto {
private String name;
private String username;
private String email;
private String password;
}
在 service package 中新增在 payload 中 register DTO 的功能
public interface AuthService {
String login(LoginDto loginDto);
String register(RegisterDto registerDto);
}
建立實際使用的功能,在 AuthServiceImpl.java 中新增 register:
@Serive
public class AuthServiceImpl implements AuthService{
private AuthentictionManager authenticationManager;
private UserRepository userRepository;
private RoleRepository roleRepository;
private PasswordEncoder passwordEncoder; // spring framework 的模組
//public AuthServiceImpl(AuthenticationManager authticationManager){
// this.authenticationManager = authenticationManager ;
//}
public AuthServiceImpl(AuthenticationManager authticationManager,
UserRepository userRepository,RoleRepository roleRepository,
PasswordEncoder passwordEncoder){
this.authenticationManager = authenticationManager ;
this.userRepository= userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public String login(LoginDto loginDto) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthticationToken(
loginDto.getUsernameOrEmail(),loginDto.getPassword()));
// 引入 spring framework 中的模組
SecurityContextHolder.getContext().setAuthentication(authentication);
return "User login successfully";
}
@Override
public String register(RegisterDto registerDto){
// 確認 username 是否已經存在在 DB 中
if(userRepository.existsByUsername(registerDto.getUsername())){
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Username is alredy exists!");
}
// 確認 email 是否有存在
if(userRepository.existsByEmail(registerDto.getEmail())){
throw new BlogAPIException(HttpStatus.BAD_REQUEST, "Email is alredy exists!");
}
User user = new User();
user.setName(registerDto.getName());
user.setUsername(registerDto.getUsername());
user.setEmail(registerDto.getEmail());
user.setPassword(passwordEncode.encode(registerDto.getPassword()));
Set<Role> roles = new HashSet<>();
Role userRole = roleRepository.findByName("ROLE_USER").get();
roles.add(userRole);
user.setRoles(roles);
userRepository.save(user);
return "User registered successfully";
}
}
這裡是 url 的建立
@PostMapping(value={"/register","signup"})
public RespositoryEntity<String> register(RegisterDto registerDto){
String response = authService.register(registerDto);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
使用 http://localhost:8080/api/auth/register ,選用 POST 這個 method
在測試要發送的資料要包含註冊的欄位內容,如下去做測試,看是否能夠真的註冊會員
{
"name" :"Emily",
"username" : "Emily",
"email": "emily@gmail.com",
"password":"123"
}
今天的API 註冊功能實作就先記錄到這裡!
有任何問題歡迎留言一起討論~ 明天見~