Search in sources :

Example 1 with UserSessionDTO

use of cn.edu.sdu.qd.oj.common.entity.UserSessionDTO in project sduoj-server by SDUOJ.

the class UserController method register.

@PostMapping("/register")
@ResponseBody
public ResponseResult<UserSessionDTO> register(HttpServletResponse response, @Valid @RequestBody UserDTO userDTO, @RealIp String ipv4, @RequestHeader("user-agent") String userAgent) {
    userDTO.setRoles(null);
    UserSessionDTO userSessionDTO = this.userService.register(userDTO, ipv4, userAgent);
    writeSessionToHeader(response, userSessionDTO);
    return ResponseResult.ok(userSessionDTO);
}
Also used : UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) ApiResponseBody(cn.edu.sdu.qd.oj.common.entity.ApiResponseBody)

Example 2 with UserSessionDTO

use of cn.edu.sdu.qd.oj.common.entity.UserSessionDTO in project sduoj-server by SDUOJ.

the class ContestService method queryRank.

/**
 * @Description 查询榜单数据,并做越权、脱敏、榜单冻结
 */
@Cacheable(value = ContestCacheTypeManager.RANK, key = "#contestId+'-'+#userSessionDTO.userId")
public List<ContestRankDTO> queryRank(long contestId, UserSessionDTO userSessionDTO) throws InternalApiException {
    // 查比赛
    ContestDO contestDO = queryContestAndValidate(contestId, userSessionDTO.getUserId());
    // 提出 contestFeature
    ContestFeatureDTO contestFeatureDTO = ContestConvertUtils.featuresTo(contestDO.getFeatures());
    ContestFeatureDTO.InfoOpenness infoOpenness = contestDO.getGmtEnd().after(new Date()) ? contestFeatureDTO.getContestRunning() : contestFeatureDTO.getContestEnd();
    ContestModeEnum contestMode = ContestModeEnum.of(contestFeatureDTO.getMode());
    // 查询 raw 的榜单数据
    List<ContestRankDTO> contestRankDTOList = queryRawRankData(contestDO);
    // 置挂星参赛者
    Set<Long> unofficialParticipantIds = new HashSet<>(ContestConvertUtils.participantsToUserIdList(contestDO.getUnofficialParticipants()));
    contestRankDTOList.stream().filter(o -> unofficialParticipantIds.contains(o.getUserId())).forEach(o -> o.setOfficial(false));
    // 比赛管理员 直接获取所有榜单,无封榜无脱敏
    if (contestCommonService.isContestManager(contestDO, userSessionDTO)) {
        return contestRankDTOList;
    }
    // 禁止显示榜单,脱敏其他人的提交信息
    if (infoOpenness.getDisplayRank() == 0) {
        contestRankDTOList = contestRankDTOList.stream().filter(o -> userSessionDTO.userIdEquals(o.getUserId())).collect(Collectors.toList());
    }
    // 禁止显示分数
    if (infoOpenness.getDisplayJudgeScore() == 0) {
        contestRankDTOList.stream().map(ContestRankDTO::getSubmissions).forEach(o -> o.forEach(s -> s.setJudgeScore(0)));
    }
    // 榜单冻结
    if (contestFeatureDTO.getFrozenTime() != 0) {
        Date frozenTime = new Date(contestDO.getGmtEnd().getTime() - contestFeatureDTO.getFrozenTime() * 60000);
        contestRankDTOList.forEach(o -> {
            o.frozenRank(frozenTime);
            o.toComputeProblemResults(contestMode);
        });
    }
    // 比赛进行时,需要进行 submissions 转 problemResults,将提交中的蕴涵的信息脱掉
    if (contestDO.getGmtEnd().after(new Date())) {
        contestRankDTOList.forEach(o -> o.toComputeProblemResults(contestMode));
    }
    return contestRankDTOList;
}
Also used : LambdaQueryChainWrapper(com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper) java.util(java.util) ProblemListDTO(cn.edu.sdu.qd.oj.problem.dto.ProblemListDTO) Cacheable(org.springframework.cache.annotation.Cacheable) Autowired(org.springframework.beans.factory.annotation.Autowired) PermissionEnum(cn.edu.sdu.qd.oj.auth.enums.PermissionEnum) ContestDO(cn.edu.sdu.qd.oj.contest.entity.ContestDO) CacheEvict(org.springframework.cache.annotation.CacheEvict) ApiExceptionEnum(cn.edu.sdu.qd.oj.common.enums.ApiExceptionEnum) PageResult(cn.edu.sdu.qd.oj.common.entity.PageResult) ContestModeEnum(cn.edu.sdu.qd.oj.contest.enums.ContestModeEnum) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) SubmissionClient(cn.edu.sdu.qd.oj.contest.client.SubmissionClient) RedisUtils(cn.edu.sdu.qd.oj.common.util.RedisUtils) SubmissionJudgeResult(cn.edu.sdu.qd.oj.submit.enums.SubmissionJudgeResult) ContestOpennessEnum(cn.edu.sdu.qd.oj.contest.enums.ContestOpennessEnum) ContestCacheTypeManager(cn.edu.sdu.qd.oj.contest.cache.ContestCacheTypeManager) ContestConvertUtils(cn.edu.sdu.qd.oj.contest.converter.ContestConvertUtils) Service(org.springframework.stereotype.Service) ProblemClient(cn.edu.sdu.qd.oj.contest.client.ProblemClient) InternalApiException(cn.edu.sdu.qd.oj.common.exception.InternalApiException) RedisConstants(cn.edu.sdu.qd.oj.common.util.RedisConstants) AssertUtils(cn.edu.sdu.qd.oj.common.util.AssertUtils) cn.edu.sdu.qd.oj.contest.dto(cn.edu.sdu.qd.oj.contest.dto) ProblemDTO(cn.edu.sdu.qd.oj.problem.dto.ProblemDTO) ProblemDescriptionDTO(cn.edu.sdu.qd.oj.problem.dto.ProblemDescriptionDTO) cn.edu.sdu.qd.oj.submit.dto(cn.edu.sdu.qd.oj.submit.dto) ContestDao(cn.edu.sdu.qd.oj.contest.dao.ContestDao) NotNull(javax.validation.constraints.NotNull) ContestListDao(cn.edu.sdu.qd.oj.contest.dao.ContestListDao) Collectors(java.util.stream.Collectors) UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) SubmissionListReqDTO(cn.edu.sdu.qd.oj.submit.dto.SubmissionListReqDTO) Slf4j(lombok.extern.slf4j.Slf4j) ApiException(cn.edu.sdu.qd.oj.common.exception.ApiException) ContestListDO(cn.edu.sdu.qd.oj.contest.entity.ContestListDO) UserClient(cn.edu.sdu.qd.oj.contest.client.UserClient) Lists(org.assertj.core.util.Lists) SubmissionDTO(cn.edu.sdu.qd.oj.submit.dto.SubmissionDTO) SubmissionListDTO(cn.edu.sdu.qd.oj.submit.dto.SubmissionListDTO) SubmissionCreateReqDTO(cn.edu.sdu.qd.oj.submit.dto.SubmissionCreateReqDTO) ContestListConverter(cn.edu.sdu.qd.oj.contest.converter.ContestListConverter) ContestConverter(cn.edu.sdu.qd.oj.contest.converter.ContestConverter) BeanUtils(org.springframework.beans.BeanUtils) Transactional(org.springframework.transaction.annotation.Transactional) ContestModeEnum(cn.edu.sdu.qd.oj.contest.enums.ContestModeEnum) ContestDO(cn.edu.sdu.qd.oj.contest.entity.ContestDO) Cacheable(org.springframework.cache.annotation.Cacheable)

