org.apache.kylin.rest.exception.ForbiddenException Java Examples

The following examples show how to use org.apache.kylin.rest.exception.ForbiddenException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserController.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.POST }, produces = { "application/json" })
@ResponseBody
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN)
//do not use aclEvaluate, if getManagedUsersByFuzzMatching there's no users and will come into init() and will call save.
public ManagedUser create(@PathVariable("userName") String userName, @RequestBody ManagedUser user) {
    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), user.getUsername()) && user.isDisabled()) {
        throw new ForbiddenException("Action not allowed!");
    }

    checkUserName(userName);

    user.setUsername(userName);
    user.setPassword(pwdEncode(user.getPassword()));

    logger.info("Creating {}", user);

    completeAuthorities(user);
    userService.createUser(user);
    return get(userName);
}
 
Example #2
Source File: BaseControllerTest.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws IOException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost");

    NotFoundException notFoundException = new NotFoundException("not found");
    ErrorResponse errorResponse = basicController.handleBadRequest(request, notFoundException);
    Assert.assertNotNull(errorResponse);

    ForbiddenException forbiddenException = new ForbiddenException("forbidden");
    errorResponse = basicController.handleForbidden(request, forbiddenException);
    Assert.assertNotNull(errorResponse);

    InternalErrorException internalErrorException = new InternalErrorException("error");
    errorResponse = basicController.handleError(request, internalErrorException);
    Assert.assertNotNull(errorResponse);

    BadRequestException badRequestException = new BadRequestException("error");
    errorResponse = basicController.handleBadRequest(request, badRequestException);
    Assert.assertNotNull(errorResponse);
}
 
Example #3
Source File: CubeService.java    From kylin with Apache License 2.0 6 votes vote down vote up
public CubeDesc updateCube(CubeInstance cube, CubeDesc desc, ProjectInstance project) throws IOException {
    aclEvaluate.checkProjectWritePermission(cube);
    Message msg = MsgPicker.getMsg();
    String projectName = project.getName();

    desc.setDraft(false);

    try {
        if (cube.getSegments().size() != 0 && !cube.getDescriptor().consistentWith(desc)) {
            throw new BadRequestException(
                    String.format(Locale.ROOT, msg.getINCONSISTENT_CUBE_DESC(), desc.getName()));
        }

        desc = updateCubeAndDesc(cube, desc, projectName, true);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException(msg.getUPDATE_CUBE_NO_RIGHT());
    }

    if (desc.isBroken()) {
        throw new BadRequestException(desc.getErrorsAsString());
    }

    return desc;
}
 
Example #4
Source File: CubeService.java    From kylin with Apache License 2.0 6 votes vote down vote up
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN
        + " or hasPermission(#project, 'ADMINISTRATION') or hasPermission(#project, 'MANAGEMENT')")
public CubeDesc saveCube(CubeDesc desc, ProjectInstance project) throws IOException {
    Message msg = MsgPicker.getMsg();

    desc.setDraft(false);
    if (desc.getUuid() == null)
        desc.updateRandomUuid();

    try {
        createCubeAndDesc(project, desc);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException(msg.getUPDATE_CUBE_NO_RIGHT());
    }

    if (desc.isBroken()) {
        throw new BadRequestException(desc.getErrorsAsString());
    }

    return desc;
}
 
Example #5
Source File: StreamingV2Controller.java    From kylin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/updateConfig", method = { RequestMethod.PUT })
@ResponseBody
public StreamingRequest updateStreamingConfig(@RequestBody StreamingRequest streamingRequest)
        throws JsonProcessingException {
    StreamingSourceConfig streamingSourceConfig = deserializeStreamingConfig(streamingRequest.getStreamingConfig());

    if (streamingSourceConfig == null) {
        return streamingRequest;
    }

    final String user = SecurityContextHolder.getContext().getAuthentication().getName();
    logger.info("{} try to updateStreamingConfig.", user);
    try {
        streamingSourceConfig = streamingService.updateStreamingConfig(streamingSourceConfig);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException("You don't have right to update this StreamingSourceConfig.");
    } catch (Exception e) {
        logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
        throw new InternalErrorException("Failed to deal with the request: " + e.getLocalizedMessage());
    }
    streamingRequest.setSuccessful(true);

    return streamingRequest;
}
 
