Search in sources :

Example 6 with User

use of com.hccake.ballcat.common.security.userdetails.User in project ballcat by ballcat-projects.

the class SysMenuController method getUserPermission.

/**
 * 返回当前用户的路由集合
 * @return 当前用户的路由
 */
@GetMapping("/router")
@Operation(summary = "动态路由", description = "动态路由")
public R<List<SysMenuRouterVO>> getUserPermission() {
    // 获取角色Code
    User user = SecurityUtils.getUser();
    Map<String, Object> attributes = user.getAttributes();
    Object rolesObject = attributes.get(UserAttributeNameConstants.ROLE_CODES);
    if (!(rolesObject instanceof Collection)) {
        return R.ok(new ArrayList<>());
    }
    @SuppressWarnings("unchecked") Collection<String> roleCodes = (Collection<String>) rolesObject;
    if (CollectionUtil.isEmpty(roleCodes)) {
        return R.ok(new ArrayList<>());
    }
    // 获取符合条件的权限
    Set<SysMenu> all = new HashSet<>();
    roleCodes.forEach(roleCode -> all.addAll(sysMenuService.listByRoleCode(roleCode)));
    // 筛选出菜单
    List<SysMenuRouterVO> menuVOList = all.stream().filter(menuVo -> SysMenuType.BUTTON.getValue() != menuVo.getType()).sorted(Comparator.comparingInt(SysMenu::getSort)).map(SysMenuConverter.INSTANCE::poToRouterVo).collect(Collectors.toList());
    return R.ok(menuVOList);
}
Also used : SysMenuUpdateDTO(com.hccake.ballcat.system.model.dto.SysMenuUpdateDTO) PathVariable(org.springframework.web.bind.annotation.PathVariable) SysMenuConverter(com.hccake.ballcat.system.converter.SysMenuConverter) SysMenuRouterVO(com.hccake.ballcat.system.model.vo.SysMenuRouterVO) SysMenuService(com.hccake.ballcat.system.service.SysMenuService) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) Valid(javax.validation.Valid) HashSet(java.util.HashSet) R(com.hccake.ballcat.common.model.result.R) UserAttributeNameConstants(com.hccake.ballcat.common.security.constant.UserAttributeNameConstants) Operation(io.swagger.v3.oas.annotations.Operation) PutMapping(org.springframework.web.bind.annotation.PutMapping) Map(java.util.Map) UpdateOperationLogging(com.hccake.ballcat.common.log.operation.annotation.UpdateOperationLogging) GetMapping(org.springframework.web.bind.annotation.GetMapping) SysMenuQO(com.hccake.ballcat.system.model.qo.SysMenuQO) SysMenu(com.hccake.ballcat.system.model.entity.SysMenu) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) SecurityUtils(com.hccake.ballcat.common.security.util.SecurityUtils) SysMenuType(com.hccake.ballcat.system.enums.SysMenuType) CollectionUtil(cn.hutool.core.collection.CollectionUtil) BaseResultCode(com.hccake.ballcat.common.model.result.BaseResultCode) Collection(java.util.Collection) Set(java.util.Set) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) User(com.hccake.ballcat.common.security.userdetails.User) CreateOperationLogging(com.hccake.ballcat.common.log.operation.annotation.CreateOperationLogging) List(java.util.List) SysMenuPageVO(com.hccake.ballcat.system.model.vo.SysMenuPageVO) SysMenuCreateDTO(com.hccake.ballcat.system.model.dto.SysMenuCreateDTO) Tag(io.swagger.v3.oas.annotations.tags.Tag) SysMenuGrantVO(com.hccake.ballcat.system.model.vo.SysMenuGrantVO) Comparator(java.util.Comparator) DeleteOperationLogging(com.hccake.ballcat.common.log.operation.annotation.DeleteOperationLogging) User(com.hccake.ballcat.common.security.userdetails.User) SysMenuConverter(com.hccake.ballcat.system.converter.SysMenuConverter) SysMenuRouterVO(com.hccake.ballcat.system.model.vo.SysMenuRouterVO) SysMenu(com.hccake.ballcat.system.model.entity.SysMenu) Collection(java.util.Collection) HashSet(java.util.HashSet) GetMapping(org.springframework.web.bind.annotation.GetMapping) Operation(io.swagger.v3.oas.annotations.Operation)

Example 7 with User

use of com.hccake.ballcat.common.security.userdetails.User in project ballcat by ballcat-projects.

the class UserAttributeHandshakeInterceptor method beforeHandshake.

