feat(商城): 代码优化

master
wayn 1 year ago
parent 400b8cc3bb
commit 7bdb327605

@ -1,7 +1,7 @@
package com.wayn.admin.api.controller.system;
import com.wayn.admin.framework.security.service.LoginService;
import com.wayn.admin.framework.security.service.SysPermissionService;
import com.wayn.admin.framework.security.service.PermissionService;
import com.wayn.admin.framework.security.service.TokenService;
import com.wayn.common.constant.SysConstants;
import com.wayn.common.core.domain.system.Menu;
@ -36,7 +36,7 @@ import java.util.concurrent.TimeUnit;
public class LoginController {
private LoginService loginService;
private TokenService tokenService;
private SysPermissionService sysPermissionService;
private PermissionService permissionService;
private IMenuService iMenuService;
private RedisCache redisCache;
@ -60,8 +60,8 @@ public class LoginController {
R success = R.success();
LoginUserDetail loginUser = tokenService.getLoginUser(request);
User user = loginUser.getUser();
Set<String> rolePermission = sysPermissionService.getRolePermission(user);
Set<String> menuPermission = sysPermissionService.getMenuPermission(user);
Set<String> rolePermission = permissionService.getRolePermission(user);
Set<String> menuPermission = permissionService.getMenuPermission(rolePermission);
success.add("user", user);
success.add("roles", rolePermission);
success.add("permissions", menuPermission);

@ -18,9 +18,6 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
@ -98,18 +95,4 @@ public class SecurityConfig {
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}

@ -33,7 +33,7 @@ public class LoginService {
if (e instanceof BadCredentialsException) {
throw new BadCredentialsException(e.getMessage(), e);
} else {
throw new BusinessException(e.getMessage());
throw new BusinessException(e.getMessage(), e);
}
}
LoginUserDetail principal = (LoginUserDetail) authentication.getPrincipal();

@ -1,34 +1,29 @@
package com.wayn.admin.framework.security.service;
import com.wayn.common.constant.SysConstants;
import com.wayn.common.core.domain.system.Role;
import com.wayn.common.core.domain.system.User;
import com.wayn.common.core.model.LoginUserDetail;
import com.wayn.common.core.service.system.IMenuService;
import com.wayn.common.core.service.system.IRoleService;
import com.wayn.common.core.service.system.IUserService;
import com.wayn.common.util.ServletUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Service("ss")
@AllArgsConstructor
public class PermissionService {
/**
*
*/
private static final String ALL_PERMISSION = "*:*:*";
/**
*
*/
private static final String SUPER_ADMIN = "admin";
private static final String ROLE_DELIMETER = ",";
private static final String PERMISSION_DELIMETER = ",";
private TokenService tokenService;
private IUserService userService;
private IRoleService roleService;
private IMenuService menuService;
/**
*
@ -72,7 +67,7 @@ public class PermissionService {
return false;
}
Set<String> authorities = loginUser.getPermissions();
for (String permission : permissions.split(PERMISSION_DELIMETER)) {
for (String permission : permissions.split(SysConstants.PERMISSION_DELIMETER)) {
if (permission != null && hasPermissions(authorities, permission)) {
return true;
}
@ -96,7 +91,7 @@ public class PermissionService {
}
for (Role sysRole : loginUser.getUser().getRoles()) {
String roleKey = sysRole.getRoleKey();
if (SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role))) {
if (SysConstants.SUPER_ADMIN.contains(roleKey) || roleKey.contains(StringUtils.trim(role))) {
return true;
}
}
@ -127,7 +122,7 @@ public class PermissionService {
if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) {
return false;
}
for (String role : roles.split(ROLE_DELIMETER)) {
for (String role : roles.split(SysConstants.ROLE_DELIMETER)) {
if (hasRole(role)) {
return true;
}
@ -143,6 +138,43 @@ public class PermissionService {
* @return
*/
private boolean hasPermissions(Set<String> permissions, String permission) {
return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
return permissions.contains(SysConstants.ALL_PERMISSION)
|| permissions.contains(StringUtils.trim(permission));
}
/**
*
*
* @param user
* @return
*/
public Set<String> getRolePermission(User user) {
Set<String> roles = new HashSet<>();
// 管理员拥有所有权限
if (user.isAdmin()) {
roles.add("admin");
} else {
roles.addAll(roleService.selectRoleKeyByUserId(user.getUserId()));
}
return roles;
}
/**
*
*
* @param roleKeys
* @return
*/
public Set<String> getMenuPermission(Set<String> roleKeys) {
Set<String> perms = new HashSet<>();
// 管理员拥有所有权限
if (roleKeys.contains(SysConstants.SUPER_ADMIN)) {
perms.add("*:*:*");
} else {
for (String roleKey : roleKeys) {
perms.addAll(menuService.selectMenuPermsByRoleKey(roleKey));
}
}
return perms;
}
}

@ -1,55 +0,0 @@
package com.wayn.admin.framework.security.service;
import com.wayn.common.core.domain.system.User;
import com.wayn.common.core.service.system.IMenuService;
import com.wayn.common.core.service.system.IRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
@Component
@AllArgsConstructor
public class SysPermissionService {
private IRoleService roleService;
private IMenuService menuService;
/**
*
*
* @param user
* @return
*/
public Set<String> getRolePermission(User user) {
Set<String> roles = new HashSet<>();
// 管理员拥有所有权限
if (user.isAdmin()) {
roles.add("admin");
} else {
roles.addAll(roleService.selectRoleByUserId(user.getUserId()));
}
return roles;
}
/**
*
*
* @param user
* @return
*/
public Set<String> getMenuPermission(User user) {
Set<String> perms = new HashSet<>();
// 管理员拥有所有权限
if (user.isAdmin()) {
perms.add("*:*:*");
} else {
perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
}
return perms;
}
}

@ -16,6 +16,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.Set;
@Slf4j
@Service
@ -26,7 +27,7 @@ public class UserDetailsServiceImpl implements UserDetailsService {
private IDeptService iDeptService;
private SysPermissionService permissionService;
private PermissionService permissionService;
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
@ -35,17 +36,23 @@ public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1. 读取数据库中当前用户信息
User user = iUserService.getOne(new QueryWrapper<User>().eq("user_name", username));
// 2. 判断该用户是否存在
if (user == null) {
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
// 3. 判断是否禁用
if (Objects.equals(UserStatusEnum.DISABLE.getCode(), user.getUserStatus())) {
log.info("登录用户:{} 已经被停用.", username);
throw new DisabledException("登录用户:" + username + " 不存在");
}
user.setDept(iDeptService.getById(user.getDeptId()));
return new LoginUserDetail(user, permissionService.getMenuPermission(user));
// 4. 获取当前用户的角色信息
Set<String> rolePermission = permissionService.getRolePermission(user);
// 5. 根据角色获取权限信息
Set<String> menuPermission = permissionService.getMenuPermission(rolePermission);
return new LoginUserDetail(user, menuPermission);
}
}

@ -37,6 +37,23 @@ public class SysConstants {
*/
public static final String TOKEN_PREFIX = "Bearer ";
// ------------------------------------------------ 角色常量 ------------------------------------------------------------------------
/**
*
*/
public static final String ALL_PERMISSION = "*:*:*";
/**
*
*/
public static final String SUPER_ADMIN = "admin";
public static final String ROLE_DELIMETER = ",";
public static final String PERMISSION_DELIMETER = ",";
// ------------------------------------------------ 菜单常量 ------------------------------------------------------------------------
/**
* M C F

@ -6,11 +6,13 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wayn.common.base.entity.BaseEntity;
import com.wayn.common.constant.SysConstants;
import com.wayn.common.enums.domain.StatusConverter;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import java.io.Serial;
import java.util.List;
@ -78,12 +80,12 @@ public class Role extends BaseEntity {
}
public static boolean isAdmin(Long roleId) {
return roleId != null && 1L == roleId;
public static boolean isAdmin(String roleKey) {
return StringUtils.isNotBlank(roleKey) && SysConstants.SUPER_ADMIN.equals(roleKey);
}
public boolean isAdmin() {
return isAdmin(this.roleId);
return isAdmin(this.roleKey);
}
}

@ -17,6 +17,7 @@ import lombok.EqualsAndHashCode;
import java.io.Serial;
import java.util.List;
import java.util.Set;
/**
* sys_user

@ -15,4 +15,6 @@ public interface MenuMapper extends BaseMapper<Menu> {
List<Menu> selectMenuListByUserId(Menu menu, Long userId);
List<Menu> selectMenuList(Menu menu);
List<String> selectMenuPermsByRoleKey(String roleKey);
}

@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wayn.common.core.domain.system.Role;
import java.util.Collection;
import java.util.List;
public interface RoleMapper extends BaseMapper<Role> {
@ -18,4 +19,6 @@ public interface RoleMapper extends BaseMapper<Role> {
List<Role> selectRoleList(Role role);
List<Role> selectRolesByUserName(String userName);
Collection<String> selectRoleKeyByUserId(Long userId);
}

@ -18,12 +18,12 @@ public interface IMenuService extends IService<Menu> {
List<Menu> list(Menu menu);
/**
* id
* key
*
* @param userId
* @return
*/
List<String> selectMenuPermsByUserId(Long userId);
List<String> selectMenuPermsByRoleKey(String roleKey);
/**
* id

@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wayn.common.core.domain.system.Role;
import java.util.Collection;
import java.util.List;
public interface IRoleService extends IService<Role> {
@ -95,4 +96,6 @@ public interface IRoleService extends IService<Role> {
* @return int
*/
long countUserRoleByRoleId(Long roleId);
Collection<String> selectRoleKeyByUserId(Long userId);
}

@ -37,8 +37,8 @@ public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IM
}
@Override
public List<String> selectMenuPermsByUserId(Long userId) {
return menuMapper.selectMenuPermsByUserId(userId);
public List<String> selectMenuPermsByRoleKey(String roleKey) {
return menuMapper.selectMenuPermsByRoleKey(roleKey);
}
@Override

@ -18,6 +18,7 @@ import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@ -103,6 +104,11 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IR
return iUserRoleService.count(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getRoleId, roleId));
}
@Override
public Collection<String> selectRoleKeyByUserId(Long userId) {
return roleMapper.selectRoleKeyByUserId(userId);
}
@Override
public IPage<Role> listPage(Page<Role> page, Role role) {
return roleMapper.selectRoleListPage(page, role);

@ -3,6 +3,7 @@ package com.wayn.common.exception;
import com.wayn.common.enums.ReturnCodeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.elasticsearch.client.ml.SetUpgradeModeRequest;
import java.io.Serial;
@ -20,12 +21,19 @@ public class BusinessException extends RuntimeException {
private String msg;
public BusinessException(ReturnCodeEnum returnCodeEnum) {
super(returnCodeEnum.getMsg());
this.code = returnCodeEnum.getCode();
this.msg = returnCodeEnum.getMsg();
}
public BusinessException(String msg) {
super(msg);
this.msg = msg;
this.code = ReturnCodeEnum.CUSTOM_ERROR.getCode();
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}

@ -28,9 +28,9 @@ public class GlobalExceptionHandler {
public R businessException(BusinessException e) {
log.error(e.getMessage(), e);
if (Objects.isNull(e.getCode())) {
return R.error(ReturnCodeEnum.CUSTOM_ERROR.setMsg(e.getMessage()));
return R.error(ReturnCodeEnum.CUSTOM_ERROR.setMsg(e.getMsg()));
}
return R.error(e.getCode(), e.getMessage());
return R.error(e.getCode(), e.getMsg());
}
/**

@ -78,4 +78,13 @@
</where>
order by m.parent_id, m.sort
</select>
<select id="selectMenuPermsByRoleKey" resultType="java.lang.String">
select distinct m.perms
from sys_menu m
left join sys_role_menu rm on m.menu_id = rm.menu_id
left join sys_role r on r.role_id = rm.role_id
where m.menu_status = '0' and r.role_status = '0' and r.role_key = #{roleKey}
</select>
</mapper>

@ -81,4 +81,12 @@
<include refid="selectRoleVo"/>
WHERE r.del_flag = 0 and u.user_name = #{userName}
</select>
</mapper>
<select id="selectRoleKeyByUserId" resultType="java.lang.String">
SELECT r.role_key
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
WHERE r.del_flag = 0 and ur.user_id = #{userId}
</select>
</mapper>

Loading…
Cancel
Save