Example #6
Source File: ModelController.java    From kylin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
public ModelRequest updateModelDesc(@RequestBody ModelRequest modelRequest) throws JsonProcessingException {
    DataModelDesc modelDesc = deserializeDataModelDesc(modelRequest);
    if (modelDesc == null) {
        return modelRequest;
    }
    try {
        modelDesc = modelService.updateModelAndDesc(modelRequest.getProject(), modelDesc);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException("You don't have right to update this model.");
    } catch (Exception e) {
        logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
        throw new InternalErrorException("Failed to deal with the request: " + e.getLocalizedMessage(), e);
    }

    if (modelDesc.getError().isEmpty()) {
        modelRequest.setSuccessful(true);
    } else {
        logger.warn("Model " + modelDesc.getName() + " fail to update because " + modelDesc.getError());
        updateRequest(modelRequest, false, omitMessage(modelDesc.getError()));
    }
    String descData = JsonUtil.writeValueAsIndentString(modelDesc);
    modelRequest.setModelDescData(descData);
    return modelRequest;
}
 
Example #7
Source File: UserController.java    From kylin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.DELETE }, produces = { "application/json" })
@ResponseBody
public EnvelopeResponse delete(@PathVariable("userName") String userName) throws IOException {

    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), userName)) {
        throw new ForbiddenException("...");
    }

    //delete user's project ACL
    accessService.revokeProjectPermission(userName, MetadataConstants.TYPE_USER);

    //delete user's table/row/column ACL
    //        ACLOperationUtil.delLowLevelACL(userName, MetadataConstants.TYPE_USER);

    checkUserName(userName);
    userService.deleteUser(userName);
    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, userName, "");
}
 
Example #8
Source File: UserController.java    From kylin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.POST }, produces = { "application/json" })
@ResponseBody
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN)
//do not use aclEvaluate, if getManagedUsersByFuzzMatching there's no users and will come into init() and will call save.
public ManagedUser create(@PathVariable("userName") String userName, @RequestBody ManagedUser user) {
    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), user.getUsername()) && user.isDisabled()) {
        throw new ForbiddenException("Action not allowed!");
    }

    checkUserName(userName);

    user.setUsername(userName);
    user.setPassword(pwdEncode(user.getPassword()));

    logger.info("Creating {}", user);

    completeAuthorities(user);
    userService.createUser(user);
    return get(userName);
}
 
Example #9
Source File: BaseControllerTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws IOException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost");

    NotFoundException notFoundException = new NotFoundException("not found");
    ErrorResponse errorResponse = basicController.handleBadRequest(request, notFoundException);
    Assert.assertNotNull(errorResponse);

    ForbiddenException forbiddenException = new ForbiddenException("forbidden");
    errorResponse = basicController.handleForbidden(request, forbiddenException);
    Assert.assertNotNull(errorResponse);

    InternalErrorException internalErrorException = new InternalErrorException("error");
    errorResponse = basicController.handleError(request, internalErrorException);
    Assert.assertNotNull(errorResponse);

    BadRequestException badRequestException = new BadRequestException("error");
    errorResponse = basicController.handleBadRequest(request, badRequestException);
    Assert.assertNotNull(errorResponse);
}
 
Example #10
Source File: CubeService.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
public CubeDesc updateCube(CubeInstance cube, CubeDesc desc, ProjectInstance project) throws IOException {
    aclEvaluate.checkProjectWritePermission(cube);
    Message msg = MsgPicker.getMsg();
    String projectName = project.getName();

    desc.setDraft(false);

    try {
        if (cube.getSegments().size() != 0 && !cube.getDescriptor().consistentWith(desc)) {
            throw new BadRequestException(
                    String.format(Locale.ROOT, msg.getINCONSISTENT_CUBE_DESC(), desc.getName()));
        }

        desc = updateCubeAndDesc(cube, desc, projectName, true);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException(msg.getUPDATE_CUBE_NO_RIGHT());
    }

    if (desc.isBroken()) {
        throw new BadRequestException(desc.getErrorsAsString());
    }

    return desc;
}
 