/**
 * Invoked before the handshake is processed.
 * @param request the current request
 * @param response the current response
 * @param wsHandler the target WebSocket handler
 * @param attributes the attributes from the HTTP handshake to associate with the
 * WebSocket session; the provided attributes are copied, the original map is not
 * used.
 * @return whether to proceed with the handshake ({@code true}) or abort
 * ({@code false})
 */
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
    String accessToken = null;
    // 获得 accessToken
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
        accessToken = serverRequest.getServletRequest().getParameter(AdminWebSocketConstants.TOKEN_ATTR_NAME);
    }
    // 由于 WebSocket 握手是由 http 升级的,携带 token 已经被 Security 拦截验证了,所以可以直接获取到用户
    User user = SecurityUtils.getUser();
    attributes.put(AdminWebSocketConstants.TOKEN_ATTR_NAME, accessToken);
    attributes.put(AdminWebSocketConstants.USER_KEY_ATTR_NAME, user.getUserId());
    return true;
}
Also used : ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) User(com.hccake.ballcat.common.security.userdetails.User)

Example 8 with User

use of com.hccake.ballcat.common.security.userdetails.User in project ballcat by ballcat-projects.

the class RemoteOpaqueTokenIntrospector method buildUser.

/**
 * 根据返回值信息,反向构建出 User 对象
 * @param responseBody 响应体信息
 * @param claims attributes
 * @return User
 */
private User buildUser(JSONObject responseBody, Map<String, Object> claims) {
    User.UserBuilder builder = User.builder();
    JSONObject info = (JSONObject) responseBody.getOrDefault(TokenAttributeNameConstants.INFO, new JSONObject());
    Number userIdNumber = info.getAsNumber(UserInfoFiledNameConstants.USER_ID);
    if (userIdNumber != null) {
        builder.userId(userIdNumber.intValue());
    }
    Number typeNumber = info.getAsNumber(UserInfoFiledNameConstants.TYPE);
    if (typeNumber != null) {
        builder.type(typeNumber.intValue());
    }
    Number organizationIdNumber = info.getAsNumber(UserInfoFiledNameConstants.ORGANIZATION_ID);
    if (organizationIdNumber != null) {
        builder.organizationId(organizationIdNumber.intValue());
    }
    builder.username(info.getAsString(UserInfoFiledNameConstants.USERNAME)).nickname(info.getAsString(UserInfoFiledNameConstants.NICKNAME)).avatar(info.getAsString(UserInfoFiledNameConstants.AVATAR)).status(1);
    Object authoritiesJSONArray = responseBody.get("authorities");
    if (authoritiesJSONArray != null) {
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(((JSONArray) authoritiesJSONArray).toArray(new String[0]));
        builder.authorities(authorities);
    }
    Object attribute = responseBody.get(TokenAttributeNameConstants.ATTRIBUTES);
    if (attribute != null) {
        claims.putAll((JSONObject) attribute);
    }
    builder.attributes(claims);
    return builder.build();
}
Also used : User(com.hccake.ballcat.common.security.userdetails.User) JSONObject(net.minidev.json.JSONObject) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) JSONObject(net.minidev.json.JSONObject)

Example 9 with User

use of com.hccake.ballcat.common.security.userdetails.User in project ballcat by ballcat-projects.

the class AnnouncementLoginEventListener method onAuthenticationSuccessEvent.

/**
 * 登陆成功时间监听 用户未读公告生成
 * @param event 登陆成功 event
 */
