-
Notifications
You must be signed in to change notification settings - Fork 40
feature: add user login and signup functions #244
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
...nd/api-gateway/src/main/java/com/datamate/gateway/application/UserApplicationService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| package com.datamate.gateway.application; | ||
|
|
||
| import com.datamate.gateway.domain.entity.User; | ||
| import com.datamate.gateway.domain.service.UserService; | ||
| import com.datamate.gateway.interfaces.dto.LoginRequest; | ||
| import com.datamate.gateway.interfaces.dto.LoginResponse; | ||
| import com.datamate.gateway.interfaces.dto.RegisterRequest; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| /** | ||
| * UserApplicationServices | ||
| * | ||
| * @since 2026/1/14 | ||
| */ | ||
| @Slf4j | ||
| @Service | ||
| @Transactional | ||
| @RequiredArgsConstructor | ||
| public class UserApplicationService { | ||
| private final UserService userService; | ||
|
|
||
| public Optional<LoginResponse> login(LoginRequest loginRequest) { | ||
| User user = new User(); | ||
| user.setUsername(loginRequest.getUsername()); | ||
| user.setPassword(loginRequest.getPassword()); | ||
|
|
||
| Optional<User> authenticatedUser = userService.authenticate(user); | ||
| if (authenticatedUser.isPresent()) { | ||
| User userEntity = authenticatedUser.get(); | ||
| return Optional.of(convertToLoginResponse(userEntity)); | ||
| } | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| /** | ||
| * Register a new user | ||
| * | ||
| * @param registerRequest registration request | ||
| * @return LoginResponse with user details and token if registration successful, empty otherwise | ||
| */ | ||
| public Optional<LoginResponse> register(RegisterRequest registerRequest) { | ||
| return userService.register(registerRequest) | ||
| .map(this::convertToLoginResponse); | ||
| } | ||
|
|
||
| private LoginResponse convertToLoginResponse(User user) { | ||
| return LoginResponse.builder() | ||
| .id(user.getId()) | ||
| .username(user.getUsername()) | ||
| .email(user.getEmail()) | ||
| .token(user.getToken()) | ||
| .build(); | ||
| } | ||
| } |
46 changes: 46 additions & 0 deletions
46
backend/api-gateway/src/main/java/com/datamate/gateway/common/config/JwtConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package com.datamate.gateway.common.config; | ||
|
|
||
| import jakarta.annotation.PostConstruct; | ||
| import lombok.Getter; | ||
| import lombok.Setter; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| /** | ||
| * JwtConfig | ||
| * | ||
| * @since 2026/1/14 | ||
| */ | ||
| @Getter | ||
| @Setter | ||
| @Slf4j | ||
| @Configuration | ||
| @ConfigurationProperties(prefix = "datamate.jwt") | ||
| public class JwtConfig { | ||
| private String secret; | ||
|
|
||
| @PostConstruct | ||
| public void validate() { | ||
| if (secret == null || secret.trim().isEmpty()) { | ||
| throw new IllegalStateException( | ||
| """ | ||
| JWT secret is required. Please configure datamate.jwt.secret | ||
| Options: | ||
| 1. Add to application.yml: | ||
| datamate: | ||
| jwt: | ||
| secret: your-strong-secret-key-here | ||
| 2. Set environment variable: | ||
| export JWT_SECRET=your-strong-secret-key-here | ||
| 3. Run with system property: | ||
| -Ddatamate.jwt.secret=your-strong-secret-key-here""" | ||
| ); | ||
| } | ||
|
|
||
| // 额外验证 | ||
| if (secret.length() < 32) { | ||
| log.warn("\n⚠️ JWT secret is only {} characters. For security, use at least 32 characters.\n", secret.length()); | ||
| } | ||
| } | ||
| } |
25 changes: 25 additions & 0 deletions
25
backend/api-gateway/src/main/java/com/datamate/gateway/common/config/SecurityConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package com.datamate.gateway.common.config; | ||
|
|
||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; | ||
| import org.springframework.security.config.web.server.ServerHttpSecurity; | ||
| import org.springframework.security.web.server.SecurityWebFilterChain; | ||
|
|
||
| /** | ||
| * 安全配置 - 暂时禁用所有认证 | ||
| */ | ||
| @Configuration | ||
| @EnableWebFluxSecurity | ||
| public class SecurityConfig { | ||
|
|
||
| @Bean | ||
| public SecurityWebFilterChain filterChain(ServerHttpSecurity http) throws Exception { | ||
| http.csrf(ServerHttpSecurity.CsrfSpec::disable) | ||
|
||
| .authorizeExchange(exchange -> | ||
| exchange.pathMatchers("**").permitAll() // 允许所有请求无需认证 | ||
| ); | ||
|
|
||
| return http.build(); | ||
| } | ||
| } | ||
83 changes: 83 additions & 0 deletions
83
backend/api-gateway/src/main/java/com/datamate/gateway/common/filter/UserContextFilter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package com.datamate.gateway.common.filter; | ||
|
|
||
| import com.datamate.common.infrastructure.common.Response; | ||
| import com.datamate.common.infrastructure.exception.CommonErrorCode; | ||
| import com.datamate.gateway.domain.service.UserService; | ||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.cloud.gateway.filter.GatewayFilterChain; | ||
| import org.springframework.cloud.gateway.filter.GlobalFilter; | ||
| import org.springframework.core.io.buffer.DataBuffer; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.http.server.reactive.ServerHttpRequest; | ||
| import org.springframework.http.server.reactive.ServerHttpResponse; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.server.ServerWebExchange; | ||
| import reactor.core.publisher.Mono; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
|
|
||
| /** | ||
| * 用户信息过滤器 | ||
| * | ||
| */ | ||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class UserContextFilter implements GlobalFilter { | ||
| private static final String AUTH_HEADER = "Authorization"; | ||
|
|
||
| private static final String TOKEN_PREFIX = "Bearer "; | ||
|
|
||
| private final UserService userService; | ||
|
|
||
| @Value("${datamate.jwt.enable:false}") | ||
| private Boolean jwtEnable; | ||
|
|
||
| @Override | ||
| public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { | ||
| ServerHttpRequest request = exchange.getRequest(); | ||
| String path = request.getURI().getPath(); | ||
| if (path.equals("/api/user/login") || path.equals("/api/user/signup")) { | ||
| return chain.filter(exchange); | ||
| } | ||
| try { | ||
| if (!jwtEnable) { | ||
| return chain.filter(exchange); | ||
| } | ||
| // Get token from Authorization header | ||
| String authHeader = request.getHeaders().getFirst(AUTH_HEADER); | ||
| if (authHeader == null || !authHeader.startsWith(TOKEN_PREFIX)) { | ||
| return sendUnauthorizedResponse(exchange); | ||
| } | ||
| String token = authHeader.substring(TOKEN_PREFIX.length()); | ||
| if (!userService.validateToken(token)) { | ||
| return sendUnauthorizedResponse(exchange); | ||
| } | ||
| return chain.filter(exchange); | ||
| } catch (Exception e) { | ||
| log.error("get current user info error", e); | ||
| return sendUnauthorizedResponse(exchange); | ||
| } | ||
| } | ||
|
|
||
| private Mono<Void> sendUnauthorizedResponse(ServerWebExchange exchange) { | ||
| ServerHttpResponse response = exchange.getResponse(); | ||
| response.setStatusCode(HttpStatus.UNAUTHORIZED); | ||
| response.getHeaders().setContentType(MediaType.APPLICATION_JSON); | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| byte[] bytes; | ||
| try { | ||
| bytes = objectMapper.writeValueAsString(Response.error(CommonErrorCode.UNAUTHORIZED)).getBytes(StandardCharsets.UTF_8); | ||
| } catch (JsonProcessingException e) { | ||
| String responseBody = "{\"code\":401,\"message\":\"登录失败:用户名或密码错误\",\"data\":null}"; | ||
| bytes = responseBody.getBytes(StandardCharsets.UTF_8); | ||
| } | ||
| DataBuffer buffer = response.bufferFactory().wrap(bytes); | ||
| return response.writeWith(Mono.just(buffer)); | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
backend/api-gateway/src/main/java/com/datamate/gateway/domain/entity/User.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| package com.datamate.gateway.domain.entity; | ||
|
|
||
| import com.baomidou.mybatisplus.annotation.TableField; | ||
| import com.baomidou.mybatisplus.annotation.TableName; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import lombok.Setter; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| /** | ||
| * 用户 | ||
| * | ||
| * @since 2026/1/12 | ||
| */ | ||
| @Getter | ||
| @Setter | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| @TableName(value = "users", autoResultMap = true) | ||
| public class User { | ||
| private Long id; | ||
| private String username; | ||
| private String email; | ||
| private String passwordHash; | ||
| private String fullName; | ||
| private String role; | ||
| private boolean enabled; | ||
| private LocalDateTime lastLoginAt; | ||
|
|
||
| @TableField(exist = false) | ||
| private String password; | ||
|
|
||
| @TableField(exist = false) | ||
| private String token; | ||
| } |
12 changes: 12 additions & 0 deletions
12
backend/api-gateway/src/main/java/com/datamate/gateway/domain/repository/UserRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.datamate.gateway.domain.repository; | ||
|
|
||
| import com.baomidou.mybatisplus.extension.repository.IRepository; | ||
| import com.datamate.gateway.domain.entity.User; | ||
|
|
||
| /** | ||
| * UserRepository | ||
| * | ||
| * @since 2026/1/12 | ||
| */ | ||
| public interface UserRepository extends IRepository<User> { | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.