新增user服务和gateway服务
This commit is contained in:
113
timeline-user-service/pom.xml
Normal file
113
timeline-user-service/pom.xml
Normal file
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.timeline</groupId>
|
||||
<artifactId>timeline</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>timeline-user-service</artifactId>
|
||||
<name>timeline-user-service</name>
|
||||
<description>User management service for timeline system</description>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring Boot -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Cloud -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- JWT -->
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.11.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.11.5</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.11.5</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- 公共模块 -->
|
||||
<dependency>
|
||||
<groupId>com.timeline</groupId>
|
||||
<artifactId>timeline-component-common</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 数据库相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>3.0.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>8.2.0</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- 工具类 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
spring.application.name=timeline.user
|
||||
server.port=30003
|
||||
|
||||
# ?????
|
||||
spring.datasource.url=jdbc:mysql://8.137.148.196:33306/timeline?serverTimezone=UTC&allowPublicKeyRetrieval=true
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=your_password
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
# MyBatis ??
|
||||
mybatis.mapper-locations=classpath:mapper/*.xml
|
||||
mybatis.type-aliases-package=com.timeline.user.entity
|
||||
mybatis.configuration.mapUnderscoreToCamelCase=true
|
||||
|
||||
# JWT ??
|
||||
jwt.secret=timelineSecretKey
|
||||
jwt.expiration=86400
|
||||
|
||||
# ????
|
||||
logging.level.com.timeline.user=DEBUG
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
|
||||
<mapper namespace="com.timeline.user.dao.UserMapper">
|
||||
|
||||
<insert id="insert" parameterType="com.timeline.user.entity.User">
|
||||
INSERT INTO user (user_id, username, password, nickname, email, phone, status, is_deleted, create_time, update_time)
|
||||
VALUES (#{userId}, #{username}, #{password}, #{nickname}, #{email}, #{phone}, #{status}, #{isDeleted}, #{createTime}, #{updateTime})
|
||||
</insert>
|
||||
|
||||
<select id="selectById" resultType="com.timeline.user.entity.User">
|
||||
SELECT * FROM user WHERE id = #{id} AND is_deleted = 0
|
||||
</select>
|
||||
|
||||
<select id="selectByUserId" resultType="com.timeline.user.entity.User">
|
||||
SELECT * FROM user WHERE user_id = #{userId} AND is_deleted = 0
|
||||
</select>
|
||||
|
||||
<select id="selectByUsername" resultType="com.timeline.user.entity.User">
|
||||
SELECT * FROM user WHERE username = #{username} AND is_deleted = 0
|
||||
</select>
|
||||
|
||||
<update id="update" parameterType="com.timeline.user.entity.User">
|
||||
UPDATE user
|
||||
SET username = #{username},
|
||||
email = #{email},
|
||||
phone = #{phone},
|
||||
status = #{status},
|
||||
update_time = #{updateTime}
|
||||
WHERE user_id = #{userId} AND is_deleted = 0
|
||||
</update>
|
||||
|
||||
<update id="deleteByUserId">
|
||||
UPDATE user SET is_deleted = 1, update_time = NOW() WHERE user_id = #{userId}
|
||||
</update>
|
||||
</mapper>
|
||||
Reference in New Issue
Block a user