admin_basic

Change-Id: I16f1cd5785730b22e6e1e3fb4905f546ef0b555d
diff --git a/src/main/java/com/example/g8backend/config/SecurityConfig.java b/src/main/java/com/example/g8backend/config/SecurityConfig.java
index 179d95f..82c9946 100644
--- a/src/main/java/com/example/g8backend/config/SecurityConfig.java
+++ b/src/main/java/com/example/g8backend/config/SecurityConfig.java
@@ -1,26 +1,20 @@
 package com.example.g8backend.config;
 
+import com.example.g8backend.filter.JwtAuthenticationFilter;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import com.example.g8backend.filter.JwtAuthenticationFilter;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 import org.springframework.security.web.SecurityFilterChain;
 import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
 
-
 @Configuration
 @EnableWebSecurity
 public class SecurityConfig {
-    @Bean
-    public BCryptPasswordEncoder passwordEncoder() {
-        return new BCryptPasswordEncoder();
-    }
-
     private final JwtAuthenticationFilter jwtAuthenticationFilter;
 
     public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
@@ -28,15 +22,28 @@
     }
 
     @Bean
+    public BCryptPasswordEncoder passwordEncoder() {
+        return new BCryptPasswordEncoder();
+    }
+
+    @Bean
     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
         return http
-            .csrf(AbstractHttpConfigurer::disable)
-            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
-            .build();
+                .csrf(AbstractHttpConfigurer::disable)
+                .authorizeHttpRequests(auth -> auth
+                        // 管理员接口需ADMIN角色
+                        .requestMatchers("/admin/**").hasRole("ADMIN")
+                        // 用户签到接口需认证
+                        .requestMatchers("/user/signin").authenticated()
+                        // 其他请求允许匿名访问(感觉这里应该还需要做修改,暂时先放着)
+                        .anyRequest().permitAll()
+                )
+                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
+                .build();
     }
 
     @Bean
     public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
         return config.getAuthenticationManager();
     }
-}
+}
\ No newline at end of file
diff --git a/src/main/java/com/example/g8backend/controller/AdminController.java b/src/main/java/com/example/g8backend/controller/AdminController.java
new file mode 100644
index 0000000..89208c6
--- /dev/null
+++ b/src/main/java/com/example/g8backend/controller/AdminController.java
@@ -0,0 +1,23 @@
+package com.example.g8backend.controller;
+
+import com.example.g8backend.service.AdminService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/admin")
+public class AdminController {
+    @Autowired
+    private AdminService adminService;
+
+    @PostMapping("/grant-vip/{userId}")
+    @PreAuthorize("hasRole('ADMIN')") // 仅允许管理员访问
+    public String grantVip(@PathVariable Long userId) {
+        boolean success = adminService.grantVip(userId);
+        return success ? "VIP授予成功" : "操作失败(用户不存在)";
+    }
+}
\ No newline at end of file
diff --git a/src/main/java/com/example/g8backend/entity/User.java b/src/main/java/com/example/g8backend/entity/User.java
index 4c4a465..0645824 100644
--- a/src/main/java/com/example/g8backend/entity/User.java
+++ b/src/main/java/com/example/g8backend/entity/User.java
@@ -22,6 +22,7 @@
     private String userLevel;      // 用户等级(lv1/lv2/lv3/vip)
     private Integer signinCount;
     private LocalDate lastSigninDate;
+    private String role;
 
     @Override
     public String toString() {
diff --git a/src/main/java/com/example/g8backend/service/AdminService.java b/src/main/java/com/example/g8backend/service/AdminService.java
new file mode 100644
index 0000000..1f84eec
--- /dev/null
+++ b/src/main/java/com/example/g8backend/service/AdminService.java
@@ -0,0 +1,5 @@
+package com.example.g8backend.service;
+
+public interface AdminService {
+    boolean grantVip(Long targetUserId);
+}
\ No newline at end of file
diff --git a/src/main/java/com/example/g8backend/service/impl/AdminServiceImpl.java b/src/main/java/com/example/g8backend/service/impl/AdminServiceImpl.java
new file mode 100644
index 0000000..d3be9fe
--- /dev/null
+++ b/src/main/java/com/example/g8backend/service/impl/AdminServiceImpl.java
@@ -0,0 +1,26 @@
+package com.example.g8backend.service.impl;
+
+import com.example.g8backend.entity.User;
+import com.example.g8backend.mapper.UserMapper;
+import com.example.g8backend.service.AdminService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@RequiredArgsConstructor
+public class AdminServiceImpl implements AdminService {
+    private final UserMapper userMapper;
+
+    @Override
+    @Transactional
+    public boolean grantVip(Long targetUserId) {
+        User user = userMapper.selectById(targetUserId);
+        if (user == null) {
+            return false; // 用户不存在
+        }
+        user.setUserLevel("vip");
+        userMapper.updateById(user);
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index 944d880..19ff0b5 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -21,3 +21,5 @@
 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
 
 logging.level.org.springframework.data.redis= DEBUG
+
+spring.security.user.role-prefix=
diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql
index 051ce5e..4a3621e 100644
--- a/src/main/resources/schema.sql
+++ b/src/main/resources/schema.sql
@@ -8,6 +8,7 @@
   `user_level` ENUM('lv1', 'lv2', 'lv3', 'vip') DEFAULT 'lv1',
   `signin_count` INT DEFAULT 0,
   `last_signin_date` DATE,
+  `role` ENUM('USER', 'ADMIN') DEFAULT 'USER' COMMENT '用户角色',
   INDEX `idx_user_level` (`user_level`)  -- 按等级查询优化
 );
 -- 用户统计表
diff --git a/src/test/java/com/example/g8backend/service/AdminServiceImplTest.java b/src/test/java/com/example/g8backend/service/AdminServiceImplTest.java
new file mode 100644
index 0000000..f8e6229
--- /dev/null
+++ b/src/test/java/com/example/g8backend/service/AdminServiceImplTest.java
@@ -0,0 +1,38 @@
+package com.example.g8backend.service;
+
+import com.example.g8backend.entity.User;
+import com.example.g8backend.mapper.UserMapper;
+import com.example.g8backend.service.impl.AdminServiceImpl;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+@ExtendWith(MockitoExtension.class)
+public class AdminServiceImplTest {
+    @Mock
+    private UserMapper userMapper;
+    @InjectMocks
+    private AdminServiceImpl adminService;
+
+    @Test
+    public void testGrantVip_Success() {
+        User user = new User();
+        user.setUserId(1L);
+        when(userMapper.selectById(1L)).thenReturn(user);
+
+        boolean result = adminService.grantVip(1L);
+        assertTrue(result);
+        assertEquals("vip", user.getUserLevel());
+    }
+
+    @Test
+    public void testGrantVip_UserNotFound() {
+        when(userMapper.selectById(1L)).thenReturn(null);
+        boolean result = adminService.grantVip(1L);
+        assertFalse(result);
+    }
+}
\ No newline at end of file