Administrator 2 anni fa
parent
commit
8c6ead7665

+ 46 - 5
ruoyi-admin/src/main/java/com/ruoyi/web/controller/index/IndexController.java

@@ -2,6 +2,7 @@ package com.ruoyi.web.controller.index;
 
 import com.ruoyi.common.annotation.Log;
 import com.ruoyi.common.constant.CacheConstants;
+import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.constant.UserConstants;
 import com.ruoyi.common.core.controller.BaseController;
 import com.ruoyi.common.core.domain.AjaxResult;
@@ -11,6 +12,7 @@ import com.ruoyi.common.enums.BusinessType;
 import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.framework.web.service.SysLoginService;
 import com.ruoyi.system.domain.KaoqinConfig;
 import com.ruoyi.system.domain.KaoqinRecord;
 import com.ruoyi.system.service.IKaoqinRecordService;
@@ -49,13 +51,13 @@ public class IndexController extends BaseController {
     @Autowired
     private IKaoqinRecordService kaoqinRecordService;
 
+    @Autowired
+    private SysLoginService loginService;
     /**
      * app新增用户
      */
     @PostMapping
     public AjaxResult add(@Validated @RequestBody SysUser user) {
-        String phonenumber = user.getPhonenumber();
-        user.setUserName(phonenumber);
         if (!user.getCode().equals(redisCache.getCacheObject(CacheConstants.SMS_CODE_KEY+user.getPhonenumber()))) {
             return error("新增用户'" + user.getUserName() + "'失败,短信验证码错误");
         }
@@ -64,12 +66,24 @@ public class IndexController extends BaseController {
         } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                 && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
             return error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
-        } else if ("1".equals(checkStrongPwd(user.getPassword()))) {
+        }/* else if ("1".equals(checkStrongPwd(user.getPassword()))) {
             return AjaxResult.error("密码必须包含数字、大小写字母、特殊符号且大于8位");
-        }
+        }*/
         user.setCreateBy("APP");
+        AjaxResult ajax = AjaxResult.success();
+        // 生成令牌
+        user.setCreateBy(getUsername());
+        //生成一个密码
+        //String password = randomPassword();
+        String password = user.getUserName()+"Abc#";
+        //todo 密码 要发送短信给用户
         user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
-        return toAjax(userService.insertUserApp(user));
+        if (userService.insertUser(user) > 0){
+            String token = loginService.loginZhuCe(user.getUserName(), password);
+            ajax.put(Constants.TOKEN, token);
+            return ajax;
+        }
+        return AjaxResult.error();
     }
 
     /**
@@ -184,4 +198,31 @@ public class IndexController extends BaseController {
         map.put("y", yMpa);
         return AjaxResult.success(map);
     }
+
+
+    /** 随机出用户输入的密码位数的密码,从大小写字母,数字中取值 */
+    public static String randomPassword(){
+        char[] password = new char[8];//创建char数组接收每一位随机出来的密码
+        Random rand = new Random();
+        //在ASCII码表中,48-57 数字,65-90 大写字母,97-122 小写字母
+        for (int i = 0; i <password.length ; i++) {
+            int choice = rand.nextInt(4);
+            int lowercase = rand.nextInt(26)+65;//小写字母ASCII码表范围
+            int uppercase = rand.nextInt(26)+97;//大写字母ASCII码表范围
+            int figure = rand.nextInt(10)+48;//数字ASCII码表范围
+            int special = rand.nextInt(15) + 33;
+            //将 " 和 ' 替换成#
+            if (special == 34 || special == 39) {
+                special = 35;
+            }
+            switch (choice){//从大写字母.小写字母.数字中随机取值
+                case 0:password[i]=(char)lowercase;break;
+                case 1:password[i]=(char)uppercase;break;
+                case 2:password[i]=(char)figure;break;
+                case 3:password[i] = (char) special;break;
+                default:
+            }
+        }
+        return new String(password);
+    }
 }

+ 1 - 1
ruoyi-admin/src/main/java/com/ruoyi/web/controller/kaoqin/KaoQinController.java

