Search in sources :

Example 16 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo-plugin-experimental by guqing.

the class InstallController method installBlog.

@PostMapping
@ResponseBody
@CacheLock
@ApiOperation("Initializes the blog")
public BaseResponse<String> installBlog(@RequestBody InstallParam installParam) {
    // Validate manually
    ValidationUtils.validate(installParam, CreateCheck.class);
    // Check is installed
    boolean isInstalled = optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false);
    if (isInstalled) {
        throw new BadRequestException("该博客已初始化,不能再次安装!");
    }
    // Initialize settings
    initSettings(installParam);
    // Create default user
    User user = createUser(installParam);
    // Create default category
    Category category = createDefaultCategoryIfAbsent();
    // Create default post
    PostDetailVO post = createDefaultPostIfAbsent(category);
    // Create default sheet
    createDefaultSheet();
    // Create default postComment
    createDefaultComment(post);
    // Create default menu
    createDefaultMenu();
    eventPublisher.publishEvent(new LogEvent(this, user.getId().toString(), LogType.BLOG_INITIALIZED, "博客已成功初始化"));
    return BaseResponse.ok("安装完成!");
}
Also used : User(run.halo.app.model.entity.User) Category(run.halo.app.model.entity.Category) LogEvent(run.halo.app.event.logger.LogEvent) PostDetailVO(run.halo.app.model.vo.PostDetailVO) BadRequestException(run.halo.app.exception.BadRequestException) CacheLock(run.halo.app.cache.lock.CacheLock) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiOperation(io.swagger.annotations.ApiOperation) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 17 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo-plugin-experimental by guqing.

the class AdminServiceImpl method authenticate.

@Override
@NonNull
public User authenticate(@NonNull LoginParam loginParam) {
    Assert.notNull(loginParam, "Login param must not be null");
    String username = loginParam.getUsername();
    String mismatchTip = "用户名或者密码不正确";
    final User user;
    try {
        // Get user by username or email
        user = ValidationUtils.isEmail(username) ? userService.getByEmailOfNonNull(username) : userService.getByUsernameOfNonNull(username);
    } catch (NotFoundException e) {
        log.error("Failed to find user by name: " + username);
        eventPublisher.publishEvent(new LogEvent(this, loginParam.getUsername(), LogType.LOGIN_FAILED, loginParam.getUsername()));
        throw new BadRequestException(mismatchTip);
    }
    userService.mustNotExpire(user);
    if (!userService.passwordMatch(user, loginParam.getPassword())) {
        // If the password is mismatch
        eventPublisher.publishEvent(new LogEvent(this, loginParam.getUsername(), LogType.LOGIN_FAILED, loginParam.getUsername()));
        throw new BadRequestException(mismatchTip);
    }
    return user;
}
Also used : User(run.halo.app.model.entity.User) LogEvent(run.halo.app.event.logger.LogEvent) NotFoundException(run.halo.app.exception.NotFoundException) BadRequestException(run.halo.app.exception.BadRequestException) NonNull(org.springframework.lang.NonNull)

Example 18 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo-plugin-experimental by guqing.

the class AdminServiceImpl method refreshToken.

@Override
@NonNull
public AuthToken refreshToken(@NonNull String refreshToken) {
    Assert.hasText(refreshToken, "Refresh token must not be blank");
    Integer userId = cacheStore.getAny(SecurityUtils.buildTokenRefreshKey(refreshToken), Integer.class).orElseThrow(() -> new BadRequestException("登录状态已失效,请重新登录").setErrorData(refreshToken));
    // Get user info
    User user = userService.getById(userId);
    // Remove all token
    cacheStore.getAny(SecurityUtils.buildAccessTokenKey(user), String.class).ifPresent(accessToken -> cacheStore.delete(SecurityUtils.buildTokenAccessKey(accessToken)));
    cacheStore.delete(SecurityUtils.buildTokenRefreshKey(refreshToken));
    cacheStore.delete(SecurityUtils.buildAccessTokenKey(user));
    cacheStore.delete(SecurityUtils.buildRefreshTokenKey(user));
    return buildAuthToken(user);
}
Also used : User(run.halo.app.model.entity.User) BadRequestException(run.halo.app.exception.BadRequestException) NonNull(org.springframework.lang.NonNull)

Example 19 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo-plugin-experimental by guqing.

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)

Example 20 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo-plugin-experimental by guqing.

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)

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