xiatian 2 年之前
父节点
当前提交
2b5fc01f3a

+ 1 - 3
db/init.sql

@@ -193,7 +193,6 @@ CREATE TABLE `mps_school` (
   `update_time` bigint DEFAULT NULL,
   `creator_id` bigint DEFAULT NULL,
   `updater_id` bigint DEFAULT NULL,
-  `code` varchar(255) COLLATE utf8_bin NOT NULL,
   `contacts` varchar(255) COLLATE utf8_bin DEFAULT NULL,
   `enable` bit(1) NOT NULL,
   `name` varchar(255) COLLATE utf8_bin NOT NULL,
@@ -201,7 +200,6 @@ CREATE TABLE `mps_school` (
   `telephone` varchar(255) COLLATE utf8_bin DEFAULT NULL,
   PRIMARY KEY (`id`),
   UNIQUE KEY `IDX_SCHOOL_01` (`name`),
-  UNIQUE KEY `IDX_SCHOOL_02` (`code`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
 
 -- ----------------------------
@@ -221,7 +219,7 @@ CREATE TABLE `mps_user` (
   `role_id` bigint NOT NULL,
   `school_id` bigint NOT NULL,
   PRIMARY KEY (`id`),
-  UNIQUE KEY `IDX_USER_01` (`school_id`,`login_name`)
+  UNIQUE KEY `IDX_USER_01` (`login_name`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
 
 -- ----------------------------

+ 22 - 0
src/main/java/cn/com/qmth/mps/config/SysProperty.java

@@ -11,6 +11,12 @@ public class SysProperty {
 	 */
 	@Value("${session-timeout}")
     private Integer sessionTimeout;
+	
+	@Value("${wxapp-appid}")
+    private String wxappAppid;
+	
+	@Value("${wxapp-secret}")
+    private String wxappSecret;
 
 	public Integer getSessionTimeout() {
 		return sessionTimeout;
@@ -19,6 +25,22 @@ public class SysProperty {
 	public void setSessionTimeout(Integer sessionTimeout) {
 		this.sessionTimeout = sessionTimeout;
 	}
+
+	public String getWxappAppid() {
+		return wxappAppid;
+	}
+
+	public void setWxappAppid(String wxappAppid) {
+		this.wxappAppid = wxappAppid;
+	}
+
+	public String getWxappSecret() {
+		return wxappSecret;
+	}
+
+	public void setWxappSecret(String wxappSecret) {
+		this.wxappSecret = wxappSecret;
+	}
     
 
 	

+ 7 - 4
src/main/java/cn/com/qmth/mps/controller/AuthController.java

@@ -1,5 +1,6 @@
 package cn.com.qmth.mps.controller;
 
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -7,6 +8,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 import com.qmth.boot.api.constant.ApiConstant;
 
+import cn.com.qmth.mps.service.AuthService;
 import cn.com.qmth.mps.vo.AdminLoginVo;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -15,18 +17,19 @@ import io.swagger.annotations.ApiOperation;
 @Api(tags = "登录相关接口")
 @RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/auth")
 public class AuthController extends BaseController {
+	@Autowired
+	private AuthService authService;
 
 	@ApiOperation(value = "管理端登录")
 	@PostMapping("login/admin")
-	public AdminLoginVo loginAdmin(@RequestParam String schoolCode, @RequestParam String loginName,
-			@RequestParam String password) {
+	public AdminLoginVo loginAdmin(@RequestParam String loginName, @RequestParam String password) {
 		return null;
 	}
 
 	@ApiOperation(value = "微信小程序登录")
 	@PostMapping("login/wxapp")
-	public AdminLoginVo loginWxApp(@RequestParam String wxappCode,@RequestParam String schoolCode, @RequestParam String phone) {
-		return null;
+	public AdminLoginVo loginWxApp(@RequestParam String wxappCode, @RequestParam String phone) {
+		return authService.loginWxApp(wxappCode,phone);
 	}
 
 	@ApiOperation(value = "登出")

+ 9 - 0
src/main/java/cn/com/qmth/mps/dao/UserDao.java

@@ -0,0 +1,9 @@
+package cn.com.qmth.mps.dao;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+
+import cn.com.qmth.mps.entity.UserEntity;
+
+public interface UserDao extends BaseMapper<UserEntity> {
+
+}

+ 0 - 11
src/main/java/cn/com/qmth/mps/entity/SchoolEntity.java

@@ -7,7 +7,6 @@ import cn.com.qmth.mps.entity.base.AuditingEntity;
 public class SchoolEntity extends AuditingEntity {
 
 	private static final long serialVersionUID = -592353272256492483L;
-	private String code;
 	private String name;
 	private Boolean enable;
 
@@ -58,14 +57,4 @@ public class SchoolEntity extends AuditingEntity {
 		this.region = region;
 	}
 
-	public String getCode() {
-		return code;
-	}
-
-	public void setCode(String code) {
-		this.code = code;
-	}
-
-	
-
 }

+ 20 - 7
src/main/java/cn/com/qmth/mps/enums/Role.java

@@ -2,17 +2,18 @@ package cn.com.qmth.mps.enums;
 
 public enum Role {
 
-    SUPPER_ADMIN("超级管理员"),
+    SUPPER_ADMIN(1L,"超级管理员"),
 
-    SCHOOL_ADMIN("机构管理员"),
+    SCHOOL_ADMIN(2L,"机构管理员"),
 
-    SECTION_LEADER("科组长"),
+    SECTION_LEADER(3L,"科组长"),
 
     ;
-
+	private Long id;
     private String name;
 
-    Role(String name) {
+    Role(Long id,String name) {
+    	this.id = id;
         this.name = name;
     }
 
@@ -20,7 +21,12 @@ public enum Role {
         return name;
     }
 
-    public static Role getByName(String name) {
+    
+    public Long getId() {
+		return id;
+	}
+
+	public static Role getByName(String name) {
         for (Role r : Role.values()) {
             if (r.getName().equals(name)) {
                 return r;
@@ -28,5 +34,12 @@ public enum Role {
         }
         return null;
     }
-
+	public static Role getById(Long id) {
+        for (Role r : Role.values()) {
+            if (r.getId().equals(id)) {
+                return r;
+            }
+        }
+        return null;
+    }
 }

+ 23 - 0
src/main/java/cn/com/qmth/mps/job/AbstractJob.java

@@ -0,0 +1,23 @@
+package cn.com.qmth.mps.job;
+
+import org.apache.logging.log4j.ThreadContext;
+
+import cn.com.qmth.mps.util.ThreadLocalUtil;
+
+public abstract class AbstractJob {
+
+    public abstract void run();
+
+    public void execute() {
+        try {
+            String traceId = ThreadLocalUtil.next();
+            ThreadContext.put("TRACE_ID", traceId);
+            ThreadContext.put("CALLER", Thread.currentThread().getName());
+
+            this.run();
+        } finally {
+            ThreadContext.clearAll();
+        }
+    }
+
+}

+ 16 - 0
src/main/java/cn/com/qmth/mps/job/OnlineUserCountJob.java

@@ -0,0 +1,16 @@
+package cn.com.qmth.mps.job;
+
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+
+import cn.com.qmth.mps.util.ActiveDataUtil;
+
+@Service
+public class OnlineUserCountJob {
+
+	@Scheduled(cron = "0/30 * * * * ?")
+    public void updateUserCount() {
+        ActiveDataUtil.updateUserCount();
+    }
+
+}

+ 11 - 0
src/main/java/cn/com/qmth/mps/service/AuthService.java

@@ -0,0 +1,11 @@
+package cn.com.qmth.mps.service;
+
+import cn.com.qmth.mps.vo.AdminLoginVo;
+
+public interface AuthService {
+
+	AdminLoginVo loginWxApp(String wxappCode, String phone);
+
+
+
+}

+ 12 - 0
src/main/java/cn/com/qmth/mps/service/UserService.java

@@ -0,0 +1,12 @@
+package cn.com.qmth.mps.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+
+import cn.com.qmth.mps.entity.UserEntity;
+
+public interface UserService  extends IService<UserEntity> {
+
+	UserEntity getByLoginName(String phone);
+
+
+}

+ 76 - 0
src/main/java/cn/com/qmth/mps/service/impl/AuthServiceImpl.java

@@ -0,0 +1,76 @@
+package cn.com.qmth.mps.service.impl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.qmth.boot.core.exception.StatusException;
+import com.qmth.boot.tools.uuid.FastUUID;
+
+import cn.com.qmth.mps.bean.User;
+import cn.com.qmth.mps.config.SysProperty;
+import cn.com.qmth.mps.entity.UserEntity;
+import cn.com.qmth.mps.enums.Role;
+import cn.com.qmth.mps.service.AuthService;
+import cn.com.qmth.mps.service.UserService;
+import cn.com.qmth.mps.util.ActiveDataUtil;
+import cn.com.qmth.mps.util.HttpUtil;
+import cn.com.qmth.mps.vo.AdminLoginVo;
+import net.sf.json.JSONObject;
+
+@Service
+public class AuthServiceImpl implements AuthService {
+	private static String uri="https://api.weixin.qq.com/sns/jscode2session";
+	@Autowired
+	private UserService userService;
+	@Autowired
+	private SysProperty sysProperty;
+	@Override
+	public AdminLoginVo loginWxApp(String wxappCode, String phone) {
+		
+		Map<String,String> params=new HashMap<>();
+		params.put("appid", sysProperty.getWxappAppid());
+		params.put("secret", sysProperty.getWxappSecret());
+		params.put("js_code", wxappCode);
+		params.put("grant_type", "authorization_code");
+		String ret;
+		try {
+			ret=HttpUtil.httpActionGet(uri, null, params);
+		} catch (Exception e) {
+			throw new StatusException("登录失败",e);
+		}
+		JSONObject jo=JSONObject.fromObject(ret);
+		if(jo.containsKey("errmsg")) {
+			throw new StatusException("登录失败,"+jo.getString("errmsg"));
+		}
+		UserEntity userE=userService.getByLoginName(phone);
+		if(userE==null) {
+			throw new StatusException("该手机号不存在");
+		}
+		if(!userE.getEnable()) {
+			throw new StatusException("该用户已禁用");
+		}
+		if(!userE.getRoleId().equals(Role.SECTION_LEADER.getId())) {
+			throw new StatusException("该用户不是科组长");
+		}
+		User user = new User();
+		user.setName(userE.getName());
+		user.setSchoolId(userE.getSchoolId());
+		user.setId(userE.getId());
+		user.setRole(Role.getById(userE.getRoleId()));
+		user.setAccessToken(FastUUID.get());
+		user.buildKey();
+		ActiveDataUtil.userLogin(user);
+		AdminLoginVo vo=new AdminLoginVo();
+		vo.setAccessToken(user.getAccessToken());
+		vo.setName(user.getName());
+		vo.setSessionId(user.getSessionId());
+		vo.setSchoolId(user.getSchoolId());
+		vo.setRole(user.getRole());
+		return vo;
+	}
+
+
+}

+ 26 - 0
src/main/java/cn/com/qmth/mps/service/impl/UserServiceImpl.java

@@ -0,0 +1,26 @@
+package cn.com.qmth.mps.service.impl;
+
+import org.springframework.stereotype.Service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+
+import cn.com.qmth.mps.dao.UserDao;
+import cn.com.qmth.mps.entity.UserEntity;
+import cn.com.qmth.mps.service.UserService;
+
+@Service
+public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
+
+	private static final String[] EXCEL_HEADER = new String[] { "姓名", "登录名", "登陆密码", "角色名称", "课程代码", "课程名称", "审核权限" };
+
+	@Override
+	public UserEntity getByLoginName(String phone) {
+		QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
+		LambdaQueryWrapper<UserEntity> lw = wrapper.lambda();
+		lw.eq(UserEntity::getLoginName, phone);
+		return this.getOne(wrapper);
+	}
+
+}

+ 61 - 0
src/main/java/cn/com/qmth/mps/util/ActiveDataUtil.java

@@ -0,0 +1,61 @@
+package cn.com.qmth.mps.util;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import cn.com.qmth.mps.bean.User;
+import cn.com.qmth.mps.config.SysProperty;
+import cn.com.qmth.mps.support.SpringContextHolder;
+
+public class ActiveDataUtil {
+
+	private static SysProperty sysProperty = SpringContextHolder.getBean(SysProperty.class);
+
+	private static int online_user_count = 0;
+
+	private final static Long DEFTIMEOUT = (sysProperty.getSessionTimeout() == null ? 7200
+			: sysProperty.getSessionTimeout()) * 1000L;
+
+	private final static Map<Long, User> userActiveData = new ConcurrentHashMap<>();
+
+	public static void updateUserActive(User user) {
+		user.setActiveTime(System.currentTimeMillis());
+		userActiveData.put(user.getId(), user);
+	}
+
+	private static void clearTimeOutUserActive() {
+		Date d = new Date();
+		Long now = d.getTime();
+		for (Long k : userActiveData.keySet()) {
+			if (now - userActiveData.get(k).getActiveTime() > DEFTIMEOUT) {
+				userActiveData.remove(k);
+			}
+		}
+	}
+
+	public static void updateUserCount() {
+		clearTimeOutUserActive();
+		online_user_count = userActiveData.size();
+	}
+
+	public static int getUserCount() {
+		return online_user_count;
+	}
+
+	public static void userLogout(Long userId) {
+		userActiveData.remove(userId);
+		updateUserCount();
+	}
+
+	public static synchronized void userLogin(User user) {
+		updateUserActive(user);
+		updateUserCount();
+
+	}
+
+	public static User getUser(Long userId) {
+		return userActiveData.get(userId);
+	}
+
+}

+ 171 - 0
src/main/java/cn/com/qmth/mps/util/HttpUtil.java

@@ -0,0 +1,171 @@
+package cn.com.qmth.mps.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.Map;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import com.qmth.boot.core.exception.StatusException;
+
+public class HttpUtil {
+
+	/** 默认的编码格式 */
+	private static final String DEFAULT_CHARSET = "UTF-8";
+
+	private static final String CONTENT_TYPE = "Content-Type";
+
+	private static final String APPLICATION_JSON = "application/x-www-form-urlencoded;charset=utf-8";
+
+	private static final String METHOD_GET = "GET";
+
+	/**
+	 * 
+	 * @param params headers参数
+	 * @param datas  requestParams参数
+	 * @return
+	 * @throws Exception
+	 */
+	public static String httpActionGet(String uri, Map<String, String> heads, Map<String, String> params) {
+		String result = null;
+		HttpsURLConnection conn = null;
+		OutputStream os = null;
+		InputStream is = null;
+
+		try {
+			// 设置请求参数
+			if (params != null) {
+				StringBuilder sb = new StringBuilder();
+				for (Map.Entry<String, String> data : params.entrySet()) {
+					sb.append(data.getKey()).append("=").append(data.getValue()).append("&");
+				}
+				uri = uri+"?" + sb.toString();
+			}
+			// 获取链接
+			URL url = new URL(uri);
+			conn = (HttpsURLConnection) url.openConnection();
+
+			conn.setRequestMethod(METHOD_GET);
+			conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
+			// ssl
+			SSLContext context = SSLContext.getInstance("SSL", "SunJSSE");
+			TrustManager[] tm = new TrustManager[] { new X509TrustManager() {
+
+				@Override
+				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+				}
+
+				@Override
+				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+				}
+
+				@Override
+				public X509Certificate[] getAcceptedIssuers() {
+					return null;
+				}
+			} };
+			// 初始化
+			context.init(null, tm, new java.security.SecureRandom());
+			// 获取SSLSocketFactory对象
+			SSLSocketFactory ssf = context.getSocketFactory();
+			conn.setSSLSocketFactory(ssf);
+
+			conn.setUseCaches(false);
+			conn.setDoOutput(true);
+
+			// 设置额外的参数
+			if (heads != null && !heads.isEmpty()) {
+
+				for (Map.Entry<String, String> head : heads.entrySet()) {
+					conn.setRequestProperty(head.getKey(), head.getValue());
+				}
+			}
+			// 创建链接
+			conn.connect();
+
+			result = getResult(conn);
+		} catch (Exception e) {
+			throw new StatusException("授权服务器访问失败", e);
+		} finally {
+			try {
+				if (os != null) {
+					os.close();
+					os = null;
+				}
+				if (is != null) {
+					is.close();
+					is = null;
+				}
+			} catch (IOException e) {
+			}
+
+			if (conn != null) {
+				conn.disconnect();
+				conn = null;
+			}
+		}
+
+		return result;
+	}
+
+	/**
+	 * 获得连接请求的返回数据
+	 * 
+	 * @param conn
+	 * 
+	 * @return 字符串
+	 */
+	private static String getResult(HttpURLConnection conn) throws IOException {
+
+		StringBuilder text = new StringBuilder();
+
+		InputStream is = null;
+		InputStreamReader sr = null;
+		BufferedReader br = null;
+
+		int code = conn.getResponseCode();
+
+		try {
+			is = code != 200 ? conn.getErrorStream() : conn.getInputStream();
+
+			sr = new InputStreamReader(is, DEFAULT_CHARSET);
+			br = new BufferedReader(sr);
+
+			char[] chars = new char[4096];
+			int length = 0;
+
+			while ((length = br.read(chars)) != -1) {
+				text.append(chars, 0, length);
+			}
+		} finally {
+			if (br != null) {
+				br.close();
+				br = null;
+			}
+			if (sr != null) {
+				sr.close();
+				sr = null;
+			}
+			if (is != null) {
+				is.close();
+				is = null;
+			}
+		}
+		if (code != 200) {
+			throw new IOException(text.toString());
+		}
+		return text.toString();
+	}
+
+}

+ 12 - 0
src/main/java/cn/com/qmth/mps/vo/AdminLoginVo.java

@@ -4,6 +4,8 @@ import cn.com.qmth.mps.bean.User;
 import cn.com.qmth.mps.enums.Role;
 
 public class AdminLoginVo {
+	private Long schoolId;
+	
 	private String name;
 
     private String sessionId;
@@ -52,4 +54,14 @@ public class AdminLoginVo {
     	v.setName(user.getName());
     	return v;
     }
+
+	public Long getSchoolId() {
+		return schoolId;
+	}
+
+	public void setSchoolId(Long schoolId) {
+		this.schoolId = schoolId;
+	}
+    
+    
 }

+ 4 - 1
src/main/resources/application.properties

@@ -30,4 +30,7 @@ com.qmth.fss.server=http://localhost:7101/file
 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
 spring.jackson.time-zone=GMT+8
 
-session-timeout=7200
+session-timeout=7200
+
+wxapp-appid=xxx
+wxapp-secret=xxxx