Example #11
Source File: BaseControllerTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws IOException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost");

    NotFoundException notFoundException = new NotFoundException("not found");
    ErrorResponse errorResponse = basicController.handleBadRequest(request, notFoundException);
    Assert.assertNotNull(errorResponse);

    ForbiddenException forbiddenException = new ForbiddenException("forbidden");
    errorResponse = basicController.handleForbidden(request, forbiddenException);
    Assert.assertNotNull(errorResponse);

    InternalErrorException internalErrorException = new InternalErrorException("error");
    errorResponse = basicController.handleError(request, internalErrorException);
    Assert.assertNotNull(errorResponse);

    BadRequestException badRequestException = new BadRequestException("error");
    errorResponse = basicController.handleBadRequest(request, badRequestException);
    Assert.assertNotNull(errorResponse);
}
 
Example #12
Source File: StreamingV2Controller.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/updateConfig", method = { RequestMethod.PUT })
@ResponseBody
public StreamingRequest updateStreamingConfig(@RequestBody StreamingRequest streamingRequest)
        throws JsonProcessingException {
    StreamingSourceConfig streamingSourceConfig = deserializeStreamingConfig(streamingRequest.getStreamingConfig());

    if (streamingSourceConfig == null) {
        return streamingRequest;
    }

    final String user = SecurityContextHolder.getContext().getAuthentication().getName();
    logger.info("{} try to updateStreamingConfig.", user);
    try {
        streamingSourceConfig = streamingService.updateStreamingConfig(streamingSourceConfig);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException("You don't have right to update this StreamingSourceConfig.");
    } catch (Exception e) {
        logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
        throw new InternalErrorException("Failed to deal with the request: " + e.getLocalizedMessage());
    }
    streamingRequest.setSuccessful(true);

    return streamingRequest;
}
 
Example #13
Source File: ModelController.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
public ModelRequest updateModelDesc(@RequestBody ModelRequest modelRequest) throws JsonProcessingException {
    DataModelDesc modelDesc = deserializeDataModelDesc(modelRequest);
    if (modelDesc == null) {
        return modelRequest;
    }
    try {
        modelDesc = modelService.updateModelAndDesc(modelRequest.getProject(), modelDesc);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException("You don't have right to update this model.");
    } catch (Exception e) {
        logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
        throw new InternalErrorException("Failed to deal with the request: " + e.getLocalizedMessage(), e);
    }

    if (modelDesc.getError().isEmpty()) {
        modelRequest.setSuccessful(true);
    } else {
        logger.warn("Model " + modelDesc.getName() + " fail to update because " + modelDesc.getError());
        updateRequest(modelRequest, false, omitMessage(modelDesc.getError()));
    }
    String descData = JsonUtil.writeValueAsIndentString(modelDesc);
    modelRequest.setModelDescData(descData);
    return modelRequest;
}
 
Example #14
Source File: UserController.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.DELETE }, produces = { "application/json" })
@ResponseBody
public EnvelopeResponse delete(@PathVariable("userName") String userName) throws IOException {

    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), userName)) {
        throw new ForbiddenException("...");
    }

    //delete user's project ACL
    accessService.revokeProjectPermission(userName, MetadataConstants.TYPE_USER);

    //delete user's table/row/column ACL
    //        ACLOperationUtil.delLowLevelACL(userName, MetadataConstants.TYPE_USER);

    checkUserName(userName);
    userService.deleteUser(userName);
    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, userName, "");
}
 
Example #15
Source File: CubeService.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN
        + " or hasPermission(#project, 'ADMINISTRATION') or hasPermission(#project, 'MANAGEMENT')")
public CubeDesc saveCube(CubeDesc desc, ProjectInstance project) throws IOException {
    Message msg = MsgPicker.getMsg();

    desc.setDraft(false);
    if (desc.getUuid() == null)
        desc.updateRandomUuid();

    try {
        createCubeAndDesc(project, desc);
    } catch (AccessDeniedException accessDeniedException) {
        throw new ForbiddenException(msg.getUPDATE_CUBE_NO_RIGHT());
    }

    if (desc.isBroken()) {
        throw new BadRequestException(desc.getErrorsAsString());
    }

    return desc;
}
 
