新增user服务和gateway服务
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
package com.timeline.user;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan({"com.timeline", "com.timeline.user"})
|
||||
public class TimelineUserServiceApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TimelineUserServiceApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.timeline.user.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "jwt")
|
||||
public class JwtConfig {
|
||||
private String secret = "timelineSecretKey";
|
||||
private Long expiration = 86400L; // 24小时
|
||||
|
||||
// Getters and setters
|
||||
public String getSecret() {
|
||||
return secret;
|
||||
}
|
||||
|
||||
public void setSecret(String secret) {
|
||||
this.secret = secret;
|
||||
}
|
||||
|
||||
public Long getExpiration() {
|
||||
return expiration;
|
||||
}
|
||||
|
||||
public void setExpiration(Long expiration) {
|
||||
this.expiration = expiration;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.timeline.user.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.timeline.user.config;
|
||||
|
||||
import com.timeline.user.interceptor.UserContextInterceptor;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private UserContextInterceptor userContextInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(userContextInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
.excludePathPatterns("/api/auth/login", "/api/auth/register");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.timeline.user.controller;
|
||||
|
||||
import com.timeline.common.response.ResponseEntity;
|
||||
import com.timeline.user.dto.LoginRequest;
|
||||
import com.timeline.user.dto.LoginResponse;
|
||||
import com.timeline.user.dto.RegisterRequest;
|
||||
import com.timeline.user.entity.User;
|
||||
import com.timeline.user.service.UserService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
|
||||
log.info("用户登录请求: {}", loginRequest.getUsername());
|
||||
LoginResponse response = userService.login(loginRequest);
|
||||
return ResponseEntity.success(response);
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<User> register(@RequestBody RegisterRequest registerRequest) {
|
||||
log.info("用户注册请求: {}", registerRequest.getUsername());
|
||||
User user = userService.register(registerRequest);
|
||||
return ResponseEntity.success(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.timeline.user.controller;
|
||||
|
||||
import com.timeline.common.response.ResponseEntity;
|
||||
import com.timeline.user.service.UserService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/permission")
|
||||
public class PermissionController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@GetMapping("/check")
|
||||
public ResponseEntity<Boolean> checkUserPermission(
|
||||
@RequestParam String userId,
|
||||
@RequestParam String requiredPermission) {
|
||||
log.info("检查用户权限: userId={}, requiredPermission={}", userId, requiredPermission);
|
||||
boolean hasPermission = userService.checkUserPermission(userId, requiredPermission);
|
||||
return ResponseEntity.success(hasPermission);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.timeline.user.controller;
|
||||
|
||||
import com.timeline.common.response.ResponseEntity;
|
||||
import com.timeline.user.dto.RegisterRequest;
|
||||
import com.timeline.user.entity.User;
|
||||
import com.timeline.user.service.UserService;
|
||||
import com.timeline.user.utils.UserContext;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/user")
|
||||
public class UserController {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@GetMapping("/info")
|
||||
public ResponseEntity<User> getCurrentUserInfo() {
|
||||
String userId = UserContext.getCurrentUserId();
|
||||
log.info("获取当前用户信息: {}", userId);
|
||||
User user = userService.getUserByUserId(userId);
|
||||
return ResponseEntity.success(user);
|
||||
}
|
||||
|
||||
@PutMapping("/info")
|
||||
public ResponseEntity<User> updateUserInfo(@RequestBody RegisterRequest updateRequest) {
|
||||
String userId = UserContext.getCurrentUserId();
|
||||
log.info("更新用户信息: {}", userId);
|
||||
User user = userService.updateUserInfo(userId, updateRequest);
|
||||
return ResponseEntity.success(user);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public ResponseEntity<String> deleteUser() {
|
||||
String userId = UserContext.getCurrentUserId();
|
||||
log.info("删除用户: {}", userId);
|
||||
userService.deleteUser(userId);
|
||||
return ResponseEntity.success("用户删除成功");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.timeline.user.dao;
|
||||
|
||||
import com.timeline.user.entity.User;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface UserMapper {
|
||||
void insert(User user);
|
||||
User selectById(Long id);
|
||||
User selectByUserId(String userId);
|
||||
User selectByUsername(String username);
|
||||
void update(User user);
|
||||
void deleteByUserId(String userId);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.timeline.user.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.timeline.user.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class LoginResponse {
|
||||
private String token;
|
||||
private String userId;
|
||||
private String username;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.timeline.user.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class RegisterRequest {
|
||||
private String username;
|
||||
private String nickname;
|
||||
private String password;
|
||||
private String email;
|
||||
private String phone;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.timeline.user.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class User {
|
||||
private Long id;
|
||||
private String userId;
|
||||
private String username;
|
||||
private String password;
|
||||
private String nickname;
|
||||
private String email;
|
||||
private String phone;
|
||||
private Integer status; // 0-正常,1-禁用
|
||||
private Integer isDeleted; // 0-未删除,1-已删除
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime createTime;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.timeline.user.interceptor;
|
||||
|
||||
import com.timeline.user.entity.User;
|
||||
import com.timeline.user.service.UserService;
|
||||
import com.timeline.user.utils.JwtUtils;
|
||||
import com.timeline.user.utils.UserContext;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
@Component
|
||||
public class UserContextInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
String token = request.getHeader("Authorization");
|
||||
if (token != null && token.startsWith("Bearer ")) {
|
||||
token = token.substring(7);
|
||||
if (jwtUtils.validateToken(token) && !jwtUtils.isTokenExpired(token)) {
|
||||
String userId = jwtUtils.getUserIdFromToken(token);
|
||||
User user = userService.getUserByUserId(userId);
|
||||
if (user != null) {
|
||||
UserContext.setUser(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
UserContext.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.timeline.user.service;
|
||||
|
||||
import com.timeline.user.entity.User;
|
||||
import com.timeline.user.dto.LoginRequest;
|
||||
import com.timeline.user.dto.RegisterRequest;
|
||||
import com.timeline.user.dto.LoginResponse;
|
||||
|
||||
public interface UserService {
|
||||
LoginResponse login(LoginRequest loginRequest);
|
||||
User register(RegisterRequest registerRequest);
|
||||
User getUserByUserId(String userId);
|
||||
User updateUserInfo(String userId, RegisterRequest updateRequest);
|
||||
void deleteUser(String userId);
|
||||
boolean checkUserPermission(String userId, String requiredPermission);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.timeline.user.service.impl;
|
||||
|
||||
import com.timeline.common.constants.CommonConstants;
|
||||
import com.timeline.common.exception.CustomException;
|
||||
import com.timeline.common.response.ResponseEnum;
|
||||
import com.timeline.common.utils.IdUtils;
|
||||
import com.timeline.user.dao.UserMapper;
|
||||
import com.timeline.user.entity.User;
|
||||
import com.timeline.user.dto.LoginRequest;
|
||||
import com.timeline.user.dto.RegisterRequest;
|
||||
import com.timeline.user.dto.LoginResponse;
|
||||
import com.timeline.user.service.UserService;
|
||||
import com.timeline.user.utils.JwtUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Override
|
||||
public LoginResponse login(LoginRequest loginRequest) {
|
||||
try {
|
||||
User user = userMapper.selectByUsername(loginRequest.getUsername());
|
||||
if (user == null) {
|
||||
throw new CustomException(ResponseEnum.UNAUTHORIZED, "用户名或密码错误");
|
||||
}
|
||||
|
||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
|
||||
throw new CustomException(ResponseEnum.UNAUTHORIZED, "用户名或密码错误");
|
||||
}
|
||||
|
||||
if (user.getStatus() == 1) {
|
||||
throw new CustomException(ResponseEnum.FORBIDDEN, "用户已被禁用");
|
||||
}
|
||||
|
||||
String token = jwtUtils.generateToken(user.getUserId(), user.getUsername());
|
||||
return new LoginResponse(token, user.getUserId(), user.getUsername());
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("用户登录失败", e);
|
||||
throw new CustomException(ResponseEnum.INTERNAL_SERVER_ERROR, "登录失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public User register(RegisterRequest registerRequest) {
|
||||
try {
|
||||
// 检查用户名是否已存在
|
||||
User existingUser = userMapper.selectByUsername(registerRequest.getUsername());
|
||||
if (existingUser != null) {
|
||||
throw new CustomException(ResponseEnum.BAD_REQUEST, "用户名已存在");
|
||||
}
|
||||
|
||||
User user = new User();
|
||||
user.setUserId(IdUtils.randomUuidUpper());
|
||||
user.setUsername(registerRequest.getUsername());
|
||||
user.setNickname(registerRequest.getNickname());
|
||||
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
|
||||
user.setEmail(registerRequest.getEmail());
|
||||
user.setPhone(registerRequest.getPhone());
|
||||
user.setStatus(CommonConstants.USER_STATUS_NORMAL); // 正常状态
|
||||
user.setIsDeleted(CommonConstants.NOT_DELETED);
|
||||
user.setCreateTime(LocalDateTime.now());
|
||||
user.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
userMapper.insert(user);
|
||||
return user;
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("用户注册失败", e);
|
||||
throw new CustomException(ResponseEnum.INTERNAL_SERVER_ERROR, "注册失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public User getUserByUserId(String userId) {
|
||||
return userMapper.selectByUserId(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public User updateUserInfo(String userId, RegisterRequest updateRequest) {
|
||||
try {
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new CustomException(ResponseEnum.NOT_FOUND, "用户不存在");
|
||||
}
|
||||
|
||||
user.setEmail(updateRequest.getEmail());
|
||||
user.setPhone(updateRequest.getPhone());
|
||||
user.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
userMapper.update(user);
|
||||
return user;
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("更新用户信息失败", e);
|
||||
throw new CustomException(ResponseEnum.INTERNAL_SERVER_ERROR, "更新用户信息失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteUser(String userId) {
|
||||
try {
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
if (user == null) {
|
||||
throw new CustomException(ResponseEnum.NOT_FOUND, "用户不存在");
|
||||
}
|
||||
|
||||
userMapper.deleteByUserId(userId);
|
||||
} catch (CustomException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.error("删除用户失败", e);
|
||||
throw new CustomException(ResponseEnum.INTERNAL_SERVER_ERROR, "删除用户失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkUserPermission(String userId, String requiredPermission) {
|
||||
// 这里可以实现更复杂的权限检查逻辑
|
||||
// 简单示例:检查用户是否存在
|
||||
User user = userMapper.selectByUserId(userId);
|
||||
return user != null && user.getStatus() == 0; // 用户存在且未被禁用
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.timeline.user.utils;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@Value("${jwt.secret:timelineSecretKey}")
|
||||
private String secret;
|
||||
|
||||
@Value("${jwt.expiration:86400}")
|
||||
private Long expiration;
|
||||
|
||||
public String generateToken(String userId, String username) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("userId", userId);
|
||||
claims.put("username", username);
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(username)
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
|
||||
.signWith(SignatureAlgorithm.HS512, secret)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims getClaimsFromToken(String token) {
|
||||
return Jwts.parser()
|
||||
.setSigningKey(secret)
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
public String getUserIdFromToken(String token) {
|
||||
return getClaimsFromToken(token).get("userId", String.class);
|
||||
}
|
||||
|
||||
public String getUsernameFromToken(String token) {
|
||||
return getClaimsFromToken(token).getSubject();
|
||||
}
|
||||
|
||||
public boolean validateToken(String token) {
|
||||
try {
|
||||
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenExpired(String token) {
|
||||
Date expiration = getClaimsFromToken(token).getExpiration();
|
||||
return expiration.before(new Date());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.timeline.user.utils;
|
||||
|
||||
import com.timeline.user.entity.User;
|
||||
|
||||
public class UserContext {
|
||||
private static final ThreadLocal<User> userHolder = new ThreadLocal<>();
|
||||
|
||||
public static void setUser(User user) {
|
||||
userHolder.set(user);
|
||||
}
|
||||
|
||||
public static User getCurrentUser() {
|
||||
return userHolder.get();
|
||||
}
|
||||
|
||||
public static String getCurrentUserId() {
|
||||
User user = getCurrentUser();
|
||||
return user != null ? user.getUserId() : null;
|
||||
}
|
||||
|
||||
public static String getCurrentUsername() {
|
||||
User user = getCurrentUser();
|
||||
return user != null ? user.getUsername() : null;
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
userHolder.remove();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user