Example 3 with UserSessionDTO

use of cn.edu.sdu.qd.oj.common.entity.UserSessionDTO in project sduoj-server by SDUOJ.

the class LoginFilter method filter.

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String requestUrl = request.getPath().toString();
    String realIp = FilterUtils.getRealIp(request);
    log.info("Filter From: {}\tUrl: {}\tParams: {}", realIp, requestUrl, request.getQueryParams());
    // 取 token 并解密
    UserSessionDTO userSessionDTO = Optional.of(exchange).map(ServerWebExchange::getSession).map(Mono::block).map(WebSession::getAttributes).map(map -> map.get(UserSessionDTO.HEADER_KEY)).map(o -> (String) o).map(o -> JSON.parseObject(o, UserSessionDTO.class)).orElse(null);
    // 无 session,非 allowUrl
    boolean isAllowPath = isAllowPath(requestUrl);
    if (userSessionDTO == null && !isAllowPath) {
        return FilterUtils.returnWithStatus(exchange, HttpStatus.UNAUTHORIZED, " 你的账号没有该权限或未登录! ");
    }
    // 鉴权
    if (userSessionDTO != null) {
        List<String> urlRoles = NonExceptionOptional.ofNullable(() -> permissionClient.urlToRoles(requestUrl.replace("/api", ""))).orElse(Lists.newArrayList());
        List<String> roles = NonExceptionOptional.ofNullable(() -> userClient.queryRolesById(userSessionDTO.getUserId())).orElse(Lists.newArrayList());
        if (!urlRoles.contains(PermissionEnum.ALL.name) && Collections.disjoint(roles, urlRoles) && !isAllowPath) {
            log.warn("have not permission {} {}", userSessionDTO, requestUrl);
            return FilterUtils.returnWithStatus(exchange, HttpStatus.UNAUTHORIZED, String.format("This User has no permission on '%s'", requestUrl));
        }
        // 装饰器 修改 getHeaders 方法
        ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {

            @Override
            public HttpHeaders getHeaders() {
                MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap(8, Locale.ENGLISH));
                super.getHeaders().forEach((key, value) -> multiValueMap.put(key, value));
                // multiValueMap.remove("cookie"); // 在此处已解码 token, 故不下传省流量, 如果后续有多值 cookie 此处需要修改
                multiValueMap.remove(UserSessionDTO.HEADER_KEY);
                multiValueMap.add(UserSessionDTO.HEADER_KEY, JSON.toJSONString(userSessionDTO));
                multiValueMap.remove(UserSessionDTO.HEADER_KEY_USERID);
                multiValueMap.add(UserSessionDTO.HEADER_KEY_USERID, userSessionDTO.getUserId().toString());
                // }
                return new HttpHeaders(multiValueMap);
            }
        };
        return chain.filter(exchange.mutate().request(decorator).build()).then(thenHandleSession(exchange));
    }
    return chain.filter(exchange).then(thenHandleSession(exchange));
}
Also used : GlobalFilter(org.springframework.cloud.gateway.filter.GlobalFilter) Ordered(org.springframework.core.Ordered) GatewayFilterChain(org.springframework.cloud.gateway.filter.GatewayFilterChain) LinkedCaseInsensitiveMap(org.springframework.util.LinkedCaseInsensitiveMap) Autowired(org.springframework.beans.factory.annotation.Autowired) PermissionEnum(cn.edu.sdu.qd.oj.auth.enums.PermissionEnum) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Lists(com.google.common.collect.Lists) NonExceptionOptional(cn.edu.sdu.qd.oj.common.util.NonExceptionOptional) UserClient(cn.edu.sdu.qd.oj.gateway.client.UserClient) Locale(java.util.Locale) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) PermissionClient(cn.edu.sdu.qd.oj.gateway.client.PermissionClient) WebSession(org.springframework.web.server.WebSession) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) MultiValueMap(org.springframework.util.MultiValueMap) FilterProperties(cn.edu.sdu.qd.oj.gateway.config.FilterProperties) Mono(reactor.core.publisher.Mono) UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) List(java.util.List) JSON(com.alibaba.fastjson.JSON) CollectionUtils(org.springframework.util.CollectionUtils) FilterUtils(cn.edu.sdu.qd.oj.gateway.util.FilterUtils) SessionIdStrategyForceModifyUtils(cn.edu.sdu.qd.oj.gateway.util.SessionIdStrategyForceModifyUtils) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator) Optional(java.util.Optional) Collections(java.util.Collections) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HttpHeaders(org.springframework.http.HttpHeaders) LinkedCaseInsensitiveMap(org.springframework.util.LinkedCaseInsensitiveMap) WebSession(org.springframework.web.server.WebSession) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator)