@EventListener(AuthenticationSuccessEvent.class)
public void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) throws InterruptedException {
    AbstractAuthenticationToken source = (AbstractAuthenticationToken) event.getSource();
    Object details = source.getDetails();
    if (!(details instanceof HashMap)) {
        return;
    }
    // https://github.com/spring-projects-experimental/spring-authorization-server
    if ("password".equals(((HashMap) details).get("grant_type"))) {
        User user = (User) source.getPrincipal();
        SysUser sysUser = getSysUser(user);
        // 获取当前用户未拉取过的公告信息
        Integer userId = sysUser.getUserId();
        List<Announcement> announcements = announcementService.listUnPulled(userId);
        // 获取当前用户的各个过滤属性
        Map<Integer, Object> filterAttrs = recipientHandler.getFilterAttrs(sysUser);
        // 获取符合当前用户条件的,且接收类型包含站内的公告,保存其关联关系
        List<UserAnnouncement> userAnnouncements = announcements.stream().filter(x -> x.getReceiveMode().contains(NotifyChannelEnum.STATION.getValue())).filter(x -> filterMatched(x, filterAttrs)).map(Announcement::getId).map(id -> userAnnouncementService.prodUserAnnouncement(userId, id)).collect(Collectors.toList());
        try {
            userAnnouncementService.saveBatch(userAnnouncements);
        } catch (Exception exception) {
            log.error("用户公告保存失败:[{}]", userAnnouncements, exception);
        }
    }
}
Also used : Announcement(com.hccake.ballcat.notify.model.entity.Announcement) RequiredArgsConstructor(lombok.RequiredArgsConstructor) EventListener(org.springframework.context.event.EventListener) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) AuthenticationSuccessEvent(org.springframework.security.authentication.event.AuthenticationSuccessEvent) NotifyChannelEnum(com.hccake.ballcat.notify.enums.NotifyChannelEnum) User(com.hccake.ballcat.common.security.userdetails.User) AnnouncementService(com.hccake.ballcat.notify.service.AnnouncementService) UserAnnouncement(com.hccake.ballcat.notify.model.entity.UserAnnouncement) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) List(java.util.List) RecipientHandler(com.hccake.ballcat.notify.recipient.RecipientHandler) SysUser(com.hccake.ballcat.system.model.entity.SysUser) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) Map(java.util.Map) UserAnnouncementService(com.hccake.ballcat.notify.service.UserAnnouncementService) User(com.hccake.ballcat.common.security.userdetails.User) SysUser(com.hccake.ballcat.system.model.entity.SysUser) SysUser(com.hccake.ballcat.system.model.entity.SysUser) Announcement(com.hccake.ballcat.notify.model.entity.Announcement) UserAnnouncement(com.hccake.ballcat.notify.model.entity.UserAnnouncement) HashMap(java.util.HashMap) UserAnnouncement(com.hccake.ballcat.notify.model.entity.UserAnnouncement) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) EventListener(org.springframework.context.event.EventListener)

Example 10 with User

use of com.hccake.ballcat.common.security.userdetails.User in project ballcat by ballcat-projects.

the class SysUserDetailsServiceImpl method getUserDetailsByUserInfo.

/**
 * 根据UserInfo 获取 UserDetails
 * @param userInfoDTO 用户信息DTO
 * @return UserDetails
 */
public UserDetails getUserDetailsByUserInfo(UserInfoDTO userInfoDTO) {
    SysUser sysUser = userInfoDTO.getSysUser();
    Collection<String> roleCodes = userInfoDTO.getRoleCodes();
    Collection<String> permissions = userInfoDTO.getPermissions();
    Collection<String> dbAuthsSet = new HashSet<>();
    if (CollectionUtil.isNotEmpty(roleCodes)) {
        // 获取角色
        dbAuthsSet.addAll(roleCodes);
        // 获取资源
        dbAuthsSet.addAll(permissions);
    }
    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
    // 默认将角色和权限放入属性中
    HashMap<String, Object> attributes = new HashMap<>(8);
    attributes.put(UserAttributeNameConstants.ROLE_CODES, roleCodes);
    attributes.put(UserAttributeNameConstants.PERMISSIONS, permissions);
    // 用户额外属性
    userInfoCoordinator.coordinateAttribute(userInfoDTO, attributes);
    return new User(sysUser.getUserId(), sysUser.getUsername(), sysUser.getPassword(), sysUser.getNickname(), sysUser.getAvatar(), sysUser.getStatus(), sysUser.getOrganizationId(), sysUser.getType(), authorities, attributes);
}
Also used : User(com.hccake.ballcat.common.security.userdetails.User) SysUser(com.hccake.ballcat.system.model.entity.SysUser) SysUser(com.hccake.ballcat.system.model.entity.SysUser) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Aggregations

User (com.hccake.ballcat.common.security.userdetails.User)10 HashMap (java.util.HashMap)3 Map (java.util.Map)3 SysUser (com.hccake.ballcat.system.model.entity.SysUser)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 RequiredArgsConstructor (lombok.RequiredArgsConstructor)2 CollectionUtil (cn.hutool.core.collection.CollectionUtil)1 CreateOperationLogging (com.hccake.ballcat.common.log.operation.annotation.CreateOperationLogging)1 DeleteOperationLogging (com.hccake.ballcat.common.log.operation.annotation.DeleteOperationLogging)1 UpdateOperationLogging (com.hccake.ballcat.common.log.operation.annotation.UpdateOperationLogging)1 BaseResultCode (com.hccake.ballcat.common.model.result.BaseResultCode)1 R (com.hccake.ballcat.common.model.result.R)1 UserAttributeNameConstants (com.hccake.ballcat.common.security.constant.UserAttributeNameConstants)1 SecurityUtils (com.hccake.ballcat.common.security.util.SecurityUtils)1 OperationLog (com.hccake.ballcat.log.model.entity.OperationLog)1 NotifyChannelEnum (com.hccake.ballcat.notify.enums.NotifyChannelEnum)1 Announcement (com.hccake.ballcat.notify.model.entity.Announcement)1