Skip to content

Commit

Permalink
🌂 daily optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
hellokaton committed Oct 16, 2017
1 parent c1cb811 commit 17271b4
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 168 deletions.
11 changes: 7 additions & 4 deletions src/main/java/com/tale/controller/admin/AttachController.java
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public String index(Request request, @Param(defaultValue = "1") int page,
@JSON
public RestResponse upload(Request request) {

log.info("UPLOAD DIR = {}", TaleUtils.upDir);
log.info("UPLOAD DIR = {}", TaleUtils.UP_DIR);

Users users = this.user();
Integer uid = users.getUid();
Expand All @@ -95,7 +95,7 @@ public RestResponse upload(Request request) {
String fkey = TaleUtils.getFileKey(fname);

String ftype = f.getContentType().contains("image") ? Types.IMAGE : Types.FILE;
String filePath = TaleUtils.upDir + fkey;
String filePath = TaleUtils.UP_DIR + fkey;

try {
Files.write(Paths.get(filePath), f.getData());
Expand Down Expand Up @@ -150,8 +150,11 @@ public RestResponse delete(@Param Integer id, Request request) {
new Logs(LogActions.DEL_ATTACH, attach.getFkey(), request.address(), this.getUid()).save();
} catch (Exception e) {
String msg = "附件删除失败";
if (e instanceof TipException) msg = e.getMessage();
else log.error(msg, e);
if (e instanceof TipException) {
msg = e.getMessage();
} else {
log.error(msg, e);
}
return RestResponse.fail(msg);
}
return RestResponse.ok();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public RestResponse doAdvanced(@Param String cache_key, @Param String block_ips,
@Param String allow_install) {
// 清除缓存
if (StringKit.isNotBlank(cache_key)) {
if (cache_key.equals("*")) {
if ("*".equals(cache_key)) {
cache.clean();
} else {
cache.del(cache_key);
Expand Down
7 changes: 2 additions & 5 deletions src/main/java/com/tale/extension/Commons.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ public final class Commons {

private static SiteService siteService;

private static final List EMPTY = new ArrayList(0);

private static final Random rand = new Random();

private static final String TEMPLATES = "/templates/";

public static void setSiteService(SiteService ss) {
Expand Down Expand Up @@ -244,6 +240,7 @@ public static String emoji(String value) {
return EmojiParser.parseToUnicode(value);
}

private static final Pattern SRC_PATTERN = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)");
/**
* 获取文章第一张图片
*
Expand All @@ -259,7 +256,7 @@ public static String show_thumb(String content) {
if (m_image.find()) {
img = img + "," + m_image.group();
// //匹配src
Matcher m = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)").matcher(img);
Matcher m = SRC_PATTERN.matcher(img);
if (m.find()) {
return m.group(1);
}
Expand Down
36 changes: 6 additions & 30 deletions src/main/java/com/tale/hooks/BaseWebHook.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
package com.tale.hooks;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.StringKit;
import com.blade.kit.UUID;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.hook.WebHook;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.tale.init.TaleConst;
import com.tale.model.dto.Types;
import com.tale.model.entity.Users;
import com.tale.utils.MapCache;
import com.tale.utils.TaleUtils;
import lombok.extern.slf4j.Slf4j;

@Bean
@Slf4j
public class BaseWebHook implements WebHook {

private MapCache cache = MapCache.single();

@Override
public boolean before(Signature signature) {
Request request = signature.request();
Request request = signature.request();
Response response = signature.response();

String uri = request.uri();
String ip = request.address();
String ip = request.address();

// 禁止该ip访问
if(TaleConst.BLOCK_IPS.contains(ip)){
if (TaleConst.BLOCK_IPS.contains(ip)) {
response.text("You have been banned, brother");
return false;
}
Expand All @@ -56,33 +50,15 @@ public boolean before(Signature signature) {
}
}

if(uri.startsWith("/admin") && !uri.startsWith("/admin/login")){
if(null == user){
if (uri.startsWith("/admin") && !uri.startsWith("/admin/login")) {
if (null == user) {
response.redirect("/admin/login");
return false;
}
request.attribute("plugin_menus", TaleConst.plugin_menus);
request.attribute("PLUGIN_MENUS", TaleConst.PLUGIN_MENUS);
}
}
String method = request.method();
if(method.equals("GET")){
String csrf_token = UUID.UU64();
// 默认存储20分钟
int timeout = TaleConst.BCONF.getInt("app.csrf-token-timeout", 20) * 60;
cache.hset(Types.CSRF_TOKEN, csrf_token, uri, timeout);
request.attribute("_csrf_token", csrf_token);
}
return true;
}

@Override
public boolean after(Signature signature) {
Request request = signature.request();
String _csrf_token = request.attribute("del_csrf_token");
if(StringKit.isNotBlank(_csrf_token)){
// 移除本次token
cache.hdel(Types.CSRF_TOKEN, _csrf_token);
}
return true;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/tale/init/TaleConst.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class TaleConst {
/**
* 插件菜单
*/
public static final List<PluginMenu> plugin_menus = new ArrayList<>();
public static final List<PluginMenu> PLUGIN_MENUS = new ArrayList<>();

/**
* 上传文件最大20M
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/tale/init/TaleLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ private TaleLoader() {

private static Blade blade;

public static void init(Blade blade_) {
blade = blade_;
public static void init(Blade blade) {
TaleLoader.blade = blade;
loadPlugins();
loadThemes();
}
Expand Down
23 changes: 16 additions & 7 deletions src/main/java/com/tale/service/ContentsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,31 +51,40 @@ public Optional<Contents> getContents(String id) {
* @param contents 文章对象
*/
public Integer publish(Contents contents) {
if (null == contents)
if (null == contents) {
throw new TipException("文章对象为空");
if (StringKit.isBlank(contents.getTitle()))
}
if (StringKit.isBlank(contents.getTitle())) {
throw new TipException("文章标题不能为空");
}
if (contents.getTitle().length() > TaleConst.MAX_TITLE_COUNT) {
throw new TipException("文章标题最多可以输入" + TaleConst.MAX_TITLE_COUNT + "个字符");
}

if (StringKit.isBlank(contents.getContent()))
if (StringKit.isBlank(contents.getContent())) {
throw new TipException("文章内容不能为空");
}
// 最多可以输入5w个字
int len = contents.getContent().length();
if (len > TaleConst.MAX_TEXT_COUNT)
if (len > TaleConst.MAX_TEXT_COUNT) {
throw new TipException("文章内容最多可以输入" + TaleConst.MAX_TEXT_COUNT + "个字符");
if (null == contents.getAuthorId())
}
if (null == contents.getAuthorId()) {
throw new TipException("请登录后发布文章");
}

if (StringKit.isNotBlank(contents.getSlug())) {
if (contents.getSlug().length() < 5) {
throw new TipException("路径太短了");
}
if (!TaleUtils.isPath(contents.getSlug())) throw new TipException("您输入的路径不合法");
if (!TaleUtils.isPath(contents.getSlug())) {
throw new TipException("您输入的路径不合法");
}

long count = new Contents().where("type", contents.getType()).and("slug", contents.getSlug()).count();
if (count > 0) throw new TipException("该路径已经存在,请重新输入");
if (count > 0) {
throw new TipException("该路径已经存在,请重新输入");
}
}

contents.setContent(EmojiParser.parseToAliases(contents.getContent()));
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/tale/service/MetasService.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ public void delete(int mid) {
temp.setTags(reMeta(name, contents.getTags()));
isUpdate = true;
}
if (isUpdate) temp.update(cid);
if (isUpdate) {
temp.update(cid);
}
});
}
new Relationships().delete("mid", mid);
Expand Down
89 changes: 13 additions & 76 deletions src/main/java/com/tale/utils/TaleUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.Normalizer;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
Expand All @@ -44,10 +43,10 @@ public class TaleUtils {
/**
* 一个月
*/
private static final int one_month = 30 * 24 * 60 * 60;
private static final Random r = new Random();
private static final Hashids hashIds = new Hashids(TaleConst.AES_SALT);
private static final long[] hashPrefix = {-1, 2, 0, 1, 7, 0, 9};
private static final int ONE_MONTH = 30 * 24 * 60 * 60;
private static final Random R = new Random();
private static final Hashids HASH_IDS = new Hashids(TaleConst.AES_SALT);
private static final long[] HASH_PREFIX = {-1, 2, 0, 1, 7, 0, 9};

/**
* 匹配邮箱正则
Expand All @@ -65,12 +64,12 @@ public class TaleUtils {
*/
public static void setCookie(Response response, Integer uid) {
try {
hashPrefix[0] = uid;
String val = hashIds.encode(hashPrefix);
hashPrefix[0] = -1;
HASH_PREFIX[0] = uid;
String val = HASH_IDS.encode(HASH_PREFIX);
HASH_PREFIX[0] = -1;
// String val = new String(EncrypKit.encryptAES(uid.toString().getBytes(), TaleConst.AES_SALT.getBytes()));
boolean isSSL = Commons.site_url().startsWith("https");
response.cookie("/", TaleConst.USER_IN_COOKIE, val, one_month, isSSL);
response.cookie("/", TaleConst.USER_IN_COOKIE, val, ONE_MONTH, isSSL);
} catch (Exception e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -114,7 +113,7 @@ public static Integer getCookieUid(Request request) {
if (c.isPresent()) {
try {
String value = c.get();
long[] ids = hashIds.decode(value);
long[] ids = HASH_IDS.decode(value);
if (null != ids && ids.length > 0) {
return Long.valueOf(ids[0]).intValue();
}
Expand Down Expand Up @@ -235,8 +234,6 @@ public static boolean isPath(String slug) {
return false;
}

private static final Pattern pattern = Pattern.compile("[0x1f]*");

/**
* 获取RSS输出
*
Expand Down Expand Up @@ -306,66 +303,6 @@ public static String cleanXSS(String value) {
return value;
}

/**
* 过滤XSS注入
*
* @param value
* @return
*/
public static String filterXSS(String value) {
String cleanValue = null;
if (value != null) {
cleanValue = Normalizer.normalize(value, Normalizer.Form.NFD);
// Avoid null characters
cleanValue = cleanValue.replaceAll("\0", "");

// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid anything in a src='...' type of expression
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid expression(...) expressions
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");

// Avoid onload= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
cleanValue = scriptPattern.matcher(cleanValue).replaceAll("");
}
return cleanValue;
}

public static void download(Response response, String filePath) throws Exception {
File file = new File(filePath);
response.download(file.getName(), file);
}

/**
* 获取某个范围内的随机数
*
Expand All @@ -381,8 +318,8 @@ public static int[] random(int max, int len) {
}
//随机交换values.length次
for (int i = 0; i < values.length; i++) {
temp1 = Math.abs(r.nextInt()) % (values.length - 1); //随机产生一个位置
temp2 = Math.abs(r.nextInt()) % (values.length - 1); //随机产生另一个位置
temp1 = Math.abs(R.nextInt()) % (values.length - 1); //随机产生一个位置
temp2 = Math.abs(R.nextInt()) % (values.length - 1); //随机产生另一个位置
if (temp1 != temp2) {
temp3 = values[temp1];
values[temp1] = values[temp2];
Expand All @@ -406,11 +343,11 @@ public static <T> String listToInSql(java.util.List<T> list) {
return '(' + sbuf.substring(1);
}

public static final String upDir = AttachController.CLASSPATH.substring(0, AttachController.CLASSPATH.length() - 1);
public static final String UP_DIR = AttachController.CLASSPATH.substring(0, AttachController.CLASSPATH.length() - 1);

public static String getFileKey(String name) {
String prefix = "/upload/" + DateKit.toString(new Date(), "yyyy/MM");
String dir = upDir + prefix;
String dir = UP_DIR + prefix;
if (!Files.exists(Paths.get(dir))) {
new File(dir).mkdirs();
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/tale/utils/ZipUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static void addFolderToZip(String path, String srcFolder, ZipOutputStream
File folder = new File(srcFolder);
if (null != path && folder.isDirectory()) {
for (String fileName : folder.list()) {
if (path.equals("")) {
if ("".equals(path)) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
Expand Down
Loading

0 comments on commit 17271b4

Please sign in to comment.