Search in sources :

Example 11 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by halo-dev.

the class BaseCommentServiceImpl method createBy.

@Override
@NonNull
@Transactional(rollbackFor = Exception.class)
public COMMENT createBy(@NonNull BaseCommentParam<COMMENT> commentParam) {
    Assert.notNull(commentParam, "Comment param must not be null");
    // Check user login status and set this field
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        // Blogger comment
        User user = authentication.getDetail().getUser();
        commentParam.setAuthor(StringUtils.isBlank(user.getNickname()) ? user.getUsername() : user.getNickname());
        commentParam.setEmail(user.getEmail());
        commentParam.setAuthorUrl(optionService.getByPropertyOrDefault(BlogProperties.BLOG_URL, String.class, null));
    }
    // Validate the comment param manually
    ValidationUtils.validate(commentParam);
    if (authentication == null) {
        // Check email
        if (userService.getByEmail(commentParam.getEmail()).isPresent()) {
            throw new BadRequestException("不能使用博主的邮箱,如果您是博主,请登录管理端进行回复。");
        }
    }
    // Convert to comment
    return create(commentParam.convertTo());
}
Also used : User(run.halo.app.model.entity.User) Authentication(run.halo.app.security.authentication.Authentication) BadRequestException(run.halo.app.exception.BadRequestException) NonNull(org.springframework.lang.NonNull) Transactional(org.springframework.transaction.annotation.Transactional)

Example 12 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by halo-dev.

the class MultipartFileThemeUpdater method update.

@Override
public ThemeProperty update(String themeId) throws IOException {
    // check old theme id
    final var oldThemeProperty = this.themeRepository.fetchThemePropertyByThemeId(themeId).orElseThrow(() -> new NotFoundException("主题 ID 为 " + themeId + " 不存在或已删除!"));
    // fetch new theme
    final var newThemeProperty = this.fetcherComposite.fetch(this.file);
    if (!Objects.equals(oldThemeProperty.getId(), newThemeProperty.getId())) {
        log.error("Expected theme: {}, but provided theme: {}", oldThemeProperty.getId(), newThemeProperty.getId());
        // clear new theme folder
        this.themeRepository.deleteTheme(newThemeProperty);
        throw new BadRequestException("上传的主题 " + newThemeProperty.getId() + " 和当前主题的 " + oldThemeProperty.getId() + " 不一致,无法进行更新操作!");
    }
    // backup old theme
    final var backupPath = ThemeUpdater.backup(oldThemeProperty);
    try {
        // delete  old theme
        themeRepository.deleteTheme(oldThemeProperty);
        // add new theme
        return themeRepository.attemptToAdd(newThemeProperty);
    } catch (Throwable t) {
        log.error("Failed to add new theme, and restoring old theme from " + backupPath, t);
        ThemeUpdater.restore(backupPath, oldThemeProperty);
        log.info("Restored old theme from path: {}", backupPath);
        throw t;
    }
}
Also used : NotFoundException(run.halo.app.exception.NotFoundException) BadRequestException(run.halo.app.exception.BadRequestException)

Example 13 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by halo-dev.

the class ThemeServiceImpl method deleteTheme.

@Transactional
@Override
public void deleteTheme(@NonNull String themeId, @NonNull Boolean deleteSettings) {
    // Get the theme property
    ThemeProperty themeProperty = getThemeOfNonNullBy(themeId);
    if (themeId.equals(getActivatedThemeId())) {
        // Prevent to delete the activated theme
        throw new BadRequestException("无法删除正在使用的主题!").setErrorData(themeId);
    }
    try {
        // Delete the folder
        FileUtils.deleteFolder(Paths.get(themeProperty.getThemePath()));
        if (deleteSettings) {
            // Delete theme settings
            themeSettingRepository.deleteByThemeId(themeId);
        }
        // Delete theme cache
        eventPublisher.publishEvent(new ThemeUpdatedEvent(this));
    } catch (Exception e) {
        throw new ServiceException("主题删除失败", e).setErrorData(themeId);
    }
}
Also used : ServiceException(run.halo.app.exception.ServiceException) ThemeUpdatedEvent(run.halo.app.event.theme.ThemeUpdatedEvent) BadRequestException(run.halo.app.exception.BadRequestException) NotFoundException(run.halo.app.exception.NotFoundException) ServiceException(run.halo.app.exception.ServiceException) ThemeNotFoundException(run.halo.app.exception.ThemeNotFoundException) ThemePropertyMissingException(run.halo.app.exception.ThemePropertyMissingException) ThemeNotSupportException(run.halo.app.exception.ThemeNotSupportException) ThemeUpdateException(run.halo.app.exception.ThemeUpdateException) IOException(java.io.IOException) ForbiddenException(run.halo.app.exception.ForbiddenException) BadRequestException(run.halo.app.exception.BadRequestException) ThemeProperty(run.halo.app.handler.theme.config.support.ThemeProperty) Transactional(org.springframework.transaction.annotation.Transactional)

