ソースを参照

update login api

deason 1 年間 前
コミット
877524acfd

+ 3 - 0
src/main/java/com/qmth/exam/reserve/bean/login/LoginUser.java

@@ -17,6 +17,9 @@ public class LoginUser implements AccessEntity, IModel {
     @ApiModelProperty(value = "学校ID")
     private Long orgId;
 
+    @ApiModelProperty(value = "教学点ID")
+    private Long categoryId;
+
     @ApiModelProperty(value = "用户ID")
     private Long id;
 

+ 0 - 15
src/main/java/com/qmth/exam/reserve/cache/CacheHelper.java

@@ -1,15 +0,0 @@
-package com.qmth.exam.reserve.cache;
-
-import com.github.benmanes.caffeine.cache.Cache;
-import com.github.benmanes.caffeine.cache.Caffeine;
-import com.qmth.exam.reserve.bean.login.LoginUser;
-
-import java.util.concurrent.TimeUnit;
-
-public class CacheHelper {
-
-    public static final Cache<String, LoginUser> LOGIN_SESSION = Caffeine.newBuilder()
-            .expireAfterWrite(60, TimeUnit.MINUTES).build();
-
-
-}

+ 17 - 7
src/main/java/com/qmth/exam/reserve/cache/LoginSessionManager.java

@@ -1,22 +1,32 @@
 package com.qmth.exam.reserve.cache;
 
 import com.qmth.exam.reserve.bean.login.LoginUser;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.concurrent.TimeUnit;
 
 /**
- * 在线登录用户会话管理
+ * 登录用户会话管理
  */
+@Component
 public class LoginSessionManager {
 
-    public static LoginUser getLoginSession(String sessionId) {
-        return null;
+    private final long SESSION_TIMEOUT = 60;
+
+    @Resource
+    private RedisClient redisClient;
+
+    public LoginUser getLoginSession(String sessionId) {
+        return redisClient.get(CacheConstants.CACHE_SESSION_PREFIX + sessionId, LoginUser.class, SESSION_TIMEOUT, TimeUnit.MINUTES);
     }
 
-    public static void addLoginSession(LoginUser session) {
-        CacheHelper.LOGIN_SESSION.put(session.getSessionId(), session);
+    public void addLoginSession(LoginUser session) {
+        redisClient.set(CacheConstants.CACHE_SESSION_PREFIX + session.getSessionId(), session, SESSION_TIMEOUT, TimeUnit.MINUTES);
     }
 
-    public static void removeLoginSession(String sessionId) {
-        CacheHelper.LOGIN_SESSION.invalidate(sessionId);
+    public void removeLoginSession(String sessionId) {
+        redisClient.delete(CacheConstants.CACHE_SESSION_PREFIX + sessionId);
     }
 
 }

+ 16 - 10
src/main/java/com/qmth/exam/reserve/service/impl/AuthServiceImpl.java

@@ -8,6 +8,7 @@ import com.qmth.boot.tools.uuid.FastUUID;
 import com.qmth.exam.reserve.bean.login.LoginReq;
 import com.qmth.exam.reserve.bean.login.LoginUser;
 import com.qmth.exam.reserve.bean.login.WechatLoginReq;
+import com.qmth.exam.reserve.cache.CacheConstants;
 import com.qmth.exam.reserve.cache.LoginSessionManager;
 import com.qmth.exam.reserve.entity.StudentEntity;
 import com.qmth.exam.reserve.entity.UserEntity;
@@ -28,6 +29,9 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
 
     private final static Logger log = LoggerFactory.getLogger(AuthServiceImpl.class);
 
+    @Autowired
+    private LoginSessionManager loginSessionManager;
+
     @Autowired
     private UserService userService;
 
@@ -44,7 +48,7 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
             throw new StatusException("登录密码不能为空");
         }
 
-        log.info("[USER_LOGIN] account:{}", req.getAccount());
+        log.debug("[USER_LOGIN] account:{}", req.getAccount());
         UserEntity user = userService.findUserByLoginName(req.getOrgId(), req.getAccount());
         if (user == null) {
             throw new StatusException("登录用户不存在");
@@ -58,15 +62,16 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
         LoginUser loginUser = new LoginUser();
         loginUser.setId(user.getId());
         loginUser.setOrgId(user.getOrgId());
+        loginUser.setCategoryId(user.getCategoryId());
         loginUser.setAccount(user.getLoginName());
         loginUser.setName(user.getName());
         loginUser.setRole(user.getRole());
 
-        loginUser.setSessionId("U_" + user.getId());
+        loginUser.setSessionId(CacheConstants.CACHE_USER_LOGIN + user.getId());
         loginUser.setToken(FastUUID.get());
-        LoginSessionManager.addLoginSession(loginUser);
+        loginSessionManager.addLoginSession(loginUser);
 
-        log.info("[USER_LOGIN] account:{} {} {}", loginUser.getAccount(), loginUser.getName(), loginUser.getRole());
+        log.info("[USER_LOGIN_OK] account:{} {} {}", loginUser.getAccount(), loginUser.getName(), loginUser.getRole());
         return loginUser;
     }
 
@@ -80,7 +85,7 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
             throw new StatusException("登录密码不能为空");
         }
 
-        log.info("[STUDENT_LOGIN] account:{}", req.getAccount());
+        log.debug("[STUDENT_LOGIN] account:{}", req.getAccount());
         StudentEntity student = studentService.findStudentByStudentCode(req.getOrgId(), req.getAccount());
         if (student == null) {
             throw new StatusException("登录用户不存在");
@@ -94,15 +99,16 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
         LoginUser loginUser = new LoginUser();
         loginUser.setId(student.getId());
         loginUser.setOrgId(student.getOrgId());
+        loginUser.setCategoryId(student.getCategoryId());
         loginUser.setAccount(student.getStudentCode());
         loginUser.setName(student.getName());
         loginUser.setRole(Role.STUDENT);
 
-        loginUser.setSessionId("S_" + student.getId());
+        loginUser.setSessionId(CacheConstants.CACHE_STUDENT_LOGIN + student.getId());
         loginUser.setToken(FastUUID.get());
-        LoginSessionManager.addLoginSession(loginUser);
+        loginSessionManager.addLoginSession(loginUser);
 
-        log.info("[STUDENT_LOGIN] account:{} {}", loginUser.getAccount(), loginUser.getName());
+        log.info("[STUDENT_LOGIN_OK] account:{} {}", loginUser.getAccount(), loginUser.getName());
         return loginUser;
     }
 
@@ -113,13 +119,13 @@ public class AuthServiceImpl implements AuthorizationService<LoginUser>, AuthSer
 
     @Override
     public void logout(LoginUser loginUser) {
-        LoginSessionManager.removeLoginSession(loginUser.getSessionId());
+        loginSessionManager.removeLoginSession(loginUser.getSessionId());
         log.warn("用户退出登录!account:{},{}", loginUser.getAccount(), loginUser.getName());
     }
 
     @Override
     public LoginUser findByIdentity(String identity, SignatureType type, String path) {
-        return LoginSessionManager.getLoginSession(identity);
+        return loginSessionManager.getLoginSession(identity);
     }
 
 }

+ 78 - 0
src/test/java/com/qmth/exam/reserve/test/AuthTest.java

@@ -0,0 +1,78 @@
+package com.qmth.exam.reserve.test;
+
+import com.qmth.boot.tools.signature.SignatureEntity;
+import com.qmth.boot.tools.signature.SignatureType;
+import com.qmth.exam.reserve.bean.login.LoginUser;
+import com.qmth.exam.reserve.util.HttpClientBuilder;
+import com.qmth.exam.reserve.util.JsonHelper;
+import okhttp3.*;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class AuthTest {
+
+    private final static String SERVER_URL = "http://localhost:8080";
+
+    // @Test
+    public void demo() throws Exception {
+        LoginUser loginUser = this.doLogin();
+        this.doLogout(loginUser);
+    }
+
+    private LoginUser doLogin() {
+        String apiUrl = "/api/student/login";
+        Map<String, Object> params = new HashMap<>();
+        params.put("account", "1500010120019");
+        params.put("password", "123456");
+
+        String jsonParams = JsonHelper.toJson(params);
+        RequestBody requestBody = FormBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonParams);
+        Request.Builder builder = new Request.Builder().post(requestBody).url(SERVER_URL + apiUrl);
+        Request request = builder.build();
+
+        try (Response response = HttpClientBuilder.getClient().newCall(request).execute();
+             ResponseBody body = response.body();) {
+            String bodyStr = body.string();
+            System.out.printf("Response:%s %s \n\n", response.code(), bodyStr);
+
+            if (response.isSuccessful()) {
+                return JsonHelper.toObj(bodyStr, LoginUser.class);
+            }
+        } catch (IOException e) {
+            System.err.println(e.getMessage());
+        }
+
+        throw new RuntimeException("登录失败!");
+    }
+
+    private void doLogout(LoginUser loginUser) {
+        String apiUrl = "/api/student/logout";
+        long timestamp = System.currentTimeMillis();
+        String signature = SignatureEntity.build(SignatureType.TOKEN, "POST", apiUrl,
+                timestamp, loginUser.getSessionId(), loginUser.getToken());
+
+        Map<String, String> headers = new HashMap<>();
+        headers.put("authorization", signature);
+        headers.put("time", String.valueOf(timestamp));
+        System.out.println(headers);
+
+        RequestBody requestBody = FormBody.create(MediaType.parse("application/json;charset=UTF-8"), "{}");
+        Request.Builder builder = new Request.Builder().post(requestBody).url(SERVER_URL + apiUrl);
+        for (Map.Entry<String, String> entry : headers.entrySet()) {
+            builder.addHeader(entry.getKey(), entry.getValue());
+        }
+        Request request = builder.build();
+
+        try (Response response = HttpClientBuilder.getClient().newCall(request).execute();
+             ResponseBody body = response.body();) {
+            String bodyStr = body.string();
+            System.out.printf("Response:%s %s \n\n", response.code(), bodyStr);
+        } catch (IOException e) {
+            System.err.println(e.getMessage());
+        }
+    }
+
+}