Search in sources :

Example 1 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by ruibaby.

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

use of run.halo.app.exception.BadRequestException in project halo by ruibaby.

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

use of run.halo.app.exception.BadRequestException in project halo by ruibaby.

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

use of run.halo.app.exception.BadRequestException in project halo by ruibaby.

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
        run.halo.app.utils.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)

Example 5 with BadRequestException

use of run.halo.app.exception.BadRequestException in project halo by ruibaby.

the class BackupServiceImpl method importData.

@Override
public void importData(MultipartFile file) throws IOException {
    String jsonContent = FileUtils.readString(file.getInputStream());
    ObjectMapper mapper = JsonUtils.createDefaultJsonMapper();
    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {
    };
    HashMap<String, Object> data = mapper.readValue(jsonContent, typeRef);
    String version = (String) Objects.requireNonNullElse(data.get("version"), "");
    if (!VersionUtil.hasSameMajorAndMinorVersion(HaloConst.HALO_VERSION, version)) {
        throw new BadRequestException("导入数据的主次版本号与当前系统版本号不匹配,不支持导入!");
    }
    List<Attachment> attachments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("attachments")), Attachment[].class));
    attachmentService.createInBatch(attachments);
    List<Category> categories = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("categories")), Category[].class));
    categoryService.createInBatch(categories);
    List<Tag> tags = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("tags")), Tag[].class));
    tagService.createInBatch(tags);
    List<CommentBlackList> commentBlackList = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("comment_black_list")), CommentBlackList[].class));
    commentBlackListService.createInBatch(commentBlackList);
    List<Journal> journals = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("journals")), Journal[].class));
    journalService.createInBatch(journals);
    List<JournalComment> journalComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("journal_comments")), JournalComment[].class));
    journalCommentService.createInBatch(journalComments);
    List<Link> links = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("links")), Link[].class));
    linkService.createInBatch(links);
    List<Log> logs = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("logs")), Log[].class));
    logService.createInBatch(logs);
    List<Menu> menus = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("menus")), Menu[].class));
    menuService.createInBatch(menus);
    List<Option> options = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("options")), Option[].class));
    optionService.createInBatch(options);
    eventPublisher.publishEvent(new OptionUpdatedEvent(this));
    List<Photo> photos = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("photos")), Photo[].class));
    photoService.createInBatch(photos);
    List<Post> posts = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("posts")), Post[].class));
    postService.createInBatch(posts);
    List<Content> contents = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("contents")), Content[].class));
    contentService.createInBatch(contents);
    List<ContentPatchLog> contentPatchLogs = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("content_patch_logs")), ContentPatchLog[].class));
    contentPatchLogService.createInBatch(contentPatchLogs);
    List<PostCategory> postCategories = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_categories")), PostCategory[].class));
    postCategoryService.createInBatch(postCategories);
    List<PostComment> postComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_comments")), PostComment[].class));
    postCommentService.createInBatch(postComments);
    List<PostMeta> postMetas = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_metas")), PostMeta[].class));
    postMetaService.createInBatch(postMetas);
    List<PostTag> postTags = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("post_tags")), PostTag[].class));
    postTagService.createInBatch(postTags);
    List<Sheet> sheets = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheets")), Sheet[].class));
    sheetService.createInBatch(sheets);
    List<SheetComment> sheetComments = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheet_comments")), SheetComment[].class));
    sheetCommentService.createInBatch(sheetComments);
    List<SheetMeta> sheetMetas = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("sheet_metas")), SheetMeta[].class));
    sheetMetaService.createInBatch(sheetMetas);
    List<ThemeSetting> themeSettings = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("theme_settings")), ThemeSetting[].class));
    themeSettingService.createInBatch(themeSettings);
    eventPublisher.publishEvent(new ThemeUpdatedEvent(this));
    List<User> users = Arrays.asList(mapper.readValue(mapper.writeValueAsString(data.get("user")), User[].class));
    if (users.size() > 0) {
        userService.create(users.get(0));
    }
}
Also used : SheetMeta(run.halo.app.model.entity.SheetMeta) HashMap(java.util.HashMap) JournalComment(run.halo.app.model.entity.JournalComment) Attachment(run.halo.app.model.entity.Attachment) Journal(run.halo.app.model.entity.Journal) Photo(run.halo.app.model.entity.Photo) ContentPatchLog(run.halo.app.model.entity.ContentPatchLog) PostComment(run.halo.app.model.entity.PostComment) PostMeta(run.halo.app.model.entity.PostMeta) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ContentPatchLog(run.halo.app.model.entity.ContentPatchLog) Log(run.halo.app.model.entity.Log) Content(run.halo.app.model.entity.Content) ThemeUpdatedEvent(run.halo.app.event.theme.ThemeUpdatedEvent) Option(run.halo.app.model.entity.Option) CommentBlackList(run.halo.app.model.entity.CommentBlackList) Link(run.halo.app.model.entity.Link) SheetComment(run.halo.app.model.entity.SheetComment) Category(run.halo.app.model.entity.Category) PostCategory(run.halo.app.model.entity.PostCategory) User(run.halo.app.model.entity.User) OptionUpdatedEvent(run.halo.app.event.options.OptionUpdatedEvent) PostCategory(run.halo.app.model.entity.PostCategory) ThemeSetting(run.halo.app.model.entity.ThemeSetting) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Menu(run.halo.app.model.entity.Menu) PostTag(run.halo.app.model.entity.PostTag) Post(run.halo.app.model.entity.Post) BadRequestException(run.halo.app.exception.BadRequestException) PostTag(run.halo.app.model.entity.PostTag) Tag(run.halo.app.model.entity.Tag) Sheet(run.halo.app.model.entity.Sheet)

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