| | |
| | | package com.sandu.ximon.admin.controller; |
| | | |
| | | import cn.hutool.core.collection.CollectionUtil; |
| | | import cn.hutool.core.map.MapBuilder; |
| | | import cn.hutool.core.map.MapUtil; |
| | | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; |
| | | import cn.hutool.core.util.StrUtil; |
| | | import com.baomidou.mybatisplus.core.toolkit.Wrappers; |
| | | import com.github.pagehelper.PageHelper; |
| | | import com.sandu.common.domain.ResponseVO; |
| | | import com.sandu.common.enums.AdminStatusStatus; |
| | | import com.sandu.common.enums.ResponseStatusEnums; |
| | | import com.sandu.common.enums.RoleLevelStatus; |
| | | import com.sandu.common.execption.BusinessException; |
| | | import com.sandu.common.log.Log; |
| | | import com.sandu.common.object.BaseConditionVO; |
| | | import com.sandu.common.redis.RedisService; |
| | | import com.sandu.common.security.LoginUserInfo; |
| | | import com.sandu.common.security.annotation.AnonymousAccess; |
| | | import com.sandu.common.security.config.SecurityProperties; |
| | | import com.sandu.common.security.jwt.JwtTokenProvider; |
| | | import com.sandu.common.security.token.TokenProvider; |
| | | import com.sandu.common.util.IpUtil; |
| | | import com.sandu.common.util.ResponseUtil; |
| | | import com.sandu.ximon.admin.dto.AdminJwtUser; |
| | | import com.sandu.ximon.admin.param.AdminLoginParam; |
| | | import com.sandu.ximon.admin.param.*; |
| | | import com.sandu.ximon.admin.security.PermissionConfig; |
| | | import com.sandu.ximon.admin.security.SecurityUtils; |
| | | import com.sandu.ximon.admin.service.AdminService; |
| | | import com.sandu.ximon.admin.service.MenuService; |
| | | import com.sandu.ximon.admin.service.RoleService; |
| | | import com.sandu.ximon.dao.domain.Admin; |
| | | import com.sandu.ximon.dao.domain.Menu; |
| | | import com.sandu.ximon.dao.domain.Role; |
| | | import com.sandu.ximon.admin.service.*; |
| | | import com.sandu.ximon.admin.utils.RedisUtils; |
| | | import com.sandu.ximon.dao.bo.MenuNode; |
| | | import com.sandu.ximon.dao.domain.*; |
| | | import com.sandu.ximon.dao.enums.AdministratorEnums; |
| | | import com.sandu.ximon.dao.enums.MenuEnum; |
| | | import lombok.AllArgsConstructor; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import org.springframework.security.access.prepost.PreAuthorize; |
| | | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| | | import org.springframework.security.core.context.SecurityContextHolder; |
| | | import org.springframework.security.core.userdetails.UserDetails; |
| | | import org.springframework.beans.BeanUtils; |
| | | import org.springframework.security.core.GrantedAuthority; |
| | | import org.springframework.security.crypto.password.PasswordEncoder; |
| | | import org.springframework.validation.annotation.Validated; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.time.LocalDateTime; |
| | | import java.util.Collections; |
| | | import java.util.Collection; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | import java.util.stream.Collectors; |
| | | |
| | | /** |
| | | * @author hupeng |
| | | * @date 2018-11-23 |
| | | * 授权、根据token获取用户详细信息 |
| | | * @author chenjiantian |
| | | * @date 2022/1/18 16:04 |
| | | * 管理员控制类 |
| | | */ |
| | | @Slf4j |
| | | @RestController |
| | | @AllArgsConstructor |
| | | @RequestMapping("v1/admin") |
| | | @RequestMapping("/v1/admin") |
| | | public class AdminController { |
| | | |
| | | private final SecurityProperties properties; |
| | | private final MenuService menuService; |
| | | private final PasswordEncoder passwordEncoder; |
| | | private final AdminService adminService; |
| | | private final ClientService clientService; |
| | | private final RoleService roleService; |
| | | private final JwtTokenProvider tokenProvider; |
| | | private final TokenProvider tokenProvider; |
| | | private final AdminRoleRelationService adminRoleRelationService; |
| | | private PermissionConfig permissionConfig; |
| | | private final RedisService redisService; |
| | | |
| | | |
| | | @Log("后台用户登录") |
| | | @AnonymousAccess |
| | | @PostMapping(value = "/login") |
| | | public ResponseVO<Object> login(@RequestBody AdminLoginParam loginParam) { |
| | | public ResponseVO<Object> login(HttpServletRequest request, @RequestBody AdminLoginParam loginParam) { |
| | | Admin admin = adminService.getOne(Wrappers.lambdaQuery(Admin.class).eq(Admin::getUsername, loginParam.getUsername()).last("limit 1")); |
| | | if (admin == null) { |
| | | return ResponseUtil.error(ResponseStatusEnums.BAD_CREDENTIALS.getCode(), ResponseStatusEnums.BAD_CREDENTIALS.getMessage()); |
| | | } |
| | | // String session_vcode = (String) request.getSession().getAttribute(loginParam.getKey()); |
| | | String s = RedisUtils.getBean().get(loginParam.getKey()); |
| | | System.out.println(s + "==========================="); |
| | | if (!loginParam.getVlue().equals(s)) { |
| | | log.error(loginParam.getVlue() + "验证码"); |
| | | return ResponseUtil.error(ResponseStatusEnums.BAD_AUTHENTICATION.getCode(), ResponseStatusEnums.BAD_AUTHENTICATION.getMessage()); |
| | | } |
| | | RedisUtils.getBean().delete(loginParam.getKey()); |
| | | if (!passwordEncoder.matches(loginParam.getPassword(), admin.getPassword())) { |
| | | return ResponseUtil.error(ResponseStatusEnums.BAD_CREDENTIALS.getCode(), ResponseStatusEnums.BAD_CREDENTIALS.getMessage()); |
| | | } |
| | | UserDetails userJwtUser = new AdminJwtUser(admin, roleService.mapToGrantedAuthorities(admin.getId())); |
| | | UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userJwtUser, admin.getId(), userJwtUser.getAuthorities()); |
| | | if (AdminStatusStatus.DISABLE.getCode().equals(admin.getStatus())) { |
| | | return ResponseUtil.error(ResponseStatusEnums.DISABLE_ACCOUNT.getCode(), ResponseStatusEnums.DISABLE_ACCOUNT.getMessage()); |
| | | } |
| | | |
| | | SecurityContextHolder.getContext().setAuthentication(authentication); |
| | | Collection<GrantedAuthority> grantedAuthorities = roleService.mapToGrantedAuthorities(admin.getId(), true); |
| | | |
| | | LoginUserInfo loginUserInfo = new LoginUserInfo(); |
| | | loginUserInfo.setUserId(admin.getId()); |
| | | loginUserInfo.setName(admin.getNickName()); |
| | | loginUserInfo.setAccount(admin.getUsername()); |
| | | loginUserInfo.setStatus(admin.getStatus()); |
| | | loginUserInfo.setIp(IpUtil.getRealIp()); |
| | | |
| | | //确定用户角色权限 |
| | | AdminRoleRelation adminRoleRelation = adminRoleRelationService.getOne(Wrappers.lambdaQuery(AdminRoleRelation.class).eq(AdminRoleRelation::getAdminId, loginUserInfo.getUserId())); |
| | | Role role = roleService.getOne(Wrappers.lambdaQuery(Role.class).eq(Role::getId, adminRoleRelation.getRoleId())); |
| | | if (role != null && role.getLevel().equals(RoleLevelStatus.SUPER.getCode())) { |
| | | loginUserInfo.setAdministratorType(AdministratorEnums.ADMIN.getCode()); |
| | | } else { |
| | | loginUserInfo.setAdministratorType(AdministratorEnums.CUSTOMER.getCode()); |
| | | } |
| | | |
| | | loginUserInfo.setPermission(grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","))); |
| | | |
| | | // 生成令牌 |
| | | String token = tokenProvider.createToken(authentication); |
| | | final AdminJwtUser jwtUser = (AdminJwtUser) authentication.getPrincipal(); |
| | | String token = tokenProvider.createToken(loginUserInfo); |
| | | |
| | | // 更新最后登录时间 |
| | | Admin update = new Admin(); |
| | |
| | | // 返回 token 与 用户信息 |
| | | Map<String, Object> authInfo = new HashMap<String, Object>(2) {{ |
| | | put("token", properties.getTokenStartWith() + token); |
| | | put("user", jwtUser); |
| | | put("user", admin); |
| | | }}; |
| | | // if (singleLogin) { |
| | | // //踢掉之前已经登录的token |
| | | // onlineUserService.checkLoginOnUser(authUser.getUsername(), token); |
| | | // } |
| | | return ResponseUtil.success(authInfo); |
| | | } |
| | | |
| | | // @Log("后台用户信息") |
| | | @GetMapping(value = "/info") |
| | | public ResponseVO<Object> getUserInfo() { |
| | | System.out.println(SecurityUtils.getUserDetails().getAdministratorType() + " ---------"); |
| | | Long userId = SecurityUtils.getUserId(); |
| | | Admin admin = adminService.getById(userId); |
| | | List<Role> roles = roleService.listByAdminId(admin.getId()); |
| | | List<Role> roles; |
| | | MapBuilder<Object, Object> builder; |
| | | if (AdministratorEnums.ADMIN.getCode().equals(SecurityUtils.getAdministratorIdentity()) |
| | | || AdministratorEnums.CUSTOMER.getCode().equals(SecurityUtils.getAdministratorIdentity())) { |
| | | Admin admin = adminService.getById(userId); |
| | | roles = roleService.listByAdminId(admin.getId()); |
| | | builder = MapUtil.builder().put("admin", admin); |
| | | |
| | | } else { |
| | | Client client = clientService.getById(userId); |
| | | roles = roleService.listByClientId(client.getId()); |
| | | //为了保持返回数据格式一致 |
| | | Admin admin = new Admin(); |
| | | admin.setId(client.getId()); |
| | | admin.setIcon(client.getIcon()); |
| | | admin.setNickName(client.getLinkMan()); |
| | | admin.setMobile(client.getMobile()); |
| | | admin.setLoginTime(client.getLoginTime()); |
| | | admin.setCreateTime(client.getCreateTime()); |
| | | builder = MapUtil.builder().put("admin", admin); |
| | | |
| | | } |
| | | if (CollectionUtil.isEmpty(roles)) { |
| | | return ResponseUtil.fail("用户没有角色,无法获取数据"); |
| | | } |
| | | List<Menu> menus = menuService.listByRoleIds(roles.stream().map(Role::getId).collect(Collectors.toList())); |
| | | List<Menu> collect = menus.stream().filter(menu -> menu.getType() == 0).collect(Collectors.toList()); |
| | | Map<Object, Object> build = MapUtil.builder().put("info", admin).put("menus", collect).build(); |
| | | return ResponseUtil.success(build); |
| | | if (CollectionUtil.isNotEmpty(menus)) { |
| | | List<Menu> collect = menus.stream().filter(menu -> menu.getType() == 0 || menu.getType() == 1).collect(Collectors.toList()); |
| | | |
| | | List<MenuNode> menuNodeList = collect.stream() |
| | | .filter(menu -> menu.getPid().equals(0L)) |
| | | .map(menu -> covertMenuNode(menu, collect)).collect(Collectors.toList()); |
| | | builder.put("menus", menuNodeList); |
| | | } |
| | | return ResponseUtil.success(builder.build()); |
| | | } |
| | | |
| | | @GetMapping(value = "/logout") |
| | | public ResponseVO<Object> LogOut() { |
| | | // redisService.set(UserModel.USER_INFO.key(SecurityUtils.getUserId().toString() + SecurityUtils.getUserDetails().getAdministratorType()), null); |
| | | // redisService.set(UserModel.USER_TOKEN.key(UserModel.USER_TOKEN.key(SecurityUtils.getUserDetails().getToken())), null); |
| | | |
| | | |
| | | String key = String.format("%d_%d", SecurityUtils.getUserDetails().getUserId(), SecurityUtils.getUserDetails().getAdministratorType()); |
| | | redisService.set(key, null); |
| | | return ResponseUtil.success("退出登录成功"); |
| | | } |
| | | |
| | | private MenuNode covertMenuNode(Menu menu, List<Menu> menuList) { |
| | | MenuNode node = new MenuNode(); |
| | | BeanUtils.copyProperties(menu, node); |
| | | List<MenuNode> children = menuList.stream() |
| | | .filter(subMenu -> subMenu.getPid().equals(menu.getId())) |
| | | .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList()); |
| | | node.setChildren(children); |
| | | return node; |
| | | } |
| | | |
| | | @Log("后台用户列表") |
| | | @GetMapping(value = "/list") |
| | | public ResponseVO<Object> listAdmin(BaseConditionVO baseConditionVO, @RequestParam(value = "keyword", required = false) String keyword) { |
| | | PageHelper.startPage(baseConditionVO.getPageNo(), baseConditionVO.getPageSize()); |
| | | LambdaQueryWrapper<Admin> wrapper = Wrappers.lambdaQuery(Admin.class); |
| | | if (keyword != null) { |
| | | wrapper.like(Admin::getNickName, keyword) |
| | | .or(adminLambdaQueryWrapper -> { |
| | | adminLambdaQueryWrapper.like(Admin::getUsername, keyword); |
| | | }); |
| | | if (!permissionConfig.check(MenuEnum.ADMIN_LIST.getCode())) { |
| | | return ResponseUtil.fail("缺少对应用户权限"); |
| | | } |
| | | List<Admin> list = adminService.list(wrapper); |
| | | return ResponseUtil.successPage(list); |
| | | return ResponseUtil.successPage(adminService.listAdmin(baseConditionVO, keyword)); |
| | | |
| | | // PageHelper.startPage(baseConditionVO.getPageNo(), baseConditionVO.getPageSize()); |
| | | // LambdaQueryWrapper<Admin> wrapper = Wrappers.lambdaQuery(Admin.class); |
| | | // if (keyword != null) { |
| | | // wrapper.like(Admin::getNickName, keyword) |
| | | // .or(adminLambdaQueryWrapper -> { |
| | | // adminLambdaQueryWrapper.like(Admin::getUsername, keyword); |
| | | // }); |
| | | // } |
| | | // List<Admin> list = adminService.list(wrapper); |
| | | // |
| | | // List<AdminDto> adminDtoList = new ArrayList<>(); |
| | | // for (Admin demo : list) { |
| | | // AdminDto adminDto = new AdminDto(); |
| | | // BeanUtil.copyProperties(demo, adminDto); |
| | | // AdminRoleRelation one = adminRoleRelationService.getOne(Wrappers.lambdaQuery(AdminRoleRelation.class) |
| | | // .eq(AdminRoleRelation::getAdminId, demo.getId())); |
| | | // |
| | | // if (one != null) { |
| | | // adminDto.setRoleId(one.getRoleId()); |
| | | // } |
| | | // adminDtoList.add(adminDto); |
| | | // |
| | | // } |
| | | // return ResponseUtil.successPage(adminDtoList); |
| | | } |
| | | |
| | | // @PreAuthorize("@el.check('admin:add')") |
| | | // @PostMapping("/register") |
| | | // public ResponseVO<Object> register(@Validated @RequestBody AdminParam adminParam) { |
| | | // Admin admin = adminService.register(adminParam); |
| | | // return ResponseUtil.success(admin); |
| | | // } |
| | | @Log("后台用户注册") |
| | | @PostMapping("/register") |
| | | public ResponseVO<Object> register(@Validated @RequestBody AdminParam param) { |
| | | if (!permissionConfig.check(MenuEnum.ADMIN_ADD.getCode())) { |
| | | return ResponseUtil.fail("缺少对应用户权限"); |
| | | } |
| | | boolean result = adminService.register(param); |
| | | if (result) { |
| | | return ResponseUtil.success("注册用户成功"); |
| | | } else { |
| | | return ResponseUtil.fail("注册用户失败"); |
| | | } |
| | | } |
| | | |
| | | // /** |
| | | // * 修改管理员信息 |
| | | // * |
| | | // * @param resources |
| | | // * @return |
| | | // */ |
| | | // @PutMapping("/{id}") |
| | | // @PreAuthorize("@el.check('admin:edit')") |
| | | // public ResponseVO<Object> update(@RequestBody AdminParam resources, @PathVariable Long id) { |
| | | // checkLevel(id); |
| | | // adminService.updateAdmin(id, resources); |
| | | // return ResponseUtil.success(null); |
| | | // } |
| | | // |
| | | // @PutMapping("/updatePassword") |
| | | // public ResponseVO<Object> updatePassword(@Validated @RequestBody PwdParam param) { |
| | | // Long userId = SecurityUtils.getUserId(); |
| | | // adminService.updatePassword(userId, param); |
| | | // return ResponseUtil.success(null); |
| | | // } |
| | | |
| | | /** |
| | | * 修改管理员信息 |
| | | */ |
| | | @Log("后台用户修改信息") |
| | | @PostMapping("/update/{adminId}") |
| | | public ResponseVO<Object> updateAdmin(@RequestBody AdminParam param, @PathVariable Long adminId) { |
| | | if (!permissionConfig.check(MenuEnum.ADMIN_INFO_UPDATE.getCode())) { |
| | | return ResponseUtil.fail("缺少对应用户权限"); |
| | | } |
| | | boolean result = adminService.updateAdmin(adminId, param); |
| | | if (result) { |
| | | return ResponseUtil.success("修改成功"); |
| | | } else { |
| | | return ResponseUtil.fail("修改失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 修改我的密码 |
| | | */ |
| | | @Log("修改当前用户密码") |
| | | @PostMapping("/updateMyPassword") |
| | | public ResponseVO<Object> updateMyPassword(@Validated @RequestBody PwdParam param) { |
| | | boolean result; |
| | | if (SecurityUtils.getClientId() == null) { |
| | | result = adminService.updateMyPassword(param); |
| | | } else { |
| | | result = clientService.resetPassword(param); |
| | | } |
| | | |
| | | if (result) { |
| | | return ResponseUtil.success("修改成功"); |
| | | } else { |
| | | return ResponseUtil.fail("修改失败"); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 修改管理员的密码 |
| | | */ |
| | | @Log("修改管理员的密码") |
| | | @PostMapping("/updateAdminPassword") |
| | | public ResponseVO<Object> updateAdminPassword(@Validated @RequestBody UserPwsParm param) { |
| | | if (!SecurityUtils.getUserDetails().getAdministratorType().equals(AdministratorEnums.ADMIN.getCode())) { |
| | | throw new BusinessException("非超级管理员无法修改密码!"); |
| | | } |
| | | |
| | | boolean result = adminService.updateAdminPassword(param); |
| | | |
| | | if (result) { |
| | | return ResponseUtil.success("修改成功"); |
| | | } else { |
| | | return ResponseUtil.fail("修改失败"); |
| | | } |
| | | } |
| | | |
| | | // @PutMapping("/updateStatus/{id}") |
| | | // public ResponseVO<Object> updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) { |
| | |
| | | // return ResponseUtil.success(null); |
| | | // } |
| | | |
| | | // @DeleteMapping("/{id}") |
| | | // @PreAuthorize("@el.check('admin:del')") |
| | | // public ResponseVO<Object> delete(@PathVariable Long id) { |
| | | // checkLevel(id); |
| | | // adminService.deleteAdmin(id); |
| | | // return ResponseUtil.success(null); |
| | | // } |
| | | @Log("后台用户删除") |
| | | @PostMapping("/del/{adminId}") |
| | | public ResponseVO<Object> deleteAdmin(@PathVariable Long adminId) { |
| | | if (!permissionConfig.check(MenuEnum.ADMIN_DELETE.getCode())) { |
| | | return ResponseUtil.fail("缺少对应用户权限"); |
| | | } |
| | | boolean result = adminService.deleteAdmin(adminId); |
| | | if (result) { |
| | | return ResponseUtil.success("修改成功"); |
| | | } else { |
| | | return ResponseUtil.fail("修改失败"); |
| | | } |
| | | } |
| | | |
| | | @Log("用户修改头像") |
| | | @PostMapping("/updateIcon") |
| | | public ResponseVO<Object> updateIcon(@RequestBody ReceiveParam receiveParam) { |
| | | if (receiveParam.getIconUrl().trim() == null) { |
| | | throw new BusinessException("头像URL不能为空!"); |
| | | } |
| | | boolean result; |
| | | //普通用户修改头像 |
| | | if (SecurityUtils.getAdministratorIdentity().equals(AdministratorEnums.NORMAL.getCode())) { |
| | | result = clientService.updateIcon(SecurityUtils.getUserId(), receiveParam.getIconUrl()); |
| | | } else { |
| | | //超级管理员、管理员修改头像 |
| | | result = adminService.updateIcon(SecurityUtils.getUserId(), receiveParam.getIconUrl()); |
| | | } |
| | | |
| | | if (result) { |
| | | return ResponseUtil.success("修改成功"); |
| | | } else { |
| | | return ResponseUtil.fail("修改失败"); |
| | | } |
| | | } |
| | | |
| | | // /** |
| | | // * 给管理员分配角色 |
| | |
| | | // return ResponseUtil.success(""); |
| | | // } |
| | | |
| | | /** |
| | | * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误 |
| | | * |
| | | * @param updateId 被操作人的id |
| | | */ |
| | | private void checkLevel(Long updateId) { |
| | | Admin admin = adminService.findByUserName(SecurityUtils.getUsername()); |
| | | // 获取操作者最大权限 |
| | | Integer currentLevel = Collections.min(roleService.listByAdminId(admin.getId()).stream().map(Role::getLevel).collect(Collectors.toList())); |
| | | // 获取被编辑人的最大权限 |
| | | List<Integer> optList = roleService.listByAdminId(updateId).stream().map(Role::getLevel).collect(Collectors.toList()); |
| | | // 没权限 随便操作 |
| | | if (CollectionUtil.isEmpty(optList)) { |
| | | return; |
| | | } |
| | | Integer optLevel = Collections.min(optList); |
| | | if (optLevel != null) { |
| | | if (currentLevel > optLevel) { |
| | | throw new BusinessException("权限不足,你的角色级别:" + currentLevel + ",低于操作的角色级别:" + optLevel); |
| | | } |
| | | } |
| | | } |
| | | |
| | | // /** |
| | | // * 编辑我的信息 |