Example #16
Source File: UserController.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.GET }, produces = { "application/json" })
@ResponseBody
public EnvelopeResponse getUser(@PathVariable("userName") String userName) {

    if (!this.isAdmin() && !StringUtils.equals(getPrincipal(), userName)) {
        throw new ForbiddenException("...");
    }
    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, get(userName), "");
}
 
Example #17
Source File: AccessService.java    From Kylin with Apache License 2.0 5 votes vote down vote up
/**
 * Protect admin permission granted to acl owner.
 * 
 * @param acl
 * @param indexOfAce
 */
private void secureOwner(MutableAcl acl, int indexOfAce) {
    // Can't revoke admin permission from domain object owner
    if (acl.getOwner().equals(acl.getEntries().get(indexOfAce).getSid()) && BasePermission.ADMINISTRATION.equals(acl.getEntries().get(indexOfAce).getPermission())) {
        throw new ForbiddenException("Can't revoke admin permission of owner.");
    }
}
 
Example #18
Source File: AccessService.java    From kylin with Apache License 2.0 5 votes vote down vote up
/**
 * Protect admin permission granted to acl owner.
 */
private void secureOwner(MutableAclRecord acl, Sid sid) {
    Message msg = MsgPicker.getMsg();

    AclRecord record = acl.getAclRecord();
    if (record.getOwner().equals(sid) == false)
        return;

    // prevent changing owner's admin permission
    if (BasePermission.ADMINISTRATION.equals(record.getPermission(sid)))
        throw new ForbiddenException(msg.getREVOKE_ADMIN_PERMISSION());
}
 
Example #19
Source File: UserController.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN)
//do not use aclEvaluate, if there's no users and will come into init() and will call save.
public ManagedUser save(@PathVariable("userName") String userName, @RequestBody ManagedUser user) {
    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), user.getUsername()) && user.isDisabled()) {
        throw new ForbiddenException("Action not allowed!");
    }

    checkUserName(userName);

    user.setUsername(userName);

    // merge with existing user
    try {
        ManagedUser existing = get(userName);
        if (existing != null) {
            if (user.getPassword() == null)
                user.setPassword(existing.getPassword());
            if (user.getAuthorities() == null || user.getAuthorities().isEmpty())
                user.setGrantedAuthorities(existing.getAuthorities());
        }
    } catch (UsernameNotFoundException ex) {
        // that is OK, we create new
    }
    logger.info("Saving {}", user);

    completeAuthorities(user);
    userService.updateUser(user);
    return get(userName);
}
 
Example #20
Source File: UserController.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/password", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
//change passwd
public EnvelopeResponse save(@RequestBody PasswdChangeRequest user) {

    checkProfileEditAllowed();

    if (!this.isAdmin() && !StringUtils.equals(getPrincipal(), user.getUsername())) {
        throw new ForbiddenException("Permission Denied");
    }
    ManagedUser existing = get(user.getUsername());
    checkUserName(user.getUsername());
    checkNewPwdRule(user.getNewPassword());

    if (existing != null) {
        if (!this.isAdmin() && !pwdEncoder.matches(user.getPassword(), existing.getPassword())) {
            throw new BadRequestException("pwd update error");
        }

        existing.setPassword(pwdEncode(user.getNewPassword()));
        existing.setDefaultPassword(false);
        logger.info("update password for user {}", user);

        completeAuthorities(existing);
        userService.updateUser(existing);

        // update authentication
        if (StringUtils.equals(getPrincipal(), user.getUsername())) {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(existing,
                    user.getNewPassword(), existing.getAuthorities());
            token.setDetails(SecurityContextHolder.getContext().getAuthentication().getDetails());
            SecurityContextHolder.getContext().setAuthentication(token);
        }
    }

    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, get(user.getUsername()), "");
}
 
