Browse Source

添加日志

wangmh 7 years ago
parent
commit
ce3e60da31

+ 20 - 1
sso-server/src/main/java/com/uas/sso/controller/LoginController.java

@@ -26,6 +26,8 @@ import com.uas.sso.util.BeanUtil;
 import com.uas.sso.util.CaptchaUtil;
 import com.uas.sso.util.MessageUtils;
 import com.uas.sso.util.StringUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.ui.ModelMap;
 import org.springframework.util.Assert;
@@ -74,6 +76,8 @@ public class LoginController extends BaseController {
     @Autowired
     private LoginService loginService;
 
+    private final static Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
+
     @RequestMapping(method = RequestMethod.POST)
     public ModelMap login(PasswordLogin loginParam) {
         loginParam.setSureCaptcha((String) request.getSession().getAttribute(LOGIN_CAPTCHA));
@@ -87,6 +91,7 @@ public class LoginController extends BaseController {
             } else if (count >= 5)  {
                 msg = "密码错误次数已达上限,今日无法登录";
             }
+            LOGGER.error("密码错误!用户名:{},密码:{},错误次数:{}", loginParam.getUsername(), loginParam.getPassword(), count);
             return error(msg).addAttribute("errorCount", count);
         }
     }
@@ -120,6 +125,7 @@ public class LoginController extends BaseController {
             return error(new ModelMap("hasUser", false));
         }
 
+        // 用户未绑定企业则绑定
         if (!userspace.getUsers().contains(user)) {
             userService.bindUserspace(appId, user.getUserUU(), userspace.getSpaceUU());
         }
@@ -130,6 +136,7 @@ public class LoginController extends BaseController {
         int expires_in = 1 * 60;
         Token token = new Token(data, expires_in);
         tokenService.save(token);
+        LOGGER.info("获取token成功,用户:{},企业:{}", userUU, enUU);
         return success(token.getId());
     }
 