Example 4 with UserSessionDTO

use of cn.edu.sdu.qd.oj.common.entity.UserSessionDTO in project sduoj-server by SDUOJ.

the class UserController method thirdPartyBinding.

@PostMapping("/thirdPartyBinding")
@ResponseBody
public ResponseResult<UserSessionDTO> thirdPartyBinding(@RequestBody UserThirdPartyBindingReqDTO reqDTO, HttpServletResponse response, @RealIp String ipv4, @RequestHeader("user-agent") String userAgent) {
    UserSessionDTO userSessionDTO = userService.thirdPartyBinding(reqDTO, ipv4, userAgent);
    writeSessionToHeader(response, userSessionDTO);
    return ResponseResult.ok(userSessionDTO);
}
Also used : UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) ApiResponseBody(cn.edu.sdu.qd.oj.common.entity.ApiResponseBody)

Example 5 with UserSessionDTO

use of cn.edu.sdu.qd.oj.common.entity.UserSessionDTO in project sduoj-server by SDUOJ.

the class UserController method thirdPartyRegister.

@PostMapping("/thirdPartyRegister")
@ResponseBody
public ResponseResult<UserSessionDTO> thirdPartyRegister(@RequestBody UserThirdPartyRegisterReqDTO reqDTO, HttpServletResponse response, @RealIp String ipv4, @RequestHeader("user-agent") String userAgent) {
    UserSessionDTO userSessionDTO = userService.thirdPartyRegister(reqDTO, ipv4, userAgent);
    writeSessionToHeader(response, userSessionDTO);
    return ResponseResult.ok(userSessionDTO);
}
Also used : UserSessionDTO(cn.edu.sdu.qd.oj.common.entity.UserSessionDTO) ApiResponseBody(cn.edu.sdu.qd.oj.common.entity.ApiResponseBody)