Example #21
Source File: ModelService.java    From kylin with Apache License 2.0 5 votes vote down vote up
public DataModelDesc updateModelToResourceStore(DataModelDesc modelDesc, String projectName) throws IOException {

        aclEvaluate.checkProjectWritePermission(projectName);
        Message msg = MsgPicker.getMsg();

        modelDesc.setDraft(false);
        if (modelDesc.getUuid() == null)
            modelDesc.updateRandomUuid();

        try {
            if (modelDesc.getLastModified() == 0) {
                // new
                modelDesc = createModelDesc(projectName, modelDesc);
            } else {
                // update
                String error = checkIfBreakExistingCubes(modelDesc, projectName);
                if (!error.isEmpty()) {
                    throw new BadRequestException(error);
                }
                modelDesc = updateModelAndDesc(projectName, modelDesc);
            }
        } catch (AccessDeniedException accessDeniedException) {
            throw new ForbiddenException(msg.getUPDATE_MODEL_NO_RIGHT());
        }

        if (!modelDesc.getError().isEmpty()) {
            throw new BadRequestException(String.format(Locale.ROOT, msg.getBROKEN_MODEL_DESC(), modelDesc.getName()));
        }

        return modelDesc;
    }
 
Example #22
Source File: UserController.java    From kylin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.GET }, produces = { "application/json" })
@ResponseBody
public EnvelopeResponse getUser(@PathVariable("userName") String userName) {

    if (!this.isAdmin() && !StringUtils.equals(getPrincipal(), userName)) {
        throw new ForbiddenException("...");
    }
    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, get(userName), "");
}
 
Example #23
Source File: UserController.java    From kylin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/password", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
//change passwd
public EnvelopeResponse save(@RequestBody PasswdChangeRequest user) {

    checkProfileEditAllowed();

    if (!this.isAdmin() && !StringUtils.equals(getPrincipal(), user.getUsername())) {
        throw new ForbiddenException("Permission Denied");
    }
    ManagedUser existing = get(user.getUsername());
    checkUserName(user.getUsername());
    checkNewPwdRule(user.getNewPassword());

    if (existing != null) {
        if (!this.isAdmin() && !pwdEncoder.matches(user.getPassword(), existing.getPassword())) {
            throw new BadRequestException("pwd update error");
        }

        existing.setPassword(pwdEncode(user.getNewPassword()));
        existing.setDefaultPassword(false);
        logger.info("update password for user {}", user);

        completeAuthorities(existing);
        userService.updateUser(existing);

        // update authentication
        if (StringUtils.equals(getPrincipal(), user.getUsername())) {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(existing,
                    user.getNewPassword(), existing.getAuthorities());
            token.setDetails(SecurityContextHolder.getContext().getAuthentication().getDetails());
            SecurityContextHolder.getContext().setAuthentication(token);
        }
    }

    return new EnvelopeResponse(ResponseCode.CODE_SUCCESS, get(user.getUsername()), "");
}
 
Example #24
Source File: UserController.java    From kylin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{userName:.+}", method = { RequestMethod.PUT }, produces = { "application/json" })
@ResponseBody
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN)
//do not use aclEvaluate, if there's no users and will come into init() and will call save.
public ManagedUser save(@PathVariable("userName") String userName, @RequestBody ManagedUser user) {
    checkProfileEditAllowed();

    if (StringUtils.equals(getPrincipal(), user.getUsername()) && user.isDisabled()) {
        throw new ForbiddenException("Action not allowed!");
    }

    checkUserName(userName);

    user.setUsername(userName);

    // merge with existing user
    try {
        ManagedUser existing = get(userName);
        if (existing != null) {
            if (user.getPassword() == null)
                user.setPassword(existing.getPassword());
            if (user.getAuthorities() == null || user.getAuthorities().isEmpty())
                user.setGrantedAuthorities(existing.getAuthorities());
        }
    } catch (UsernameNotFoundException ex) {
        // that is OK, we create new
    }
    logger.info("Saving {}", user);

    user.setPassword(pwdEncode(user.getPassword()));

    completeAuthorities(user);
    userService.updateUser(user);
    return get(userName);
}
 
Example #25
Source File: AccessService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Protect admin permission granted to acl owner.
 */
private void secureOwner(MutableAclRecord acl, Sid sid) {
    Message msg = MsgPicker.getMsg();

    AclRecord record = acl.getAclRecord();
    if (record.getOwner().equals(sid) == false)
        return;

    // prevent changing owner's admin permission
    if (BasePermission.ADMINISTRATION.equals(record.getPermission(sid)))
        throw new ForbiddenException(msg.getREVOKE_ADMIN_PERMISSION());
}
 
