Search in sources :

Example 1 with Auth

use of com.qiniu.util.Auth in project solo by b3log.

the class AdminConsole method showAdminIndex.

/**
     * Shows administrator index with the specified context.
     *
     * @param request the specified request
     * @param context the specified context
     */
@RequestProcessing(value = "/admin-index.do", method = HTTPRequestMethod.GET)
public void showAdminIndex(final HttpServletRequest request, final HTTPRequestContext context) {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    final String templateName = "admin-index.ftl";
    renderer.setTemplateName(templateName);
    final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
    final Map<String, Object> dataModel = renderer.getDataModel();
    dataModel.putAll(langs);
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    final String userName = currentUser.optString(User.USER_NAME);
    dataModel.put(User.USER_NAME, userName);
    final String roleName = currentUser.optString(User.USER_ROLE);
    dataModel.put(User.USER_ROLE, roleName);
    final String email = currentUser.optString(User.USER_EMAIL);
    final String userAvatar = currentUser.optString(UserExt.USER_AVATAR);
    if (!Strings.isEmptyOrNull(userAvatar)) {
        dataModel.put(Common.GRAVATAR, userAvatar);
    } else {
        final String gravatar = Thumbnails.getGravatarURL(email, "128");
        dataModel.put(Common.GRAVATAR, gravatar);
    }
    try {
        final JSONObject qiniu = optionQueryService.getOptions(Option.CATEGORY_C_QINIU);
        dataModel.put(Option.ID_C_QINIU_DOMAIN, "");
        dataModel.put("qiniuUploadToken", "");
        if (null != qiniu && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_ACCESS_KEY)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_SECRET_KEY)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_BUCKET)) && StringUtils.isNotBlank(qiniu.optString(Option.ID_C_QINIU_DOMAIN))) {
            try {
                final Auth auth = Auth.create(qiniu.optString(Option.ID_C_QINIU_ACCESS_KEY), qiniu.optString(Option.ID_C_QINIU_SECRET_KEY));
                final String uploadToken = auth.uploadToken(qiniu.optString(Option.ID_C_QINIU_BUCKET), null, 3600 * 6, null);
                dataModel.put("qiniuUploadToken", uploadToken);
                dataModel.put(Option.ID_C_QINIU_DOMAIN, qiniu.optString(Option.ID_C_QINIU_DOMAIN));
            } catch (final Exception e) {
                LOGGER.log(Level.ERROR, "Qiniu settings error", e);
            }
        }
        final JSONObject preference = preferenceQueryService.getPreference();
        dataModel.put(Option.ID_C_LOCALE_STRING, preference.getString(Option.ID_C_LOCALE_STRING));
        dataModel.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
        dataModel.put(Option.ID_C_BLOG_SUBTITLE, preference.getString(Option.ID_C_BLOG_SUBTITLE));
        dataModel.put(Common.VERSION, SoloServletListener.VERSION);
        dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
        dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
        dataModel.put(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT, preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT));
        dataModel.put(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE, preference.getInt(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE));
        dataModel.put(Option.ID_C_LOCALE_STRING, preference.getString(Option.ID_C_LOCALE_STRING));
        dataModel.put(Option.ID_C_EDITOR_TYPE, preference.getString(Option.ID_C_EDITOR_TYPE));
        dataModel.put(Skin.SKIN_DIR_NAME, preference.getString(Skin.SKIN_DIR_NAME));
        Keys.fillRuntime(dataModel);
        filler.fillMinified(dataModel);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Admin index render failed", e);
    }
    fireFreeMarkerActionEvent(templateName, dataModel);
}
Also used : JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) ConsoleRenderer(org.b3log.solo.processor.renderer.ConsoleRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 2 with Auth

use of com.qiniu.util.Auth in project wechat4j by hexiangtao.

the class FileUploadHelper method uploadToQiniu.

public String uploadToQiniu(InputStream is, String fileName) {
    try {
        String host = Constant.configReader.get(Constant.QIUNIU_IMG_URL);
        String fileKey = generateFileKey(fileName);
        Auth auth = Auth.create(ak, secret);
        String uploadToken = auth.uploadToken(bucket);
        byte[] buffer = new byte[is.available()];
        IOUtils.readFully(is, buffer);
        Response response = uploadManager.put(buffer, fileKey, uploadToken);
        return response.isOK() ? host + fileKey : "";
    } catch (Exception ex) {
        return "";
    }
}
Also used : Response(com.qiniu.http.Response) Auth(com.qiniu.util.Auth)

Example 3 with Auth

use of com.qiniu.util.Auth in project symphony by b3log.

the class ArticleProcessor method showAddArticle.

/**
 * Shows add article.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/post", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class })
@After(adviceClass = { CSRFToken.class, PermissionGrant.class, StopwatchEndAdvice.class })
public void showAddArticle(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    context.setRenderer(renderer);
    renderer.setTemplateName("/home/post.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    // Qiniu file upload authenticate
    final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
    final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket"));
    dataModel.put("qiniuUploadToken", uploadToken);
    dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain"));
    if (!Symphonys.getBoolean("qiniu.enabled")) {
        dataModel.put("qiniuUploadToken", "");
    }
    final long imgMaxSize = Symphonys.getLong("upload.img.maxSize");
    dataModel.put("imgMaxSize", imgMaxSize);
    final long fileMaxSize = Symphonys.getLong("upload.file.maxSize");
    dataModel.put("fileMaxSize", fileMaxSize);
    String tags = request.getParameter(Tag.TAGS);
    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    if (StringUtils.isBlank(tags)) {
        tags = "";
        dataModel.put(Tag.TAGS, tags);
    } else {
        tags = Tag.formatTags(tags);
        final String[] tagTitles = tags.split(",");
        final StringBuilder tagBuilder = new StringBuilder();
        for (final String title : tagTitles) {
            final String tagTitle = title.trim();
            if (Strings.isEmptyOrNull(tagTitle)) {
                continue;
            }
            if (Tag.containsWhiteListTags(tagTitle)) {
                tagBuilder.append(tagTitle).append(",");
                continue;
            }
            if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) {
                continue;
            }
            if (tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH) {
                continue;
            }
            if (!Role.ROLE_ID_C_ADMIN.equals(currentUser.optString(User.USER_ROLE)) && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) {
                continue;
            }
            tagBuilder.append(tagTitle).append(",");
        }
        if (tagBuilder.length() > 0) {
            tagBuilder.deleteCharAt(tagBuilder.length() - 1);
        }
        dataModel.put(Tag.TAGS, tagBuilder.toString());
    }
    final String type = request.getParameter(Common.TYPE);
    if (StringUtils.isBlank(type)) {
        dataModel.put(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL);
    } else {
        int articleType = Article.ARTICLE_TYPE_C_NORMAL;
        try {
            articleType = Integer.valueOf(type);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Gets article type error [" + type + "]", e);
        }
        if (Article.isInvalidArticleType(articleType)) {
            articleType = Article.ARTICLE_TYPE_C_NORMAL;
        }
        dataModel.put(Article.ARTICLE_TYPE, articleType);
    }
    String at = request.getParameter(Common.AT);
    at = StringUtils.trim(at);
    if (StringUtils.isNotBlank(at)) {
        dataModel.put(Common.AT, at + " ");
    }
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
    String rewardEditorPlaceholderLabel = langPropsService.get("rewardEditorPlaceholderLabel");
    rewardEditorPlaceholderLabel = rewardEditorPlaceholderLabel.replace("{point}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_REWARD));
    dataModel.put("rewardEditorPlaceholderLabel", rewardEditorPlaceholderLabel);
    dataModel.put(Common.BROADCAST_POINT, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_BROADCAST);
    String articleContentErrorLabel = langPropsService.get("articleContentErrorLabel");
    articleContentErrorLabel = articleContentErrorLabel.replace("{maxArticleContentLength}", String.valueOf(ArticleAddValidation.MAX_ARTICLE_CONTENT_LENGTH));
    dataModel.put("articleContentErrorLabel", articleContentErrorLabel);
    final String b3Key = currentUser.optString(UserExt.USER_B3_KEY);
    final String b3ClientAddArticle = currentUser.optString(UserExt.USER_B3_CLIENT_ADD_ARTICLE_URL);
    final String b3ClientUpdateArticle = currentUser.optString(UserExt.USER_B3_CLIENT_UPDATE_ARTICLE_URL);
    dataModel.put("hasB3Key", StringUtils.isNotBlank(b3Key) && StringUtils.isNotBlank(b3ClientAddArticle) && StringUtils.isNotBlank(b3ClientUpdateArticle));
    fillPostArticleRequisite(dataModel, currentUser);
    fillDomainsWithTags(dataModel);
}
Also used : JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) ServiceException(org.b3log.latke.service.ServiceException) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 4 with Auth

use of com.qiniu.util.Auth in project symphony by b3log.

the class LoginProcessor method showGuide.

/**
 * Shows login page.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/guide", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class })
@After(adviceClass = { CSRFToken.class, PermissionGrant.class, StopwatchEndAdvice.class })
public void showGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
    final int step = currentUser.optInt(UserExt.USER_GUIDE_STEP);
    if (UserExt.USER_GUIDE_STEP_FIN == step) {
        response.sendRedirect(Latkes.getServePath());
        return;
    }
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    context.setRenderer(renderer);
    renderer.setTemplateName("/verify/guide.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    dataModel.put(Common.CURRENT_USER, currentUser);
    final List<JSONObject> tags = tagQueryService.getTags(32);
    dataModel.put(Tag.TAGS, tags);
    final List<JSONObject> users = userQueryService.getNiceUsers(6);
    final Iterator<JSONObject> iterator = users.iterator();
    while (iterator.hasNext()) {
        final JSONObject user = iterator.next();
        if (user.optString(Keys.OBJECT_ID).equals(currentUser.optString(Keys.OBJECT_ID))) {
            iterator.remove();
            break;
        }
    }
    dataModel.put(User.USERS, users);
    // Qiniu file upload authenticate
    final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
    final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket"));
    dataModel.put("qiniuUploadToken", uploadToken);
    dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain"));
    if (!Symphonys.getBoolean("qiniu.enabled")) {
        dataModel.put("qiniuUploadToken", "");
    }
    final long imgMaxSize = Symphonys.getLong("upload.img.maxSize");
    dataModel.put("imgMaxSize", imgMaxSize);
    final long fileMaxSize = Symphonys.getLong("upload.file.maxSize");
    dataModel.put("fileMaxSize", fileMaxSize);
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
}
Also used : JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 5 with Auth

use of com.qiniu.util.Auth in project symphony by b3log.

the class SettingsProcessor method showSettings.

/**
 * Shows settings pages.
 *
 * @param context  the specified context
 * @param request  the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = { "/settings", "/settings/*" }, method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, LoginCheck.class })
@After(adviceClass = { CSRFToken.class, PermissionGrant.class, StopwatchEndAdvice.class })
public void showSettings(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
    context.setRenderer(renderer);
    final String requestURI = request.getRequestURI();
    String page = StringUtils.substringAfter(requestURI, "/settings/");
    if (StringUtils.isBlank(page)) {
        page = "profile";
    }
    page += ".ftl";
    renderer.setTemplateName("/home/settings/" + page);
    final Map<String, Object> dataModel = renderer.getDataModel();
    final JSONObject user = (JSONObject) request.getAttribute(User.USER);
    user.put(UserExt.USER_T_CREATE_TIME, new Date(user.getLong(Keys.OBJECT_ID)));
    UserProcessor.fillHomeUser(dataModel, user, roleQueryService);
    final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
    avatarQueryService.fillUserAvatarURL(avatarViewMode, user);
    final String userId = user.optString(Keys.OBJECT_ID);
    final int invitedUserCount = userQueryService.getInvitedUserCount(userId);
    dataModel.put(Common.INVITED_USER_COUNT, invitedUserCount);
    // Qiniu file upload authenticate
    final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey"));
    final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket"));
    dataModel.put("qiniuUploadToken", uploadToken);
    dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain"));
    if (!Symphonys.getBoolean("qiniu.enabled")) {
        dataModel.put("qiniuUploadToken", "");
    }
    final long imgMaxSize = Symphonys.getLong("upload.img.maxSize");
    dataModel.put("imgMaxSize", imgMaxSize);
    final long fileMaxSize = Symphonys.getLong("upload.file.maxSize");
    dataModel.put("fileMaxSize", fileMaxSize);
    dataModelService.fillHeaderAndFooter(request, response, dataModel);
    String inviteTipLabel = (String) dataModel.get("inviteTipLabel");
    inviteTipLabel = inviteTipLabel.replace("{point}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_INVITE_REGISTER));
    dataModel.put("inviteTipLabel", inviteTipLabel);
    String pointTransferTipLabel = (String) dataModel.get("pointTransferTipLabel");
    pointTransferTipLabel = pointTransferTipLabel.replace("{point}", Symphonys.get("pointTransferMin"));
    dataModel.put("pointTransferTipLabel", pointTransferTipLabel);
    String dataExportTipLabel = (String) dataModel.get("dataExportTipLabel");
    dataExportTipLabel = dataExportTipLabel.replace("{point}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_DATA_EXPORT));
    dataModel.put("dataExportTipLabel", dataExportTipLabel);
    final String allowRegister = optionQueryService.getAllowRegister();
    dataModel.put("allowRegister", allowRegister);
    String buyInvitecodeLabel = langPropsService.get("buyInvitecodeLabel");
    buyInvitecodeLabel = buyInvitecodeLabel.replace("${point}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_BUY_INVITECODE));
    buyInvitecodeLabel = buyInvitecodeLabel.replace("${point2}", String.valueOf(Pointtransfer.TRANSFER_SUM_C_INVITECODE_USED));
    dataModel.put("buyInvitecodeLabel", buyInvitecodeLabel);
    final List<JSONObject> invitecodes = invitecodeQueryService.getValidInvitecodes(userId);
    for (final JSONObject invitecode : invitecodes) {
        String msg = langPropsService.get("expireTipLabel");
        msg = msg.replace("${time}", DateFormatUtils.format(invitecode.optLong(Keys.OBJECT_ID) + Symphonys.getLong("invitecode.expired"), "yyyy-MM-dd HH:mm"));
        invitecode.put(Common.MEMO, msg);
    }
    dataModel.put(Invitecode.INVITECODES, (Object) invitecodes);
    if (requestURI.contains("function")) {
        dataModel.put(Emotion.EMOTIONS, emotionQueryService.getEmojis(userId));
        dataModel.put(Emotion.SHORT_T_LIST, emojiLists);
    }
    if (requestURI.contains("i18n")) {
        dataModel.put(Common.LANGUAGES, Languages.getAvailableLanguages());
        final List<JSONObject> timezones = new ArrayList<>();
        final List<TimeZones.TimeZoneWithDisplayNames> timeZones = TimeZones.getInstance().getTimeZones();
        for (final TimeZones.TimeZoneWithDisplayNames timeZone : timeZones) {
            final JSONObject timezone = new JSONObject();
            timezone.put(Common.ID, timeZone.getTimeZone().getID());
            timezone.put(Common.NAME, timeZone.getDisplayName());
            timezones.add(timezone);
        }
        dataModel.put(Common.TIMEZONES, timezones);
    }
    dataModel.put(Common.TYPE, "settings");
}
Also used : TimeZones(org.b3log.symphony.util.TimeZones) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) JSONObject(org.json.JSONObject) Auth(com.qiniu.util.Auth) JSONObject(org.json.JSONObject) Before(org.b3log.latke.servlet.annotation.Before) After(org.b3log.latke.servlet.annotation.After) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Aggregations

Auth (com.qiniu.util.Auth)18 JSONObject (org.json.JSONObject)10 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)8 Configuration (com.qiniu.storage.Configuration)7 After (org.b3log.latke.servlet.annotation.After)7 Before (org.b3log.latke.servlet.annotation.Before)7 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)7 UploadManager (com.qiniu.storage.UploadManager)6 Response (com.qiniu.http.Response)4 QiniuException (com.qiniu.common.QiniuException)3 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 ServiceException (org.b3log.latke.service.ServiceException)3 XmallUploadException (cn.exrick.common.exception.XmallUploadException)2 Gson (com.google.gson.Gson)2 DefaultPutRet (com.qiniu.storage.model.DefaultPutRet)2 OkHttpClient (okhttp3.OkHttpClient)2 JSONArray (org.json.JSONArray)2 UnderFileSystemConfiguration (alluxio.underfs.UnderFileSystemConfiguration)1 BucketManager (com.qiniu.storage.BucketManager)1