Aggregations

UserSessionDTO (cn.edu.sdu.qd.oj.common.entity.UserSessionDTO)9 PermissionEnum (cn.edu.sdu.qd.oj.auth.enums.PermissionEnum)4 ApiResponseBody (cn.edu.sdu.qd.oj.common.entity.ApiResponseBody)4 Slf4j (lombok.extern.slf4j.Slf4j)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 PageResult (cn.edu.sdu.qd.oj.common.entity.PageResult)3 ApiExceptionEnum (cn.edu.sdu.qd.oj.common.enums.ApiExceptionEnum)3 ApiException (cn.edu.sdu.qd.oj.common.exception.ApiException)3 InternalApiException (cn.edu.sdu.qd.oj.common.exception.InternalApiException)2 AssertUtils (cn.edu.sdu.qd.oj.common.util.AssertUtils)2 RedisConstants (cn.edu.sdu.qd.oj.common.util.RedisConstants)2 RedisUtils (cn.edu.sdu.qd.oj.common.util.RedisUtils)2 ContestCacheTypeManager (cn.edu.sdu.qd.oj.contest.cache.ContestCacheTypeManager)2 ProblemClient (cn.edu.sdu.qd.oj.contest.client.ProblemClient)2 SubmissionClient (cn.edu.sdu.qd.oj.contest.client.SubmissionClient)2 UserClient (cn.edu.sdu.qd.oj.contest.client.UserClient)2 ContestConvertUtils (cn.edu.sdu.qd.oj.contest.converter.ContestConvertUtils)2 ContestConverter (cn.edu.sdu.qd.oj.contest.converter.ContestConverter)2 ContestListConverter (cn.edu.sdu.qd.oj.contest.converter.ContestListConverter)2 ContestDao (cn.edu.sdu.qd.oj.contest.dao.ContestDao)2