Explorar el Código

feat: 创建项目

DingXiaoYu hace 2 años
padre
commit
02766392ba

+ 5 - 0
pom.xml

@@ -42,6 +42,11 @@
 			<artifactId>spring-boot-starter-test</artifactId>
 			<scope>test</scope>
 		</dependency>
+		<dependency>
+			<groupId>com.auth0</groupId>
+			<artifactId>java-jwt</artifactId>
+			<version>3.10.3</version>
+		</dependency>
 	</dependencies>
 
 	<build>

+ 29 - 0
src/main/java/com/seecoder/BlueWhale/Configure/LoginInterceptor.java

@@ -0,0 +1,29 @@
+package com.seecoder.BlueWhale.Configure;
+
+import com.seecoder.BlueWhale.Exception.BlueWhaleException;
+import com.seecoder.BlueWhale.Util.TokenUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.HandlerInterceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@Component
+public class LoginInterceptor implements HandlerInterceptor {
+
+    @Autowired
+    TokenUtil tokenUtil;
+
+    @Override
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
+        String token = request.getHeader("token");
+        if (token != null && tokenUtil.verifyToken(token)) {
+            request.getSession().setAttribute("currentUser",tokenUtil.getUser(token));
+            return true;
+        }else {
+            throw BlueWhaleException.notLogin();
+        }
+    }
+
+}

+ 20 - 0
src/main/java/com/seecoder/BlueWhale/Configure/MyWebMvcConfig.java

@@ -0,0 +1,20 @@
+package com.seecoder.BlueWhale.Configure;
+
+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 MyWebMvcConfig implements WebMvcConfigurer {
+    @Autowired
+    LoginInterceptor loginInterceptor;
+
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(loginInterceptor)
+                .addPathPatterns("/**")
+                .excludePathPatterns("/api/user/register")
+                .excludePathPatterns("/api/user/login")
+                .order(1);
+    }
+}

+ 10 - 4
src/main/java/com/seecoder/BlueWhale/Controller/UserController.java

@@ -1,18 +1,19 @@
 package com.seecoder.BlueWhale.Controller;
 
 import com.seecoder.BlueWhale.Service.UserService;
+import com.seecoder.BlueWhale.Util.SecurityUtil;
 import com.seecoder.BlueWhale.VO.ResultVO;
 import com.seecoder.BlueWhale.VO.UserVO;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 @RestController
 @RequestMapping("/api/user")
 public class UserController {
 
+    @Autowired
+    SecurityUtil securityUtil;
+
     @Autowired
     UserService userService;
 
@@ -20,4 +21,9 @@ public class UserController {
     public ResultVO<Boolean> register(@RequestBody UserVO userVO){
         return ResultVO.buildSuccess(userService.register(userVO));
     }
+
+    @GetMapping("/test")
+    public String a(){
+        return securityUtil.getCurrentUser().getRole().toString();
+    }
 }

+ 4 - 0
src/main/java/com/seecoder/BlueWhale/Exception/BlueWhaleException.java

@@ -8,4 +8,8 @@ public class BlueWhaleException extends RuntimeException{
     public static BlueWhaleException phoneAlreadyExists(){
         return new BlueWhaleException("手机号已经存在!");
     }
+
+    public static BlueWhaleException notLogin(){
+        return new BlueWhaleException("未登录");
+    }
 }

+ 18 - 0
src/main/java/com/seecoder/BlueWhale/Util/SecurityUtil.java

@@ -0,0 +1,18 @@
+package com.seecoder.BlueWhale.Util;
+
+import com.seecoder.BlueWhale.PO.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+
+@Component
+public class SecurityUtil {
+
+    @Autowired
+    HttpServletRequest httpServletRequest;
+
+    public User getCurrentUser(){
+        return (User)httpServletRequest.getSession().getAttribute("currentUser");
+    }
+}

+ 44 - 0
src/main/java/com/seecoder/BlueWhale/Util/TokenUtil.java

@@ -0,0 +1,44 @@
+package com.seecoder.BlueWhale.Util;
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.JWTVerifier;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.seecoder.BlueWhale.Mapper.UserMapper;
+import com.seecoder.BlueWhale.PO.User;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.Date;
+
+@Component
+public class TokenUtil {
+    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
+
+    @Autowired
+    UserMapper userMapper;
+
+    public String getToken(User user) {
+        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
+        return JWT.create()
+                .withAudience(String.valueOf(user.getId()))
+                .withExpiresAt(date)
+                .sign(Algorithm.HMAC256(user.getPassword()));
+    }
+
+    public boolean verifyToken(String token) {
+        try {
+            Integer userId=Integer.parseInt(JWT.decode(token).getAudience().get(0));
+            User user= userMapper.findById(userId).get();
+            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
+            jwtVerifier.verify(token);
+            return true;
+        }catch (Exception e){
+            return false;
+        }
+    }
+
+    public User getUser(String token){
+        Integer userId=Integer.parseInt(JWT.decode(token).getAudience().get(0));
+        return userMapper.findById(userId).get();
+    }
+}

+ 8 - 1
src/main/resources/application.yml

@@ -3,6 +3,13 @@ spring:
     url: jdbc:mysql://localhost:3306/BlueWhale
     username: root
     password: 123456
+  jpa:
+    hibernate:
+      ddl-auto: update
+    show-sql: true
+    open-in-view: true
 
 server:
-  port: 8080
+  port: 8080
+
+

+ 12 - 0
src/test/java/com/seecoder/BlueWhale/BlueWhaleApplicationTests.java

@@ -1,13 +1,25 @@
 package com.seecoder.BlueWhale;
 
+import com.seecoder.BlueWhale.Enums.RoleEnum;
+import com.seecoder.BlueWhale.PO.User;
+import com.seecoder.BlueWhale.Util.TokenUtil;
 import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 
 @SpringBootTest
 class BlueWhaleApplicationTests {
 
+	@Autowired
+	TokenUtil tokenUtil;
+
 	@Test
 	void contextLoads() {
+		User user=new User();
+		user.setId(1);
+		user.setPassword("123456");
+		user.setRole(RoleEnum.CUSTOMER);
+		System.out.println(tokenUtil.getToken(user));
 	}
 
 }

+ 14 - 5
注意事项.md

@@ -6,8 +6,17 @@
 5. 找到`BlueWhaleApplication`类,启动成功即可。
 
 ## 2. 了解项目结构
-1. 了解`Spring Boot`的后端三层架构,了解项目结构,了解每个包的作用,以及`Spring Boot`的`约定大于配置`的思想。
-2. 了解`Spring Boot`的`IOC`(控制反转)的思想。
-3. 熟知一些注解的作用:
-4. 了解`JPA`框架的使用。
-5. 
+1. 了解`Spring Boot`的后端三层架构。
+2. 了解项目结构,了解每个包的作用,以及`Spring Boot`的`约定大于配置`的思想。
+3. 了解`Spring Boot`的`IOC`(控制反转)的思想。
+4. 了解`JPA`框架。
+
+## 3. 了解项目细节
+### 1. Controller层
+### 2. Service层
+### 3. Mapper层
+### 4. VO和PO
+### 5. 用户认证与token
+### 6. 处理Exception
+### 7. 枚举类的处理
+### 8. 跨域问题处理