Example #26
Source File: ModelService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public DataModelDesc updateModelToResourceStore(DataModelDesc modelDesc, String projectName) throws IOException {

        aclEvaluate.checkProjectWritePermission(projectName);
        Message msg = MsgPicker.getMsg();

        modelDesc.setDraft(false);
        if (modelDesc.getUuid() == null)
            modelDesc.updateRandomUuid();

        try {
            if (modelDesc.getLastModified() == 0) {
                // new
                modelDesc = createModelDesc(projectName, modelDesc);
            } else {
                // update
                String error = checkIfBreakExistingCubes(modelDesc, projectName);
                if (!error.isEmpty()) {
                    throw new BadRequestException(error);
                }
                modelDesc = updateModelAndDesc(projectName, modelDesc);
            }
        } catch (AccessDeniedException accessDeniedException) {
            throw new ForbiddenException(msg.getUPDATE_MODEL_NO_RIGHT());
        }

        if (!modelDesc.getError().isEmpty()) {
            throw new BadRequestException(String.format(Locale.ROOT, msg.getBROKEN_MODEL_DESC(), modelDesc.getName()));
        }

        return modelDesc;
    }
 
Example #27
Source File: BasicController.java    From kylin with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
@ResponseBody
ErrorResponse handleForbidden(HttpServletRequest req, Exception ex) {
    return new ErrorResponse(req.getRequestURL().toString(), ex);
}
 
Example #28
Source File: BasicController.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
@ResponseBody
ErrorResponse handleForbidden(HttpServletRequest req, Exception ex) {
    return new ErrorResponse(req.getRequestURL().toString(), ex);
}
 
Example #29
Source File: QueryController.java    From Kylin with Apache License 2.0 4 votes vote down vote up
private SQLResponse doQuery(SQLRequest sqlRequest) {
    String sql = sqlRequest.getSql();
    String project = sqlRequest.getProject();
    logger.info("Using project: " + project);
    logger.info("The original query:  " + sql);

    String serverMode = KylinConfig.getInstanceFromEnv().getServerMode();
    if (!(Constant.SERVER_MODE_QUERY.equals(serverMode.toLowerCase()) || Constant.SERVER_MODE_ALL.equals(serverMode.toLowerCase()))) {
        throw new InternalErrorException("Query is not allowed in " + serverMode + " mode.");
    }

    if (sql.toLowerCase().contains("select") == false) {
        logger.debug("Directly return expection as not supported");
        throw new InternalErrorException(QueryUtil.makeErrorMsgUserFriendly("Not Supported SQL."));
    }

    SQLResponse sqlResponse = searchQueryInCache(sqlRequest);
    try {
        if (null == sqlResponse) {
            sqlResponse = queryService.query(sqlRequest);

            long durationThreshold = KylinConfig.getInstanceFromEnv().getQueryDurationCacheThreshold();
            long scancountThreshold = KylinConfig.getInstanceFromEnv().getQueryScanCountCacheThreshold();
            if (!sqlResponse.getIsException() && (sqlResponse.getDuration() > durationThreshold || sqlResponse.getTotalScanCount() > scancountThreshold)) {
                cacheManager.getCache(SUCCESS_QUERY_CACHE).put(new Element(sqlRequest, sqlResponse));
            }
        }

        checkQueryAuth(sqlResponse);

        return sqlResponse;
    } catch (AccessDeniedException ade) {
        // Access exception is bind with each user, it will not be cached
        logger.error("Exception when execute sql", ade);
        throw new ForbiddenException(ade.getLocalizedMessage());
    } catch (Throwable e) { // calcite may throw AssertError
        SQLResponse exceptionRes = new SQLResponse(null, null, 0, true, e.getMessage());
        Cache exceptionCache = cacheManager.getCache(EXCEPTION_QUERY_CACHE);
        exceptionCache.put(new Element(sqlRequest, exceptionRes));

        logger.error("Exception when execute sql", e);
        throw new InternalErrorException(QueryUtil.makeErrorMsgUserFriendly(e.getLocalizedMessage()));
    }
}
 
Example #30
Source File: BasicController.java    From Kylin with Apache License 2.0 4 votes vote down vote up
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(ForbiddenException.class)
@ResponseBody
ErrorResponse handleForbidden(HttpServletRequest req, Exception ex) {
    return new ErrorResponse(req.getRequestURL().toString(), ex);
}