@@ -163,8 +170,12 @@ public class LoginController extends BaseController {
     @RequestMapping(value = "/updateToken", method = RequestMethod.GET)
     public ModelMap updateToken(String token) {
         Token oldToken = tokenService.findOne(token);
+        if (oldToken == null) {
+            LOGGER.error("token({})已过期,更新token失败", token);
+        }
         oldToken.setExpires_in(7*24*60*60);
         tokenService.save(oldToken);
+        LOGGER.info("更新token成功", token);
         return success(token);
     }
 
@@ -242,6 +253,7 @@ public class LoginController extends BaseController {
     @RequestMapping(value = "/logoutAccount", method = RequestMethod.GET)
     public ModelMap logoutAccount() {
         SSOHelper.clearLogin(request, response);
+        LOGGER.info("退出成功");
         return success();
     }
 
@@ -370,7 +382,6 @@ public class LoginController extends BaseController {
         // 随机获得验证码
         String code = StringUtil.getRandomNumber(6);
         Token token = new Token(code, 10 * 60);
-        System.out.println(code);
 
         // 设置绑定手机,防止获取验证码之后修改手机号
         token.setMobile(mobile);
@@ -382,6 +393,7 @@ public class LoginController extends BaseController {
         // 返回tokenId
         ModelMap returnData = new ModelMap();
         returnData.put("token", token.getId());
+        LOGGER.info("手机({})验证码发送成功", mobile);
         return success(returnData);
     }
 
@@ -394,6 +406,12 @@ public class LoginController extends BaseController {
         return success(loginService.loginBySms(loginParam));
     }
 
+    /**
+     * 商城微信公众号登录接口
+     * @param appId 应用id
+     * @param userUU 用户uu号
+     * @param spaceUU 企业uu号
+     */
     @GetMapping("/other")
     public void login(String appId, Long userUU, Long spaceUU) {
         UserAccount userAccount = spaceUU == null ? personalAccountService.findOneByUserUU(appId, userUU) : userAccountService.findOneByUserUU(appId, userUU, spaceUU);
@@ -402,6 +420,7 @@ public class LoginController extends BaseController {
         SSOHelper.setSSOCookie(request, response, st, true);
         try {
             printJsonP("successCallback", "{success:'1'}");
+            LOGGER.info("其他登录方式,用户({})登录企业({})成功", userUU, spaceUU);
         } catch (IOException e) {
             e.printStackTrace();
         }

+ 8 - 0
sso-server/src/main/java/com/uas/sso/controller/UserspaceManagerController.java

@@ -17,6 +17,8 @@ import com.uas.sso.util.CountUtils;
 import com.uas.sso.util.FastjsonUtils;
 import com.uas.sso.util.FileUrl;
 import com.uas.sso.util.HttpUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Page;
 import org.springframework.ui.ModelMap;
@@ -55,6 +57,7 @@ public class UserspaceManagerController extends BaseController {
     @Autowired
     private UserspaceDao userspaceDao;
 
+    private static final Logger LOGGER = LoggerFactory.getLogger(UserspaceManagerController.class);
     /**
      * 校验企业名称
      *
@@ -215,12 +218,15 @@ public class UserspaceManagerController extends BaseController {
      * @return
      */
     @RequestMapping(params = "_operate=unbind", method = RequestMethod.POST)
+    @Deprecated
     public ModelMap unbindApp(Long spaceUU, String appId) {
         if (StringUtils.isEmpty(spaceUU) || StringUtils.isEmpty(appId)) {
+            LOGGER.error("企业({})解除绑定应用({})参数错误!", spaceUU, appId);
             return error("参数错误");
         }
 
         userspaceService.unbindApp(spaceUU, appId);
+        LOGGER.info("企业({})解除绑定应用({})成功!", spaceUU, appId);
         return success();
     }
 
@@ -234,10 +240,12 @@ public class UserspaceManagerController extends BaseController {
     @RequestMapping(params = "_operate=bind", method = RequestMethod.POST)
     public ModelMap bindApp(Long spaceUU, String appId) {
         if (StringUtils.isEmpty(spaceUU) || StringUtils.isEmpty(appId)) {
+            LOGGER.error("企业({})绑定应用({})参数错误!", spaceUU, appId);
             return error("参数错误");
         }
 
         userspaceService.bindApp(spaceUU, appId);
+        LOGGER.info("企业({})绑定应用({})成功!", spaceUU, appId);
         return success();
     }
 

+ 11 - 0
sso-server/src/main/java/com/uas/sso/service/impl/LoginServiceImpl.java

@@ -17,6 +17,8 @@ import com.uas.sso.foreign.factory.ForeignFactory;
 import com.uas.sso.foreign.service.ForeignService;
 import com.uas.sso.service.*;
 import com.uas.sso.util.PasswordLevelUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.ui.ModelMap;
@@ -69,6 +71,8 @@ public class LoginServiceImpl implements LoginService {
      */
     private static final int PWD_ERROR_FIVE_TIME = 5;
 
+    private final static Logger LOGGER = LoggerFactory.getLogger(LoginServiceImpl.class);
+
     /**
      * 密码输错3次
      */
@@ -90,6 +94,7 @@ public class LoginServiceImpl implements LoginService {
         // 获取用户信息
         User user = userService.findByUsername(loginParam.getUsername());
         if (user == null) {
+            LOGGER.warn("用户名未找到!账号:{}, 密码:{}", loginParam.getUsername(), loginParam.getPassword());
             throw new VisibleError("用户名或密码错误");
         }
 
@@ -118,6 +123,7 @@ public class LoginServiceImpl implements LoginService {
         // 校验密码强度,如果和存储的不同,则保存
         int strength = PasswordLevelUtils.checkPasswordLevel(loginParam.getPassword()).getValue();
         if (strength != user.getPasswordLevel()) {
+            LOGGER.info("用户密码等级修改:{} -> {}",user.getPasswordLevel(), strength);
             user.setPasswordLevel(strength);
             userService.save(user);
         }
@@ -131,6 +137,7 @@ public class LoginServiceImpl implements LoginService {
         Token tk = tokenService.findOne(loginParam.getToken());
         // token不存在则不登录返回
         if (tk == null) {
+            LOGGER.warn("token({})已过期", loginParam.getToken());
             new ModelMap("returnUrl", HttpUtil.decodeURL(loginParam.getReturnUrl()));
         }
 
@@ -256,6 +263,7 @@ public class LoginServiceImpl implements LoginService {
 
         // 可能用户不在该企业,可能企业未开通该应用
         if (userAccount == null) {
+            LOGGER.error("用户({})不在该企业({}),或企业({})未开通应用({}),登录应用:{}", userUU, spaceUU, spaceUU, controlApp.getUid(), loginParam.getAppId());
             throw new VisibleError("数据错误");
         }
 
@@ -265,8 +273,10 @@ public class LoginServiceImpl implements LoginService {
             userRecord = new UserRecord(userUU);
         }
         if (userRecord.getLastLoginTime() != null) {
+            // 将上次登录时间写入cookie
             userAccount.setLastLoginTime(userRecord.getLastLoginTime());
         }
+        // 将本次登录时间写入数据库
         userRecord.setLastLoginTime(System.currentTimeMillis());
         userRecordDao.save(userRecord);
 
@@ -275,6 +285,7 @@ public class LoginServiceImpl implements LoginService {
         SSOToken st = new SSOToken(request, userAccount.getMobile());
         st.setData(JSON.toJSONString(userAccount));
         SSOHelper.setSSOCookie(request, response, st, true);
+        LOGGER.info("用户({})登录成功,时间:{}", userUU, userRecord.getLastLoginTime());
         return loginByUser(userAccount, loginParam);
     }
 

+ 19 - 14
sso-server/src/main/java/com/uas/sso/util/MessageUtils.java

@@ -4,12 +4,13 @@ import com.uas.message.mail.service.MailService;
 import com.uas.message.sms.service.SmsService;
 import com.uas.sso.entity.Setting;
 import com.uas.sso.service.SettingService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.PostConstruct;
 import java.util.Map;
-import java.util.logging.Logger;
 
 /**
  * @author wangmh
@@ -29,7 +30,7 @@ public class MessageUtils {
     private SettingService settingService;
 
     private static MessageUtils messageUtils;
-    protected final Logger logger = Logger.getLogger(MessageUtils.class.getName());
+    protected final Logger logger = LoggerFactory.getLogger(MessageUtils.class);
     @PostConstruct
     public void init() {
         messageUtils = this;
@@ -43,14 +44,16 @@ public class MessageUtils {
      */
     public static void sendSms(String templateId, String mobile, Object... data) {
         try {
-            if (!StringUtils.isEmpty(mobile)) {
-                Setting smsTplId = messageUtils.settingService.findOne(templateId);
-                if (!StringUtils.isEmpty(smsTplId)) {
-                    messageUtils.smsService.send(smsTplId.getValue(), mobile, data);
-                }
+            if (StringUtils.isEmpty(mobile)) {
+                throw new RuntimeException("用户手机号不存在");
             }
+            Setting smsTplId = messageUtils.settingService.findOne(templateId);
+            if (StringUtils.isEmpty(smsTplId)) {
+                throw new RuntimeException("模板不存在");
+            }
+            messageUtils.smsService.send(smsTplId.getValue(), mobile, data);
         } catch (Exception e) {
-            messageUtils.logger.warning("验证码发送失败:mobile:" + mobile + " msg: " + e.getMessage());
+            messageUtils.logger.warn("短信发送失败,模板:"+ templateId +",手机号:" + mobile, e);
         }
     }
 
@@ -62,14 +65,16 @@ public class MessageUtils {
      */
     public static void sendEmail(String templateId, String email, Map<String, Object> data) {
         try {
-            if (!StringUtils.isEmpty(email)) {
-                Setting mailTplId = messageUtils.settingService.findOne(templateId);
-                if (!StringUtils.isEmpty(mailTplId)) {
-                    messageUtils.mailService.send(mailTplId.getValue(), email, data);
-                }
+            if (StringUtils.isEmpty(email)) {
+                throw new RuntimeException("邮箱不存在");
+            }
+            Setting mailTplId = messageUtils.settingService.findOne(templateId);
+            if (StringUtils.isEmpty(mailTplId)) {
+                throw new RuntimeException("模板不存在");
             }
+            messageUtils.mailService.send(mailTplId.getValue(), email, data);
         } catch (Exception e) {
-            e.printStackTrace();
+            messageUtils.logger.warn("邮箱发送失败,模板:"+ templateId +",邮箱:" + email, e);
         }
     }
 

+ 17 - 1
sso-server/src/main/java/com/uas/sso/web/advice/ExceptionHandlerAdvice.java

@@ -2,6 +2,7 @@ package com.uas.sso.web.advice;
 
 import com.uas.sso.exception.VisibleError;
 import org.apache.log4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -12,7 +13,8 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
 @ControllerAdvice
 public class ExceptionHandlerAdvice {
 
-	private final static Logger logger = Logger.getLogger(ExceptionHandlerAdvice.class);
+//	private final static Logger logger = Logger.getLogger(ExceptionHandlerAdvice.class);
+    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
 
 	private ModelMap error(String errMsg) {
 		return new ModelMap("error", true).addAttribute("errMsg", errMsg);
@@ -31,4 +33,18 @@ public class ExceptionHandlerAdvice {
 		headers.add("Content-Type", "application/json; charset=utf-8");
 		return new ResponseEntity<ModelMap>(error(ex.getMessage()), headers, HttpStatus.OK);
 	}
+
+	/**
+	 * 处理运行时抛出异常
+	 *
+	 * @param ex 运行时异常
+	 * @return 键值对
+	 */
+	@ExceptionHandler(VisibleError.class)
+	public ResponseEntity<ModelMap> handleVisibleError(VisibleError ex) {
+		logger.warn("VisibleError", ex);
+		HttpHeaders headers = new HttpHeaders();
+		headers.add("Content-Type", "application/json; charset=utf-8");
+		return new ResponseEntity<ModelMap>(error(ex.getMessage()), headers, HttpStatus.OK);
+	}
 }