Example 14 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by halo-dev.

the class AdminServiceImpl method authCodeCheck.

@Override
@NonNull
public AuthToken authCodeCheck(@NonNull final LoginParam loginParam) {
    // get user
    final User user = this.authenticate(loginParam);
    // check authCode
    if (MFAType.useMFA(user.getMfaType())) {
        if (StringUtils.isBlank(loginParam.getAuthcode())) {
            throw new BadRequestException("请输入两步验证码");
        }
        TwoFactorAuthUtils.validateTFACode(user.getMfaKey(), loginParam.getAuthcode());
    }
    if (SecurityContextHolder.getContext().isAuthenticated()) {
        // If the user has been logged in
        throw new BadRequestException("您已登录,请不要重复登录");
    }
    // Log it then login successful
    eventPublisher.publishEvent(new LogEvent(this, user.getUsername(), LogType.LOGGED_IN, user.getNickname()));
    // Generate new token
    return buildAuthToken(user);
}
Also used : User(run.halo.app.model.entity.User) LogEvent(run.halo.app.event.logger.LogEvent) BadRequestException(run.halo.app.exception.BadRequestException) NonNull(org.springframework.lang.NonNull)

Example 15 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by halo-dev.

the class AbstractAuthenticationFilter method isSufficientOneTimeToken.

/**
 * Check if the sufficient one-time token is set.
 *
 * @param request http servlet request
 * @return true if sufficient; false otherwise
 */
private boolean isSufficientOneTimeToken(HttpServletRequest request) {
    // Check the param
    final String oneTimeToken = getTokenFromRequest(request, ONE_TIME_TOKEN_QUERY_NAME, ONE_TIME_TOKEN_HEADER_NAME);
    if (StringUtils.isBlank(oneTimeToken)) {
        // If no one-time token is not provided, skip
        return false;
    }
    // Get allowed uri
    String allowedUri = oneTimeTokenService.get(oneTimeToken).orElseThrow(() -> new BadRequestException("The one-time token does not exist or has been expired").setErrorData(oneTimeToken));
    // Get request uri
    String requestUri = request.getRequestURI();
    if (!StringUtils.equals(requestUri, allowedUri)) {
        // TODO using ant path matcher could be better
        throw new ForbiddenException("The one-time token does not correspond the request uri").setErrorData(oneTimeToken);
    }
    // Revoke the token before return
    oneTimeTokenService.revoke(oneTimeToken);
    return true;
}
Also used : ForbiddenException(run.halo.app.exception.ForbiddenException) BadRequestException(run.halo.app.exception.BadRequestException)

Aggregations

BadRequestException (run.halo.app.exception.BadRequestException)41 User (run.halo.app.model.entity.User)26 LogEvent (run.halo.app.event.logger.LogEvent)15 NonNull (org.springframework.lang.NonNull)12 NotFoundException (run.halo.app.exception.NotFoundException)9 IOException (java.io.IOException)6 CacheLock (run.halo.app.cache.lock.CacheLock)6 ForbiddenException (run.halo.app.exception.ForbiddenException)6 ServiceException (run.halo.app.exception.ServiceException)6 Authentication (run.halo.app.security.authentication.Authentication)6 ThemeUpdatedEvent (run.halo.app.event.theme.ThemeUpdatedEvent)5 Category (run.halo.app.model.entity.Category)5 Transactional (org.springframework.transaction.annotation.Transactional)4 ApiOperation (io.swagger.annotations.ApiOperation)3 Path (java.nio.file.Path)3 GeneralSecurityException (java.security.GeneralSecurityException)3 PostMapping (org.springframework.web.bind.annotation.PostMapping)3 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)3 UserUpdatedEvent (run.halo.app.event.user.UserUpdatedEvent)3 ThemeNotFoundException (run.halo.app.exception.ThemeNotFoundException)3