Search in sources :

Example 36 with BadRequestException

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

the class TwoFactorAuthUtils method validateTFACode.

public static void validateTFACode(String tfaKey, String tfaCode) {
    try {
        int validCode = Integer.parseInt(tfaCode);
        boolean result = TimeBasedOneTimePasswordUtil.validateCurrentNumber(tfaKey, validCode, VALID_TFA_WINDOW_MILLIS);
        if (!result) {
            throw new BadRequestException("两步验证码验证错误,请确认时间是否同步");
        }
    } catch (NumberFormatException e) {
        throw new BadRequestException("两步验证码请输入数字");
    } catch (GeneralSecurityException e) {
        throw new BadRequestException("两步验证码验证异常");
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) BadRequestException(run.halo.app.exception.BadRequestException)

Example 37 with BadRequestException

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

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) ThemeNotFoundException(run.halo.app.exception.ThemeNotFoundException) NotFoundException(run.halo.app.exception.NotFoundException) 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) ServiceException(run.halo.app.exception.ServiceException) ThemeProperty(run.halo.app.handler.theme.config.support.ThemeProperty) Transactional(org.springframework.transaction.annotation.Transactional)

Example 38 with BadRequestException

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

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 39 with BadRequestException

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

the class AdminServiceImpl method clearToken.

@Override
public void clearToken() {
    // Check if the current is logging in
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        throw new BadRequestException("您尚未登录,因此无法注销");
    }
    // Get current user
    User user = authentication.getDetail().getUser();
    // Clear access token
    cacheStore.getAny(SecurityUtils.buildAccessTokenKey(user), String.class).ifPresent(accessToken -> {
        // Delete token
        cacheStore.delete(SecurityUtils.buildTokenAccessKey(accessToken));
        cacheStore.delete(SecurityUtils.buildAccessTokenKey(user));
    });
    // Clear refresh token
    cacheStore.getAny(SecurityUtils.buildRefreshTokenKey(user), String.class).ifPresent(refreshToken -> {
        cacheStore.delete(SecurityUtils.buildTokenRefreshKey(refreshToken));
        cacheStore.delete(SecurityUtils.buildRefreshTokenKey(user));
    });
    eventPublisher.publishEvent(new LogEvent(this, user.getUsername(), LogType.LOGGED_OUT, user.getNickname()));
    log.info("You have been logged out, looking forward to your next visit!");
}
Also used : User(run.halo.app.model.entity.User) LogEvent(run.halo.app.event.logger.LogEvent) Authentication(run.halo.app.security.authentication.Authentication) BadRequestException(run.halo.app.exception.BadRequestException)

Example 40 with BadRequestException

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

the class BackupServiceImpl method backupWorkDirectory.

@Override
public BackupDTO backupWorkDirectory(List<String> options) {
    if (CollectionUtils.isEmpty(options)) {
        throw new BadRequestException("The options parameter is missing, at least one.");
    }
    // Zip work directory to temporary file
    try {
        // Create zip path for halo zip
        String haloZipFileName = HALO_BACKUP_PREFIX + DateTimeUtils.format(LocalDateTime.now(), HORIZONTAL_LINE_DATETIME_FORMATTER) + HaloUtils.simpleUUID().hashCode() + ".zip";
        // Create halo zip file
        Path haloZipFilePath = Paths.get(haloProperties.getBackupDir(), haloZipFileName);
        if (!Files.exists(haloZipFilePath.getParent())) {
            Files.createDirectories(haloZipFilePath.getParent());
        }
        Path haloZipPath = Files.createFile(haloZipFilePath);
        // Zip halo
        FileUtils.zip(Paths.get(this.haloProperties.getWorkDir()), haloZipPath, path -> {
            for (String itemToBackup : options) {
                Path backupItemPath = Paths.get(this.haloProperties.getWorkDir()).resolve(itemToBackup);
                if (path.startsWith(backupItemPath)) {
                    return true;
                }
            }
            return false;
        });
        // Build backup dto
        return buildBackupDto(BACKUP_RESOURCE_BASE_URI, haloZipPath);
    } catch (IOException e) {
        throw new ServiceException("Failed to backup halo", e);
    }
}
Also used : Path(java.nio.file.Path) ServiceException(run.halo.app.exception.ServiceException) BadRequestException(run.halo.app.exception.BadRequestException) IOException(java.io.IOException)

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 Transactional (org.springframework.transaction.annotation.Transactional)5 ThemeUpdatedEvent (run.halo.app.event.theme.ThemeUpdatedEvent)5 Category (run.halo.app.model.entity.Category)5 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