src/main/java/com/ruoyi/framework/config/SecurityConfig.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/framework/security/LoginBody.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/framework/security/LoginUser.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/framework/security/service/SysLoginService.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/framework/security/service/UserDetailsServiceImpl.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/project/system/controller/SysLoginController.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/ruoyi/project/system/domain/SysUser.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/resources/mapper/system/SysRoleMapper.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
src/main/java/com/ruoyi/framework/config/SecurityConfig.java
@@ -111,7 +111,7 @@ .authorizeHttpRequests((requests) -> { permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll()); // 对于登录login 注册register 验证码captchaImage 允许匿名访问 requests.antMatchers("/login", "/register", "/captchaImage").permitAll() requests.antMatchers("/login", "/register", "/captchaImage","/loginCheck","/userDeptList/**","/loginCheckFactory").permitAll() // 静态资源,可匿名访问 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() src/main/java/com/ruoyi/framework/security/LoginBody.java
@@ -27,6 +27,16 @@ */ private String uuid; private Long factoryId; public Long getFactoryId() { return factoryId; } public void setFactoryId(Long factoryId) { this.factoryId = factoryId; } public String getUsername() { return username; src/main/java/com/ruoyi/framework/security/LoginUser.java
@@ -76,6 +76,11 @@ */ private Integer tenantId; /** * 当前部门id */ private Long currentDeptId; public LoginUser() { } @@ -101,6 +106,16 @@ this.user = user; this.permissions = permissions; this.tenantId = tenantId; } public LoginUser(Long userId, Long [] deptIds, SysUser user,Integer tenantId,Long currentDeptId, Set<String> permissions) { this.userId = userId; this.deptIds = deptIds; this.user = user; this.permissions = permissions; this.tenantId = tenantId; this.currentDeptId = currentDeptId; } public Long getUserId() @@ -285,4 +300,16 @@ public void setTenantId(Integer tenantId) { this.tenantId = tenantId; } public void setDeptIds(Long[] deptIds) { this.deptIds = deptIds; } public Long getCurrentDeptId() { return currentDeptId; } public void setCurrentDeptId(Long currentDeptId) { this.currentDeptId = currentDeptId; } } src/main/java/com/ruoyi/framework/security/service/SysLoginService.java
@@ -1,11 +1,14 @@ package com.ruoyi.framework.security.service; import javax.annotation.Resource; import com.ruoyi.framework.web.domain.AjaxResult; import org.springframework.beans.factory.annotation.Autowired; 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.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.ruoyi.common.constant.CacheConstants; import com.ruoyi.common.constant.Constants; @@ -28,6 +31,10 @@ import com.ruoyi.project.system.domain.SysUser; import com.ruoyi.project.system.service.ISysConfigService; import com.ruoyi.project.system.service.ISysUserService; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 登录校验方法 @@ -178,4 +185,88 @@ sysUser.setLoginDate(DateUtils.getNowDate()); userService.updateUserProfile(sysUser); } public Long loginCheck(String username, String password){ loginPreCheck(username, 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(); } LoginUser loginUser = (LoginUser) authentication.getPrincipal(); return loginUser.getUserId(); } /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param factoryId 公司ID * @return 结果 */ public String loginCheckFactory(String username, String password, Long factoryId) { // 登录前置校验 loginPreCheck(username, password); // 用户验证 Authentication authentication = null; try { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); // 扩展细节:将 companyId 放入 details(可选方式) // 使用 Map 存储额外信息 Map<String, Object> details = new HashMap<>(); details.put("factoryId", factoryId); authenticationToken.setDetails(details); SecurityContextHolder.getContext().setAuthentication(authenticationToken); 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); } } src/main/java/com/ruoyi/framework/security/service/UserDetailsServiceImpl.java
@@ -1,8 +1,11 @@ package com.ruoyi.framework.security.service; import com.ruoyi.project.system.mapper.SysDeptMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; @@ -13,6 +16,8 @@ import com.ruoyi.framework.security.LoginUser; import com.ruoyi.project.system.domain.SysUser; import com.ruoyi.project.system.service.ISysUserService; import java.util.Map; /** * 用户验证处理 @@ -33,6 +38,9 @@ @Autowired private SysPermissionService permissionService; @Autowired private SysDeptMapper deptMapper; @Override public UserDetails loadUserByUsername(String username) { @@ -52,7 +60,21 @@ log.info("登录用户:{} 已被停用.", username); throw new ServiceException(MessageUtils.message("user.blocked")); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // 获取 details Object details = authentication.getDetails(); Long factoryId = null; if (details instanceof Map) { factoryId = (Long) ((Map<?, ?>) details).get("factoryId"); if(null != factoryId){ // 查询租户 Long teantId = deptMapper.maxLevelDeptId(factoryId); user.setCurrentDeptId(factoryId); user.setTenantId(teantId.intValue()); } } // 获取用户当前登录部门,并查询租户id passwordService.validate(user); return createLoginUser(user); @@ -60,6 +82,6 @@ public UserDetails createLoginUser(SysUser user) { return new LoginUser(user.getUserId(), user.getDeptIds(), user, user.getTenantId(), permissionService.getMenuPermission(user)); return new LoginUser(user.getUserId(), user.getDeptIds(), user, user.getTenantId(),user.getCurrentDeptId(), permissionService.getMenuPermission(user)); } } src/main/java/com/ruoyi/project/system/controller/SysLoginController.java
@@ -2,11 +2,11 @@ import java.util.List; import java.util.Set; import com.ruoyi.project.system.domain.vo.SysUserDeptVo; import com.ruoyi.project.system.service.ISysUserDeptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.*; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.framework.security.LoginBody; @@ -38,6 +38,9 @@ @Autowired private TokenService tokenService; @Autowired private ISysUserDeptService userDeptService; /** * 登录方法 @@ -94,4 +97,38 @@ List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId); return AjaxResult.success(menuService.buildMenus(menus)); } @PostMapping("/loginCheck") public AjaxResult loginCheck(@RequestBody LoginBody loginBody) { try { Long userId = loginService.loginCheck(loginBody.getUsername(), loginBody.getPassword()); return AjaxResult.success(userId); }catch (Exception e) { return AjaxResult.error(e.getMessage()); } } @GetMapping("/userDeptList/{userId}") public AjaxResult userDeptList(@PathVariable Long userId){ SysUserDeptVo sysUserDeptVo = new SysUserDeptVo(); sysUserDeptVo.setUserId(userId); return AjaxResult.success(userDeptService.selectUserDeptList(sysUserDeptVo)); } /** * 选择公司登录 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/loginCheckFactory") public AjaxResult loginCheckFactory(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 String token = loginService.loginCheckFactory(loginBody.getUsername(), loginBody.getPassword(),loginBody.getFactoryId()); ajax.put(Constants.TOKEN, token); return ajax; } } src/main/java/com/ruoyi/project/system/domain/SysUser.java
@@ -95,11 +95,21 @@ @TableField(exist = false) private Long deptId; private Long currentDeptId; /** * 部门名称 */ private String deptNames; public Long getCurrentDeptId() { return currentDeptId; } public void setCurrentDeptId(Long currentDeptId) { this.currentDeptId = currentDeptId; } public SysUser() { src/main/resources/mapper/system/SysRoleMapper.xml
@@ -27,7 +27,6 @@ from sys_role r left join sys_user_role ur on ur.role_id = r.role_id left join sys_user u on u.user_id = ur.user_id left join sys_dept d on u.dept_id = d.dept_id </sql> <select id="selectRoleList" parameterType="com.ruoyi.project.system.domain.SysRole" resultMap="SysRoleResult">