Commit 110d7da6 authored by Liang Ding's avatar Liang Ding

#12515 重构获取登录用户

parent 380325d2
...@@ -17,24 +17,25 @@ ...@@ -17,24 +17,25 @@
*/ */
package org.b3log.solo; package org.b3log.solo;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
import org.b3log.latke.Latkes; import org.b3log.latke.Latkes;
import org.b3log.latke.event.EventManager; import org.b3log.latke.event.EventManager;
import org.b3log.latke.ioc.BeanManager; import org.b3log.latke.ioc.BeanManager;
import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger; import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.User;
import org.b3log.latke.plugin.PluginManager; import org.b3log.latke.plugin.PluginManager;
import org.b3log.latke.plugin.ViewLoadEventHandler; import org.b3log.latke.plugin.ViewLoadEventHandler;
import org.b3log.latke.repository.Transaction; import org.b3log.latke.repository.Transaction;
import org.b3log.latke.repository.jdbc.JdbcRepository; import org.b3log.latke.repository.jdbc.JdbcRepository;
import org.b3log.latke.servlet.AbstractServletListener; import org.b3log.latke.servlet.AbstractServletListener;
import org.b3log.latke.util.Requests; import org.b3log.latke.util.*;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.b3log.solo.event.*; import org.b3log.solo.event.*;
import org.b3log.solo.model.Option; import org.b3log.solo.model.Option;
import org.b3log.solo.model.Skin; import org.b3log.solo.model.Skin;
import org.b3log.solo.repository.OptionRepository; import org.b3log.solo.repository.OptionRepository;
import org.b3log.solo.repository.UserRepository;
import org.b3log.solo.service.*; import org.b3log.solo.service.*;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Solos; import org.b3log.solo.util.Solos;
...@@ -42,17 +43,14 @@ import org.json.JSONObject; ...@@ -42,17 +43,14 @@ import org.json.JSONObject;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestEvent;
import javax.servlet.http.Cookie; import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import java.util.Set; import java.util.Set;
/** /**
* Solo Servlet listener. * Solo Servlet listener.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.9.3.41, Sep 27, 2018 * @version 1.9.3.42, Oct 5, 2018
* @since 0.3.1 * @since 0.3.1
*/ */
public final class SoloServletListener extends AbstractServletListener { public final class SoloServletListener extends AbstractServletListener {
...@@ -143,11 +141,6 @@ public final class SoloServletListener extends AbstractServletListener { ...@@ -143,11 +141,6 @@ public final class SoloServletListener extends AbstractServletListener {
LOGGER.log(Level.DEBUG, "Request made from a search engine [User-Agent={0}]", httpServletRequest.getHeader("User-Agent")); LOGGER.log(Level.DEBUG, "Request made from a search engine [User-Agent={0}]", httpServletRequest.getHeader("User-Agent"));
httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true); httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true);
} else { } else {
final HttpSession session = httpServletRequest.getSession();
LOGGER.log(Level.DEBUG, "Gets a session [id={0}, remoteAddr={1}, User-Agent={2}, isNew={3}]", session.getId(),
httpServletRequest.getRemoteAddr(), httpServletRequest.getHeader("User-Agent"), session.isNew());
// Online visitor count
final StatisticMgmtService statisticMgmtService = beanManager.getReference(StatisticMgmtService.class); final StatisticMgmtService statisticMgmtService = beanManager.getReference(StatisticMgmtService.class);
statisticMgmtService.onlineVisitorCount(httpServletRequest); statisticMgmtService.onlineVisitorCount(httpServletRequest);
} }
......
...@@ -33,8 +33,8 @@ import org.b3log.solo.model.Article; ...@@ -33,8 +33,8 @@ import org.b3log.solo.model.Article;
import org.b3log.solo.model.Page; import org.b3log.solo.model.Page;
import org.b3log.solo.repository.ArticleRepository; import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.PageRepository; import org.b3log.solo.repository.PageRepository;
import org.b3log.solo.service.ArticleQueryService;
import org.b3log.solo.service.PermalinkQueryService; import org.b3log.solo.service.PermalinkQueryService;
import org.b3log.solo.util.Solos;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.*; import javax.servlet.*;
...@@ -46,7 +46,7 @@ import java.io.IOException; ...@@ -46,7 +46,7 @@ import java.io.IOException;
* Article/Page permalink filter. * Article/Page permalink filter.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.7, Jan 8, 2013 * @version 1.0.1.8, Oct 5, 2018
* @see org.b3log.solo.processor.ArticleProcessor#showArticle(org.b3log.latke.servlet.HTTPRequestContext, * @see org.b3log.solo.processor.ArticleProcessor#showArticle(org.b3log.latke.servlet.HTTPRequestContext,
* javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
* @see org.b3log.solo.processor.PageProcessor#showPage(org.b3log.latke.servlet.HTTPRequestContext) * @see org.b3log.solo.processor.PageProcessor#showPage(org.b3log.latke.servlet.HTTPRequestContext)
...@@ -116,9 +116,8 @@ public final class PermalinkFilter implements Filter { ...@@ -116,9 +116,8 @@ public final class PermalinkFilter implements Filter {
return; return;
} }
// If requests an article and the article need view passowrd, sends redirect to the password form // If requests an article and the article need view password, sends redirect to the password form
final ArticleQueryService articleQueryService = beanManager.getReference(ArticleQueryService.class); if (null != article && Solos.needViewPwd(httpServletRequest, article)) {
if (null != article && articleQueryService.needViewPwd(httpServletRequest, article)) {
try { try {
httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd?articleId=" + article.optString(Keys.OBJECT_ID)); httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd?articleId=" + article.optString(Keys.OBJECT_ID));
......
...@@ -36,6 +36,7 @@ import org.b3log.solo.service.UserMgmtService; ...@@ -36,6 +36,7 @@ import org.b3log.solo.service.UserMgmtService;
import org.b3log.solo.service.UserQueryService; import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Emotions; import org.b3log.solo.util.Emotions;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Solos;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -49,7 +50,7 @@ import java.util.Map; ...@@ -49,7 +50,7 @@ import java.util.Map;
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author ArmstrongCN * @author ArmstrongCN
* @version 1.3.3.1, Mar 3, 2018 * @version 1.3.3.2, Oct 5, 2018
* @since 0.3.1 * @since 0.3.1
*/ */
@RequestProcessor @RequestProcessor
...@@ -283,14 +284,11 @@ public class CommentProcessor { ...@@ -283,14 +284,11 @@ public class CommentProcessor {
* Fills commenter info if logged in. * Fills commenter info if logged in.
* *
* @param requestJSONObject the specified request json object * @param requestJSONObject the specified request json object
* @param httpServletRequest the specified HTTP servlet request * @param request the specified HTTP servlet request
* @param httpServletResponse the specified HTTP servlet response * @param request the specified HTTP servlet response
*/ */
private void fillCommenter(final JSONObject requestJSONObject, private void fillCommenter(final JSONObject requestJSONObject, final HttpServletRequest request, final HttpServletResponse response) {
final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) { final JSONObject currentUser = Solos.getCurrentUser(request, response);
userMgmtService.tryLogInWithCookie(httpServletRequest, httpServletResponse);
final JSONObject currentUser = userQueryService.getCurrentUser(httpServletRequest);
if (null == currentUser) { if (null == currentUser) {
return; return;
} }
......
...@@ -64,7 +64,7 @@ import java.util.Map; ...@@ -64,7 +64,7 @@ import java.util.Map;
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a> * @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @author <a href="mailto:dongxu.wang@acm.org">Dongxu Wang</a> * @author <a href="mailto:dongxu.wang@acm.org">Dongxu Wang</a>
* @author <a href="https://github.com/nanolikeyou">nanolikeyou</a> * @author <a href="https://github.com/nanolikeyou">nanolikeyou</a>
* @version 1.1.1.13, Sep 16, 2018 * @version 1.1.1.14, Oct 5, 2018
* @since 0.3.1 * @since 0.3.1
*/ */
@RequestProcessor @RequestProcessor
...@@ -146,10 +146,7 @@ public class LoginProcessor { ...@@ -146,10 +146,7 @@ public class LoginProcessor {
} }
final HttpServletResponse response = context.getResponse(); final HttpServletResponse response = context.getResponse();
if (null != Solos.getCurrentUser(request, response)) { // User has already logged in
userMgmtService.tryLogInWithCookie(request, response);
if (null != userQueryService.getCurrentUser(request)) { // User has already logged in
response.sendRedirect(destinationURL); response.sendRedirect(destinationURL);
return; return;
......
...@@ -69,7 +69,7 @@ import java.util.*; ...@@ -69,7 +69,7 @@ import java.util.*;
* Admin console render processing. * Admin console render processing.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.7.0.5, Sep 25, 2018 * @version 1.7.0.6, Oct 5, 2018
* @since 0.4.1 * @since 0.4.1
*/ */
@RequestProcessor @RequestProcessor
...@@ -133,10 +133,11 @@ public class AdminConsole { ...@@ -133,10 +133,11 @@ public class AdminConsole {
* Shows administrator index with the specified context. * Shows administrator index with the specified context.
* *
* @param request the specified request * @param request the specified request
* @param response the specified response
* @param context the specified context * @param context the specified context
*/ */
@RequestProcessing(value = "/admin-index.do", method = HTTPRequestMethod.GET) @RequestProcessing(value = "/admin-index.do", method = HTTPRequestMethod.GET)
public void showAdminIndex(final HttpServletRequest request, final HTTPRequestContext context) { public void showAdminIndex(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) {
final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer(); final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();
context.setRenderer(renderer); context.setRenderer(renderer);
final String templateName = "admin-index.ftl"; final String templateName = "admin-index.ftl";
...@@ -144,7 +145,7 @@ public class AdminConsole { ...@@ -144,7 +145,7 @@ public class AdminConsole {
final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale()); final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
final Map<String, Object> dataModel = renderer.getDataModel(); final Map<String, Object> dataModel = renderer.getDataModel();
dataModel.putAll(langs); dataModel.putAll(langs);
final JSONObject currentUser = userQueryService.getCurrentUser(request); final JSONObject currentUser = Solos.getCurrentUser(request, response);
final String userName = currentUser.optString(User.USER_NAME); final String userName = currentUser.optString(User.USER_NAME);
dataModel.put(User.USER_NAME, userName); dataModel.put(User.USER_NAME, userName);
final String roleName = currentUser.optString(User.USER_ROLE); final String roleName = currentUser.optString(User.USER_ROLE);
......
...@@ -42,6 +42,7 @@ import org.b3log.solo.service.UserQueryService; ...@@ -42,6 +42,7 @@ import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Emotions; import org.b3log.solo.util.Emotions;
import org.b3log.solo.util.Images; import org.b3log.solo.util.Images;
import org.b3log.solo.util.Markdowns; import org.b3log.solo.util.Markdowns;
import org.b3log.solo.util.Solos;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -54,7 +55,7 @@ import java.util.stream.Collectors; ...@@ -54,7 +55,7 @@ import java.util.stream.Collectors;
* Article console request processing. * Article console request processing.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.1.1.3, Sep 25, 2018 * @version 1.1.1.4, Oct 5, 2018
* @since 0.4.0 * @since 0.4.0
*/ */
@RequestProcessor @RequestProcessor
...@@ -335,8 +336,10 @@ public class ArticleConsole { ...@@ -335,8 +336,10 @@ public class ArticleConsole {
final JSONObject ret = new JSONObject(); final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret); renderer.setJSONObject(ret);
final JSONObject currentUser = Solos.getCurrentUser(request, response);
try { try {
if (!articleQueryService.canAccessArticle(articleId, request)) { if (!articleQueryService.canAccessArticle(articleId, currentUser)) {
ret.put(Keys.STATUS_CODE, false); ret.put(Keys.STATUS_CODE, false);
ret.put(Keys.MSG, langPropsService.get("forbiddenLabel")); ret.put(Keys.MSG, langPropsService.get("forbiddenLabel"));
...@@ -383,7 +386,8 @@ public class ArticleConsole { ...@@ -383,7 +386,8 @@ public class ArticleConsole {
try { try {
final String articleId = request.getRequestURI().substring((Latkes.getContextPath() + "/console/article/unpublish/").length()); final String articleId = request.getRequestURI().substring((Latkes.getContextPath() + "/console/article/unpublish/").length());
if (!articleQueryService.canAccessArticle(articleId, request)) { final JSONObject currentUser = Solos.getCurrentUser(request, response);
if (!articleQueryService.canAccessArticle(articleId, currentUser)) {
ret.put(Keys.STATUS_CODE, false); ret.put(Keys.STATUS_CODE, false);
ret.put(Keys.MSG, langPropsService.get("forbiddenLabel")); ret.put(Keys.MSG, langPropsService.get("forbiddenLabel"));
...@@ -545,7 +549,8 @@ public class ArticleConsole { ...@@ -545,7 +549,8 @@ public class ArticleConsole {
final String articleId = article.getString(Keys.OBJECT_ID); final String articleId = article.getString(Keys.OBJECT_ID);
renderer.setJSONObject(ret); renderer.setJSONObject(ret);
if (!articleQueryService.canAccessArticle(articleId, request)) { final JSONObject currentUser = Solos.getCurrentUser(request, response);
if (!articleQueryService.canAccessArticle(articleId, currentUser)) {
ret.put(Keys.MSG, langPropsService.get("forbiddenLabel")); ret.put(Keys.MSG, langPropsService.get("forbiddenLabel"));
ret.put(Keys.STATUS_CODE, false); ret.put(Keys.STATUS_CODE, false);
...@@ -606,7 +611,7 @@ public class ArticleConsole { ...@@ -606,7 +611,7 @@ public class ArticleConsole {
final JSONObject ret = new JSONObject(); final JSONObject ret = new JSONObject();
try { try {
final JSONObject currentUser = userQueryService.getCurrentUser(request); final JSONObject currentUser = Solos.getCurrentUser(request, response);
requestJSONObject.getJSONObject(Article.ARTICLE).put(Article.ARTICLE_AUTHOR_ID, currentUser.getString(Keys.OBJECT_ID)); requestJSONObject.getJSONObject(Article.ARTICLE).put(Article.ARTICLE_AUTHOR_ID, currentUser.getString(Keys.OBJECT_ID));
final String articleId = articleMgmtService.addArticle(requestJSONObject); final String articleId = articleMgmtService.addArticle(requestJSONObject);
......
...@@ -26,6 +26,7 @@ import org.b3log.latke.servlet.HTTPRequestContext; ...@@ -26,6 +26,7 @@ import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.advice.BeforeRequestProcessAdvice; import org.b3log.latke.servlet.advice.BeforeRequestProcessAdvice;
import org.b3log.latke.servlet.advice.RequestProcessAdviceException; import org.b3log.latke.servlet.advice.RequestProcessAdviceException;
import org.b3log.solo.service.UserQueryService; import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Solos;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
...@@ -36,7 +37,7 @@ import java.util.Map; ...@@ -36,7 +37,7 @@ import java.util.Map;
* The common auth check before advice for admin console. * The common auth check before advice for admin console.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.1.1, Sep 25, 2018 * @version 1.0.1.2, Oct 5, 2018
* @since 2.9.5 * @since 2.9.5
*/ */
@Singleton @Singleton
...@@ -51,7 +52,8 @@ public class ConsoleAuthAdvice extends BeforeRequestProcessAdvice { ...@@ -51,7 +52,8 @@ public class ConsoleAuthAdvice extends BeforeRequestProcessAdvice {
@Override @Override
public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException { public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args) throws RequestProcessAdviceException {
final HttpServletRequest request = context.getRequest(); final HttpServletRequest request = context.getRequest();
if (!userQueryService.isLoggedIn(request, context.getResponse())) { final HttpServletResponse response = context.getResponse();
if (!userQueryService.isLoggedIn(request, response)) {
final JSONObject exception401 = new JSONObject(); final JSONObject exception401 = new JSONObject();
exception401.put(Keys.MSG, "Unauthorized to request [" + request.getRequestURI() + "]"); exception401.put(Keys.MSG, "Unauthorized to request [" + request.getRequestURI() + "]");
exception401.put(Keys.STATUS_CODE, HttpServletResponse.SC_UNAUTHORIZED); exception401.put(Keys.STATUS_CODE, HttpServletResponse.SC_UNAUTHORIZED);
...@@ -59,7 +61,8 @@ public class ConsoleAuthAdvice extends BeforeRequestProcessAdvice { ...@@ -59,7 +61,8 @@ public class ConsoleAuthAdvice extends BeforeRequestProcessAdvice {
throw new RequestProcessAdviceException(exception401); throw new RequestProcessAdviceException(exception401);
} }
final JSONObject currentUser = userQueryService.getCurrentUser(request);
final JSONObject currentUser = Solos.getCurrentUser(request, response);
final String userRole = currentUser.optString(User.USER_ROLE); final String userRole = currentUser.optString(User.USER_ROLE);
if (Role.VISITOR_ROLE.equals(userRole)) { if (Role.VISITOR_ROLE.equals(userRole)) {
final JSONObject exception403 = new JSONObject(); final JSONObject exception403 = new JSONObject();
......
...@@ -36,12 +36,12 @@ import org.b3log.solo.model.*; ...@@ -36,12 +36,12 @@ import org.b3log.solo.model.*;
import org.b3log.solo.repository.*; import org.b3log.solo.repository.*;
import org.b3log.solo.util.Emotions; import org.b3log.solo.util.Emotions;
import org.b3log.solo.util.Markdowns; import org.b3log.solo.util.Markdowns;
import org.b3log.solo.util.Solos;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*; import java.util.*;
import static org.b3log.solo.model.Article.*; import static org.b3log.solo.model.Article.*;
...@@ -53,7 +53,7 @@ import static org.b3log.solo.model.Article.*; ...@@ -53,7 +53,7 @@ import static org.b3log.solo.model.Article.*;
* @author <a href="http://blog.sweelia.com">ArmstrongCN</a> * @author <a href="http://blog.sweelia.com">ArmstrongCN</a>
* @author <a href="http://zephyr.b3log.org">Zephyr</a> * @author <a href="http://zephyr.b3log.org">Zephyr</a>
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a> * @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @version 1.3.2.4, Sep 16, 2018 * @version 1.3.2.5, Oct 5, 2018
* @since 0.3.5 * @since 0.3.5
*/ */
@Service @Service
...@@ -252,70 +252,30 @@ public class ArticleQueryService { ...@@ -252,70 +252,30 @@ public class ArticleQueryService {
} }
/** /**
* Can the current user access an article specified by the given article id? * Can the specified user access an article specified by the given article id?
* *
* @param articleId the given article id * @param articleId the given article id
* @param request the specified request * @param user the specified user
* @return {@code true} if the current user can access the article, {@code false} otherwise * @return {@code true} if the current user can access the article, {@code false} otherwise
* @throws Exception exception * @throws Exception exception
*/ */
public boolean canAccessArticle(final String articleId, final HttpServletRequest request) throws Exception { public boolean canAccessArticle(final String articleId, final JSONObject user) throws Exception {
if (StringUtils.isBlank(articleId)) { if (StringUtils.isBlank(articleId)) {
return false; return false;
} }
if (userQueryService.isAdminLoggedIn(request)) { if (null == user) {
return true;
}
final JSONObject article = articleRepository.get(articleId);
final String currentUserId = userQueryService.getCurrentUser(request).getString(Keys.OBJECT_ID);
return article.getString(Article.ARTICLE_AUTHOR_ID).equals(currentUserId);
}
/**
* Checks whether need password to view the specified article with the specified request.
* <p>
* Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}.
* </p>
* <p>
* The blogger itself dose not need view password never.
* </p>
*
* @param request the specified request
* @param article the specified article
* @return {@code true} if need, returns {@code false} otherwise
*/
public boolean needViewPwd(final HttpServletRequest request, final JSONObject article) {
final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD);
if (StringUtils.isBlank(articleViewPwd)) {
return false; return false;
} }
if (null == request) { if (Role.ADMIN_ROLE.equals(user.optString(User.USER_ROLE))) {
return true; return true;
} }
final HttpSession session = request.getSession(false); final JSONObject article = articleRepository.get(articleId);
final String currentUserId = user.getString(Keys.OBJECT_ID);
if (null != session) {
@SuppressWarnings("unchecked")
Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
if (null == viewPwds) {
viewPwds = new HashMap<String, String>();
}
if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
return false;
}
}
final JSONObject currentUser = userQueryService.getCurrentUser(request);
return !(null != currentUser && !Role.VISITOR_ROLE.equals(currentUser.optString(User.USER_ROLE))); return article.getString(Article.ARTICLE_AUTHOR_ID).equals(currentUserId);
} }
/** /**
...@@ -1027,7 +987,7 @@ public class ArticleQueryService { ...@@ -1027,7 +987,7 @@ public class ArticleQueryService {
return null; return null;
} }
if (needViewPwd(request, article)) { if (Solos.needViewPwd(request, article)) {
final String content = langPropsService.get("articleContentPwd"); final String content = langPropsService.get("articleContentPwd");
article.put(ARTICLE_CONTENT, content); article.put(ARTICLE_CONTENT, content);
......
...@@ -28,6 +28,7 @@ import org.b3log.latke.repository.SortDirection; ...@@ -28,6 +28,7 @@ import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service; import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Sessions;
import org.b3log.solo.model.Article; import org.b3log.solo.model.Article;
import org.b3log.solo.model.Comment; import org.b3log.solo.model.Comment;
import org.b3log.solo.model.Common; import org.b3log.solo.model.Common;
...@@ -52,7 +53,7 @@ import java.util.List; ...@@ -52,7 +53,7 @@ import java.util.List;
* Comment query service. * Comment query service.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.3.2.1, Sep 16, 2018 * @version 1.3.2.2, Oct 5, 2018
* @since 0.3.5 * @since 0.3.5
*/ */
@Service @Service
...@@ -122,7 +123,12 @@ public class CommentQueryService { ...@@ -122,7 +123,12 @@ public class CommentQueryService {
return false; return false;
} }
final String currentUserId = userQueryService.getCurrentUser(request).getString(Keys.OBJECT_ID); final JSONObject currentUser = Sessions.currentUser(request);
if (null == currentUser) {
return false;
}
final String currentUserId = currentUser.getString(Keys.OBJECT_ID);
return article.getString(Article.ARTICLE_AUTHOR_ID).equals(currentUserId); return article.getString(Article.ARTICLE_AUTHOR_ID).equals(currentUserId);
} }
......
...@@ -61,7 +61,7 @@ import static org.b3log.solo.model.Article.ARTICLE_CONTENT; ...@@ -61,7 +61,7 @@ import static org.b3log.solo.model.Article.ARTICLE_CONTENT;
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a> * @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @version 1.6.16.10, Sep 28, 2018 * @version 1.6.16.11, Oct 5, 2018
* @since 0.3.1 * @since 0.3.1
*/ */
@Service @Service
...@@ -544,18 +544,19 @@ public class DataModelService { ...@@ -544,18 +544,19 @@ public class DataModelService {
throws ServiceException { throws ServiceException {
fillSide(request, dataModel, preference); fillSide(request, dataModel, preference);
fillBlogHeader(request, response, dataModel, preference); fillBlogHeader(request, response, dataModel, preference);
fillBlogFooter(request, dataModel, preference); fillBlogFooter(request, response, dataModel, preference);
} }
/** /**
* Fills footer.ftl. * Fills footer.ftl.
* *
* @param request the specified HTTP servlet request * @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
* @param dataModel data model * @param dataModel data model
* @param preference the specified preference * @param preference the specified preference
* @throws ServiceException service exception * @throws ServiceException service exception
*/ */
private void fillBlogFooter(final HttpServletRequest request, final Map<String, Object> dataModel, final JSONObject preference) private void fillBlogFooter(final HttpServletRequest request, final HttpServletResponse response, final Map<String, Object> dataModel, final JSONObject preference)
throws ServiceException { throws ServiceException {
Stopwatchs.start("Fill Footer"); Stopwatchs.start("Fill Footer");
try { try {
...@@ -576,7 +577,7 @@ public class DataModelService { ...@@ -576,7 +577,7 @@ public class DataModelService {
dataModel.put(Keys.Server.SERVER, Latkes.getServer()); dataModel.put(Keys.Server.SERVER, Latkes.getServer());
dataModel.put(Common.IS_INDEX, "/".equals(request.getRequestURI())); dataModel.put(Common.IS_INDEX, "/".equals(request.getRequestURI()));
dataModel.put(User.USER_NAME, ""); dataModel.put(User.USER_NAME, "");
final JSONObject currentUser = userQueryService.getCurrentUser(request); final JSONObject currentUser = Solos.getCurrentUser(request, response);
if (null != currentUser) { if (null != currentUser) {
final String userAvatar = currentUser.optString(UserExt.USER_AVATAR); final String userAvatar = currentUser.optString(UserExt.USER_AVATAR);
if (StringUtils.isNotBlank(userAvatar)) { if (StringUtils.isNotBlank(userAvatar)) {
...@@ -648,7 +649,7 @@ public class DataModelService { ...@@ -648,7 +649,7 @@ public class DataModelService {
} }
dataModel.put(Option.ID_C_META_DESCRIPTION, metaDescription); dataModel.put(Option.ID_C_META_DESCRIPTION, metaDescription);
dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
dataModel.put(Common.IS_LOGGED_IN, null != userQueryService.getCurrentUser(request)); dataModel.put(Common.IS_LOGGED_IN, null != Solos.getCurrentUser(request, response));
dataModel.put(Common.FAVICON_API, Solos.FAVICON_API); dataModel.put(Common.FAVICON_API, Solos.FAVICON_API);
final String noticeBoard = preference.getString(Option.ID_C_NOTICE_BOARD); final String noticeBoard = preference.getString(Option.ID_C_NOTICE_BOARD);
dataModel.put(Option.ID_C_NOTICE_BOARD, noticeBoard); dataModel.put(Option.ID_C_NOTICE_BOARD, noticeBoard);
...@@ -891,7 +892,7 @@ public class DataModelService { ...@@ -891,7 +892,7 @@ public class DataModelService {
article.put(Common.HAS_UPDATED, false); article.put(Common.HAS_UPDATED, false);
} }
if (articleQueryService.needViewPwd(request, article)) { if (Solos.needViewPwd(request, article)) {
final String content = langPropsService.get("articleContentPwd"); final String content = langPropsService.get("articleContentPwd");
article.put(ARTICLE_CONTENT, content); article.put(ARTICLE_CONTENT, content);
} }
...@@ -975,9 +976,8 @@ public class DataModelService { ...@@ -975,9 +976,8 @@ public class DataModelService {
try { try {
final Template topBarTemplate = Skins.getTemplate("top-bar.ftl"); final Template topBarTemplate = Skins.getTemplate("top-bar.ftl");
final StringWriter stringWriter = new StringWriter(); final StringWriter stringWriter = new StringWriter();
final Map<String, Object> topBarModel = new HashMap<String, Object>(); final Map<String, Object> topBarModel = new HashMap<>();
userMgmtService.tryLogInWithCookie(request, response); final JSONObject currentUser = Solos.getCurrentUser(request, response);
final JSONObject currentUser = userQueryService.getCurrentUser(request);
Keys.fillServer(topBarModel); Keys.fillServer(topBarModel);
topBarModel.put(Common.IS_LOGGED_IN, false); topBarModel.put(Common.IS_LOGGED_IN, false);
......
...@@ -32,8 +32,6 @@ import org.b3log.latke.service.LangPropsService; ...@@ -32,8 +32,6 @@ import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service; import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils; import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Crypts;
import org.b3log.latke.util.Sessions;
import org.b3log.latke.util.Strings; import org.b3log.latke.util.Strings;
import org.b3log.solo.model.Option; import org.b3log.solo.model.Option;
import org.b3log.solo.model.UserExt; import org.b3log.solo.model.UserExt;
...@@ -42,9 +40,6 @@ import org.b3log.solo.util.Solos; ...@@ -42,9 +40,6 @@ import org.b3log.solo.util.Solos;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set; import java.util.Set;
/** /**
...@@ -53,7 +48,7 @@ import java.util.Set; ...@@ -53,7 +48,7 @@ import java.util.Set;
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="mailto:385321165@qq.com">DASHU</a> * @author <a href="mailto:385321165@qq.com">DASHU</a>
* @author <a href="https://github.com/nanolikeyou">nanolikeyou</a> * @author <a href="https://github.com/nanolikeyou">nanolikeyou</a>
* @version 1.1.0.13, Sep 21, 2018 * @version 1.1.0.14, Oct 5, 2018
* @since 0.4.0 * @since 0.4.0
*/ */
@Service @Service
...@@ -93,59 +88,6 @@ public class UserMgmtService { ...@@ -93,59 +88,6 @@ public class UserMgmtService {
@Inject @Inject
private OptionMgmtService optionMgmtService; private OptionMgmtService optionMgmtService;
/**
* Tries to login with cookie.
*
* @param request the specified request
* @param response the specified response
*/
public void tryLogInWithCookie(final HttpServletRequest request, final HttpServletResponse response) {
final Cookie[] cookies = request.getCookies();
if (null == cookies || 0 == cookies.length) {
return;
}
try {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
if (!Sessions.COOKIE_NAME.equals(cookie.getName())) {
continue;
}
final String value = Crypts.decryptByAES(cookie.getValue(), Sessions.COOKIE_SECRET);
final JSONObject cookieJSONObject = new JSONObject(value);
final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
if (StringUtils.isBlank(userId)) {
break;
}
JSONObject user = userRepository.get(userId);
if (null == user) {
break;
}
final String userPassword = user.optString(User.USER_PASSWORD);
final String token = cookieJSONObject.optString(Keys.TOKEN);
final String hashPassword = StringUtils.substringBeforeLast(token, ":");
if (userPassword.equals(hashPassword)) {
Sessions.login(request, response, user);
LOGGER.log(Level.DEBUG, "Logged in with cookie [email={0}]", user.optString(User.USER_EMAIL));
}
}
} catch (final Exception e) {
LOGGER.log(Level.TRACE, "Parses cookie failed, clears the cookie [name=" + Sessions.COOKIE_NAME + "]");
final Cookie cookie = new Cookie(Sessions.COOKIE_NAME, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
}
/** /**
* Updates a user by the specified request json object. * Updates a user by the specified request json object.
* *
......
...@@ -33,6 +33,7 @@ import org.b3log.latke.util.Paginator; ...@@ -33,6 +33,7 @@ import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Sessions; import org.b3log.latke.util.Sessions;
import org.b3log.latke.util.URLs; import org.b3log.latke.util.URLs;
import org.b3log.solo.repository.UserRepository; import org.b3log.solo.repository.UserRepository;
import org.b3log.solo.util.Solos;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -44,7 +45,7 @@ import java.util.List; ...@@ -44,7 +45,7 @@ import java.util.List;
* User query service. * User query service.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.6, Sep 21, 2018 * @version 1.0.0.7, Oct 5, 2018
* @since 0.4.0 * @since 0.4.0
*/ */
@Service @Service
...@@ -71,19 +72,12 @@ public class UserQueryService { ...@@ -71,19 +72,12 @@ public class UserQueryService {
* Checks whether the current request is made by a logged in user * Checks whether the current request is made by a logged in user
* (including default user and administrator lists in <i>users</i>). * (including default user and administrator lists in <i>users</i>).
* *
* <p>
* Invokes this method will try to login with cookie first.
* </p>
*
* @param request the specified request * @param request the specified request
* @param response the specified response * @param response the specified response
* @return {@code true} if the current request is made by logged in user, * @return {@code true} if the current request is made by logged in user, returns {@code false} otherwise
* returns {@code false} otherwise
*/ */
public boolean isLoggedIn(final HttpServletRequest request, final HttpServletResponse response) { public boolean isLoggedIn(final HttpServletRequest request, final HttpServletResponse response) {
userMgmtService.tryLogInWithCookie(request, response); return null != Solos.getCurrentUser(request, response);
return null != Sessions.currentUser(request);
} }
/** /**
...@@ -102,28 +96,6 @@ public class UserQueryService { ...@@ -102,28 +96,6 @@ public class UserQueryService {
return Role.ADMIN_ROLE.equals(user.optString(User.USER_ROLE)); return Role.ADMIN_ROLE.equals(user.optString(User.USER_ROLE));
} }
/**
* Gets the current user.
*
* @param request the specified request
* @return the current user, {@code null} if not found
*/
public JSONObject getCurrentUser(final HttpServletRequest request) {
JSONObject currentUser = Sessions.currentUser(request);
if (null == currentUser) {
return null;
}
final String email = currentUser.optString(User.USER_EMAIL);
try {
return userRepository.getByEmail(email);
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets current user by request failed, returns null", e);
return null;
}
}
/** /**
* Gets the administrator. * Gets the administrator.
* *
......
...@@ -19,12 +19,27 @@ package org.b3log.solo.util; ...@@ -19,12 +19,27 @@ package org.b3log.solo.util;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.ioc.BeanManager;
import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger; import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Role;
import org.b3log.latke.model.User;
import org.b3log.latke.util.CollectionUtils; import org.b3log.latke.util.CollectionUtils;
import org.b3log.latke.util.Crypts;
import org.b3log.latke.util.Sessions;
import org.b3log.solo.SoloServletListener; import org.b3log.solo.SoloServletListener;
import org.b3log.solo.model.Article;
import org.b3log.solo.model.Common;
import org.b3log.solo.repository.UserRepository;
import org.json.JSONObject; import org.json.JSONObject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException; import java.util.MissingResourceException;
import java.util.ResourceBundle; import java.util.ResourceBundle;
...@@ -32,7 +47,7 @@ import java.util.ResourceBundle; ...@@ -32,7 +47,7 @@ import java.util.ResourceBundle;
* Solo utilities. * Solo utilities.
* *
* @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.3.0.0, Sep 28, 2018 * @version 1.4.0.0, Oct 5, 2018
* @since 2.8.0 * @since 2.8.0
*/ */
public final class Solos { public final class Solos {
...@@ -110,6 +125,110 @@ public final class Solos { ...@@ -110,6 +125,110 @@ public final class Solos {
MOBILE_SKIN = mobileSkin; MOBILE_SKIN = mobileSkin;
} }
/**
* Checks whether need password to view the specified article with the specified request.
* <p>
* Checks session, if not represents, checks article property {@link Article#ARTICLE_VIEW_PWD view password}.
* </p>
* <p>
* The blogger itself dose not need view password never.
* </p>
*
* @param request the specified request
* @param article the specified article
* @return {@code true} if need, returns {@code false} otherwise
*/
public static boolean needViewPwd(final HttpServletRequest request, final JSONObject article) {
final String articleViewPwd = article.optString(Article.ARTICLE_VIEW_PWD);
if (StringUtils.isBlank(articleViewPwd)) {
return false;
}
if (null == request) {
return true;
}
final HttpSession session = request.getSession(false);
if (null != session) {
Map<String, String> viewPwds = (Map<String, String>) session.getAttribute(Common.ARTICLES_VIEW_PWD);
if (null == viewPwds) {
viewPwds = new HashMap<>();
}
if (articleViewPwd.equals(viewPwds.get(article.optString(Keys.OBJECT_ID)))) {
return false;
}
}
final JSONObject currentUser = getCurrentUser(request, null);
return !(null != currentUser && !Role.VISITOR_ROLE.equals(currentUser.optString(User.USER_ROLE)));
}
/**
* Gets the current logged-in user.
*
* @param request the specified request
* @param response the specified response
* @return the current logged-in user, returns {@code null} if not found
*/
public static JSONObject getCurrentUser(final HttpServletRequest request, final HttpServletResponse response) {
request.getSession(); // create session if need
JSONObject ret = Sessions.currentUser(request);
if (null != ret) {
return ret;
}
final Cookie[] cookies = request.getCookies();
if (null == cookies || 0 == cookies.length) {
return null;
}
final BeanManager beanManager = BeanManager.getInstance();
final UserRepository userRepository = beanManager.getReference(UserRepository.class);
try {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
if (!Sessions.COOKIE_NAME.equals(cookie.getName())) {
continue;
}
final String value = Crypts.decryptByAES(cookie.getValue(), Sessions.COOKIE_SECRET);
final JSONObject cookieJSONObject = new JSONObject(value);
final String userId = cookieJSONObject.optString(Keys.OBJECT_ID);
if (StringUtils.isBlank(userId)) {
break;
}
JSONObject user = userRepository.get(userId);
if (null == user) {
break;
}
final String userPassword = user.optString(User.USER_PASSWORD);
final String token = cookieJSONObject.optString(Keys.TOKEN);
final String hashPassword = StringUtils.substringBeforeLast(token, ":");
if (userPassword.equals(hashPassword)) {
Sessions.login(request, response, user);
return Sessions.currentUser(request);
}
}
} catch (final Exception e) {
LOGGER.log(Level.TRACE, "Parses cookie failed, clears the cookie [name=" + Sessions.COOKIE_NAME + "]");
final Cookie cookie = new Cookie(Sessions.COOKIE_NAME, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
return null;
}
/** /**
* Whether user configures the mail.properties. * Whether user configures the mail.properties.
* *
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment