Files
OneKeyCallVideoTablet/src/main/java/com/onekeycall/videotablet/controller/LoginController.java

190 lines
7.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.onekeycall.videotablet.controller;
import com.onekeycall.videotablet.dto.TokenPair;
import com.onekeycall.videotablet.entity.User;
import com.onekeycall.videotablet.result.Result;
import com.onekeycall.videotablet.service.UserService;
import com.onekeycall.videotablet.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/public")
public class LoginController {
private final UserService userService;
private final AuthenticationManager authenticationManager;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private JwtUtil jwtUtil;
@Autowired
public LoginController(UserService userService, AuthenticationManager authenticationManager) {
this.userService = userService;
this.authenticationManager = authenticationManager;
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody RegisterRequest registerRequest) {
try {
userService.registerUser(registerRequest.getUsername(), registerRequest.getPassword());
return new ResponseEntity<>("User registered successfully", HttpStatus.CREATED);
} catch (RuntimeException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@PostMapping("/phone_login")
public Result phoneLogin(
@RequestHeader("Device-ID") String deviceId,
@RequestParam String phone, @RequestParam String password) {
User user = userService.getUserByPhone(phone);
if (user == null) {
return Result.error().message("User not found with phone: " + phone);
}
String userId = user.getUserId();
// 1. 创建认证令牌
Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userId, password);
try {
// 2. 使用 AuthenticationManager 进行认证(核心步骤)
Authentication authentication = authenticationManager.authenticate(authenticationToken);
// 3. 认证成功后生成 JWT
User userDetails = (User) authentication.getPrincipal();
TokenPair tokenPair = jwtUtil.generateTokenPair(userDetails.getUserId(), deviceId);
// 4. 返回 Token
return Result.ok().data(Collections.singletonMap("token", tokenPair.toMap()));
} catch (Exception e) {
e.printStackTrace();
return Result.error().message("登录失败");
}
}
@PostMapping("/login")
public ResponseEntity<?> login(
@RequestHeader("Device-ID") String deviceId,
@RequestParam(value = "user_id") String userId, @RequestParam String password) {
// 1. 创建认证令牌
Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userId, password);
// 2. 使用 AuthenticationManager 进行认证(核心步骤)
Authentication authentication = authenticationManager.authenticate(authenticationToken);
// 3. 认证成功后生成 JWT
User userDetails = (User) authentication.getPrincipal();
TokenPair tokenPair = jwtUtil.generateTokenPair(userDetails.getUserId(), deviceId);
// 4. 返回 Token
return ResponseEntity.ok(Collections.singletonMap("token", tokenPair.toMap()));
}
// 注册请求参数类
public static class RegisterRequest {
private String username;
private String password;
// Getters and Setters
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@PostMapping("/phone_register")
public Result registerByPhone(
@RequestParam String phone, @RequestParam String code,
@RequestParam(value = "verify_key") String verifyKey, @RequestParam(value = "device_id") String deviceId) {
//
// if (TextUtils.isEmpty(verifyKey)) {
// return Result.error().message("verify key is empty", HttpStatus.BAD_REQUEST);
// }
Map<String, Object> map = (Map<String, Object>) redisTemplate.opsForValue().get(phone);
if (map != null) {
String redisVerifyKey = (String) map.get("verifyKey");
if (!Objects.equals(redisVerifyKey, verifyKey)) {
return Result.error().message("verify key is not same");
}
String redisCode = map.get("code").toString();
if (!Objects.equals(redisCode, code)) {
return Result.error().message("code is not same");
}
try {
User user = userService.registerByPhone(phone, code, deviceId, new Date());
TokenPair tokenPair = jwtUtil.generateTokenPair(user.getUserId(), deviceId);
//返回给app保存access_token用来加入header请求接口refresh_token用来更换access_token
Map<String, Object> tokenMap = new HashMap<>();
tokenMap.put("new_user", user.isNewUser());
tokenMap.put("user_id", user.getUserId());
tokenMap.put("has_password", user.isHasPassword());
tokenMap.put("token", tokenPair.toMap());
return Result.ok().data(tokenMap);
} catch (RuntimeException e) {
return Result.error().message(e.getMessage());
} finally {
redisTemplate.delete(phone);
}
} else {
return Result.error().message("verify key is expired");
}
}
@PostMapping("/phone_code_login")
public Result loginByPhoneCode(
@RequestParam String phone, @RequestParam String code,
@RequestParam(value = "verify_key") String verifyKey, @RequestParam(value = "device_id") String deviceId) {
Map<String, Object> map = (Map<String, Object>) redisTemplate.opsForValue().get(phone);
if (map != null) {
String redisVerifyKey = (String) map.get("verifyKey");
if (!Objects.equals(redisVerifyKey, verifyKey)) {
return Result.error().message("verify key is not same");
}
String redisCode = map.get("code").toString();
if (!Objects.equals(redisCode, code)) {
return Result.error().message("code is not same");
}
try {
User user = userService.loginByPhone(phone, code);
// 生成并返回JWT令牌实际项目中需要实现JWT逻辑
TokenPair tokenPair = jwtUtil.generateTokenPair(user.getUserId(), deviceId);
Map<String, Object> tokenMap = new HashMap<>();
tokenMap.put("new_user", user.isNewUser());
tokenMap.put("user_id", user.getUserId());
tokenMap.put("has_password", user.isHasPassword());
tokenMap.put("token", tokenPair.toMap());
return Result.ok().data(tokenMap);
} catch (RuntimeException e) {
return Result.error().message(e.getMessage());
}
} else {
return Result.error().message("verify key is expired");
}
}
}