@@ -46,7 +46,7 @@ public class KaoQinController extends BaseController {
      */
     @GetMapping(value = "/daKa")
     public AjaxResult daKa(KaoqinConfig kaoqinConfig) {
-        //先去 根据当前人员的部门id查询是否有规则,没有再去祖籍列表
+        //先去 根据当前人员的部门id查询是否有规则,没有再去祖籍列表
         KaoqinConfig kaoqinConfigDept = kaoqinConfigService.selectKaoqinConfigByDeptId(kaoqinConfig.getDeptId());
         if (kaoqinConfigDept == null){
             //根据部门祖籍列表,查询该部门考勤范围 ,经纬度

+ 31 - 0
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java

@@ -2,6 +2,8 @@ package com.ruoyi.web.controller.system;
 
 import java.util.List;
 import java.util.Set;
+
+import com.ruoyi.common.constant.CacheConstants;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -51,6 +53,35 @@ public class SysLoginController
         return ajax;
     }
 
+
+    /**
+     * 登录方法APP上使用
+     *
+     * @param loginBody 登录信息
+     * @return 结果
+     */
+    @PostMapping("/loginApp")
+    public AjaxResult loginApp(@RequestBody LoginBody loginBody)
+    {
+        String type = loginBody.getType();
+        AjaxResult ajax = AjaxResult.success();
+        if (CacheConstants.LOGIN_TYPE_PASSWORD.equals(type)){
+            // 生成令牌
+            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
+                    loginBody.getUuid());
+            ajax.put(Constants.TOKEN, token);
+        }else {
+            //使用短信验证码登录
+            // 生成令牌
+            String token = loginService.loginApp(loginBody.getUsername(),  loginBody.getCode() );
+            if ("error".equals(token)){
+                return AjaxResult.error("短信验证码错误");
+            }
+            ajax.put(Constants.TOKEN, token);
+        }
+        return ajax;
+    }
+
     /**
      * 获取用户信息
      * 

+ 2 - 0
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java

@@ -7,7 +7,9 @@ import java.util.stream.Collectors;
 import javax.servlet.http.HttpServletResponse;
 
 import com.ruoyi.common.constant.CacheConstants;
+import com.ruoyi.common.constant.Constants;
 import com.ruoyi.common.core.redis.RedisCache;
+import com.ruoyi.framework.web.service.SysLoginService;
 import org.apache.commons.lang3.ArrayUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.access.prepost.PreAuthorize;

+ 8 - 0
ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheConstants.java

@@ -11,6 +11,14 @@ public class CacheConstants
      * 登录用户 redis key
      */
     public static final String LOGIN_TOKEN_KEY = "login_tokens:";
+    /**
+     * 用户登录方式 1 账号密码
+     */
+    public static final String LOGIN_TYPE_PASSWORD = "1";
+    /**
+     * 用户登录方式 2 短信验证码
+     */
+    public static final String LOGIN_TYPE_SMS= "2";
 
     /**
      * 验证码 redis key

+ 12 - 0
ruoyi-common/src/main/java/com/ruoyi/common/core/domain/model/LoginBody.java

@@ -26,6 +26,18 @@ public class LoginBody
      * 唯一标识
      */
     private String uuid;
+    /**
+     * 登录方式 1使用密码 2使用短信验证码
+     */
+    private String type;
+
+    public String getType() {
+        return type;
+    }
+
+    public void setType(String type) {
+        this.type = type;
+    }
 
     public String getUsername()
     {

+ 1 - 1
ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java

@@ -111,7 +111,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
                 // 过滤请求
                 .authorizeRequests()
                 // 对于登录login 注册register 验证码captchaImage 允许匿名访问
-                .antMatchers("/login", "/register", "/captchaImage","/index/**","/sms/sendSmsOnly","/sms/getCode").permitAll()
+                .antMatchers("/login","/loginApp", "/register", "/captchaImage","/index/**","/sms/sendSmsOnly","/sms/getCode").permitAll()
                 // 静态资源,可匿名访问
                 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                 .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()

+ 65 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java

@@ -6,6 +6,7 @@ import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.BadCredentialsException;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
+import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.stereotype.Component;
 import com.ruoyi.common.constant.CacheConstants;
 import com.ruoyi.common.constant.Constants;
@@ -49,6 +50,8 @@ public class SysLoginService
 
     @Autowired
     private ISysConfigService configService;
+    @Autowired
+    private UserDetailsServiceImpl userDetailsService;
 
     /**
      * 登录验证
@@ -99,6 +102,68 @@ public class SysLoginService
         // 生成token
         return tokenService.createToken(loginUser);
     }
+    /**
+     * 新注册登录验证
+     *
+     * @param username 用户名
+     * @param password 密码
+     * @return 结果
+     */
+    public String loginZhuCe(String username, String password)
+    {
+        // 用户验证
+        Authentication authentication = null;
+        try
+        {
+            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
+            AuthenticationContextHolder.setContext(authenticationToken);
+            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
+            authentication = authenticationManager.authenticate(authenticationToken);
+        }
+        catch (Exception e)
+        {
+            if (e instanceof BadCredentialsException)
+            {
+                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
+                throw new UserPasswordNotMatchException();
+            }
+            else
+            {
+                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
+                throw new ServiceException(e.getMessage());
+            }
+        }
+        finally
+        {
+            AuthenticationContextHolder.clearContext();
+        }
+        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
+        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
+        recordLoginInfo(loginUser.getUserId());
+        // 生成token
+        return tokenService.createToken(loginUser);
+    }
+    /**
+     * 登录验证app短信登录
+     *
+     * @param username 手机号
+     * @param code 验证码
+     * @return 结果*/
+
+    public String loginApp(String username,  String code)
+    {
+        // 用户验证
+/*        String verifyKey = CacheConstants.SMS_CODE_KEY + username;
+        String codeApp = redisCache.getCacheObject(verifyKey);
+        if (!code.equals(codeApp)){
+            return "error";
+        }*/
+        LoginUser loginUser = (LoginUser)userDetailsService.loadUserByUsernameApp(username);
+        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
+        recordLoginInfo(loginUser.getUserId());
+        // 生成token
+        return tokenService.createToken(loginUser);
+    }
 
     /**
      * 校验验证码

+ 24 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java

@@ -79,6 +79,30 @@ public class SysPasswordService
         }
     }
 
+    public void validateApp(SysUser user)
+    {
+
+        String username = user.getUserName();
+
+        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));
+
+        if (retryCount == null)
+        {
+            retryCount = 0;
+        }
+
+        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
+        {
+            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
+                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
+            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
+        }
+        else
+        {
+            clearLoginRecordCache(username);
+        }
+    }
+
     public boolean matches(SysUser user, String rawPassword)
     {
         return SecurityUtils.matchesPassword(rawPassword, user.getPassword());

+ 24 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/UserDetailsServiceImpl.java

@@ -58,6 +58,30 @@ public class UserDetailsServiceImpl implements UserDetailsService
         return createLoginUser(user);
     }
 
+
+    public UserDetails loadUserByUsernameApp(String username) throws UsernameNotFoundException
+    {
+        SysUser user = userService.selectUserByUserName(username);
+        if (StringUtils.isNull(user))
+        {
+            log.info("登录用户:{} 不存在.", username);
+            throw new ServiceException("登录用户:" + username + " 不存在");
+        }
+        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
+        {
+            log.info("登录用户:{} 已被删除.", username);
+            throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
+        }
+        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
+        {
+            log.info("登录用户:{} 已被停用.", username);
+            throw new ServiceException("对不起,您的账号:" + username + " 已停用");
+        }
+
+        passwordService.validateApp(user);
+
+        return createLoginUser(user);
+    }
     public UserDetails createLoginUser(SysUser user)
     {
         return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));

+ 4 - 0
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/KaoqinRecordServiceImpl.java

@@ -54,6 +54,10 @@ public class KaoqinRecordServiceImpl implements IKaoqinRecordService
     @Override
     public int insertKaoqinRecord(KaoqinRecord kaoqinRecord)
     {
+        String ancestors = kaoqinRecord.getAncestors();
+        Long deptId = kaoqinRecord.getDeptId();
+        ancestors = ancestors + deptId;
+        kaoqinRecord.setAncestors(ancestors);
         kaoqinRecord.setCreateTime(DateUtils.getNowDate());
         return kaoqinRecordMapper.insertKaoqinRecord(kaoqinRecord);
     }

+ 2 - 2
ruoyi-system/src/main/resources/mapper/system/KaoqinRecordMapper.xml

@@ -54,8 +54,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
         <include refid="selectKaoqinRecordVo"/>
         <where>  
             <if test="userId != null "> and user_id = #{userId}</if>
-            <if test="userName != null  and userName != ''"> and user_name like concat('%', #{userName}, '%')</if>
-            <if test="deptName != null  and deptName != ''"> and dept_name like concat('%', #{deptName}, '%')</if>
+            <if test="userName != null  and userName != ''"> and user_name like concat( #{userName}, '%')</if>
+            <if test="deptName != null  and deptName != ''"> and dept_name like concat( #{deptName}, '%')</if>
             <if test="deptId != null  and deptId != ''"> and find_in_set(#{deptId}, ancestors)</if>
             <if test="kaYear != null  and kaYear != ''"> and ka_year = #{kaYear}</if>
             <if test="kaMonth != null  and kaMonth != ''"> and ka_month = #{kaMonth}</if>