update:一个临时下载链接最多只能下载3次,防止盗链和流量攻击

This commit is contained in:
hrz 2025-04-22 15:41:48 +08:00
parent 5789d69da4
commit 0d73ee1537
5 changed files with 69 additions and 33 deletions

View file

@ -89,4 +89,11 @@ public class RedisKeys {
public static String getOtaIdKey(String uuid) { public static String getOtaIdKey(String uuid) {
return "ota:id:" + uuid; return "ota:id:" + uuid;
} }
/**
* OTA固件下载次数的Key
*/
public static String getOtaDownloadCountKey(String uuid) {
return "ota:download:count:" + uuid;
}
} }

View file

@ -8,6 +8,7 @@ import java.nio.file.Paths;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Map; import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
@ -21,7 +22,6 @@ import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@ -36,6 +36,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.constant.Constant; import xiaozhi.common.constant.Constant;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.redis.RedisKeys;
import xiaozhi.common.redis.RedisUtils; import xiaozhi.common.redis.RedisUtils;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.common.validator.ValidatorUtils; import xiaozhi.common.validator.ValidatorUtils;
@ -97,22 +98,6 @@ public class OTAMagController {
} }
} }
@PutMapping("/{id}")
@Operation(summary = "修改 OTA 固件信息")
@RequiresPermissions("sys:role:superAdmin")
public Result<?> update(@PathVariable("id") String id, @RequestBody OtaEntity entity) {
if (entity == null) {
return new Result<>().error("固件信息不能为空");
}
entity.setId(id);
try {
otaService.update(entity);
return new Result<>();
} catch (RuntimeException e) {
return new Result<>().error(e.getMessage());
}
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@Operation(summary = "OTA 删除") @Operation(summary = "OTA 删除")
@RequiresPermissions("sys:role:superAdmin") @RequiresPermissions("sys:role:superAdmin")
@ -124,10 +109,40 @@ public class OTAMagController {
return new Result<Void>(); return new Result<Void>();
} }
@GetMapping("/download/{id}") @GetMapping("/getDownloadUrl/{id}")
@Operation(summary = "下载固件文件") @Operation(summary = "获取 OTA 固件下载链接")
@RequiresPermissions("sys:role:superAdmin") @RequiresPermissions("sys:role:superAdmin")
public ResponseEntity<byte[]> downloadFirmware(@PathVariable("id") String id) { public Result<String> getDownloadUrl(@PathVariable("id") String id) {
String uuid = UUID.randomUUID().toString();
redisUtils.set(RedisKeys.getOtaIdKey(uuid), id);
return new Result<String>().ok(uuid);
}
@GetMapping("/download/{uuid}")
@Operation(summary = "下载固件文件")
public ResponseEntity<byte[]> downloadFirmware(@PathVariable("uuid") String uuid) {
String id = (String) redisUtils.get(RedisKeys.getOtaIdKey(uuid));
if (StringUtils.isBlank(id)) {
return ResponseEntity.notFound().build();
}
// 检查下载次数
String downloadCountKey = RedisKeys.getOtaDownloadCountKey(uuid);
Integer downloadCount = (Integer) redisUtils.get(downloadCountKey);
if (downloadCount == null) {
downloadCount = 0;
}
// 如果下载次数超过3次,返回404
if (downloadCount >= 3) {
redisUtils.delete(downloadCountKey);
redisUtils.delete(RedisKeys.getOtaIdKey(uuid));
logger.warn("Download limit exceeded for UUID: {}", uuid);
return ResponseEntity.notFound().build();
}
redisUtils.set(downloadCountKey, downloadCount + 1);
try { try {
// 获取固件信息 // 获取固件信息
OtaEntity otaEntity = otaService.selectById(id); OtaEntity otaEntity = otaService.selectById(id);
@ -171,7 +186,7 @@ public class OTAMagController {
byte[] fileContent = Files.readAllBytes(path); byte[] fileContent = Files.readAllBytes(path);
// 设置响应头 // 设置响应头
String originalFilename = otaEntity.getFirmwareName() + "_" + otaEntity.getVersion(); String originalFilename = otaEntity.getType() + "_" + otaEntity.getVersion();
if (firmwarePath.contains(".")) { if (firmwarePath.contains(".")) {
String extension = firmwarePath.substring(firmwarePath.lastIndexOf(".")); String extension = firmwarePath.substring(firmwarePath.lastIndexOf("."));
originalFilename += extension; originalFilename += extension;

View file

@ -69,6 +69,7 @@ public class ShiroConfig {
*/ */
Map<String, String> filterMap = new LinkedHashMap<>(); Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/ota/**", "anon"); filterMap.put("/ota/**", "anon");
filterMap.put("/otaMag/download/**", "anon");
filterMap.put("/webjars/**", "anon"); filterMap.put("/webjars/**", "anon");
filterMap.put("/druid/**", "anon"); filterMap.put("/druid/**", "anon");
filterMap.put("/v3/api-docs/**", "anon"); filterMap.put("/v3/api-docs/**", "anon");

View file

@ -103,5 +103,21 @@ export default {
this.uploadFirmware(file, callback); this.uploadFirmware(file, callback);
}); });
}).send(); }).send();
},
// 获取固件下载链接
getDownloadUrl(id, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/otaMag/getDownloadUrl/${id}`)
.method('GET')
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.fail((err) => {
console.error('获取下载链接失败:', err);
RequestService.reAjaxFun(() => {
this.getDownloadUrl(id, callback);
});
}).send();
} }
} }

View file

@ -361,18 +361,15 @@ export default {
this.$message.error('固件信息不完整'); this.$message.error('固件信息不完整');
return; return;
} }
// 使用正确的API基础URL变量 // 先获取下载链接
const baseUrl = process.env.VUE_APP_API_BASE_URL || ''; Api.ota.getDownloadUrl(firmware.id, (res) => {
window.open(`${window.location.origin}${baseUrl}/ota/download/${firmware.id}`); if (res.data.code === 0) {
}, const uuid = res.data.data;
downloadSelectedFirmwares() { const baseUrl = process.env.VUE_APP_API_BASE_URL || '';
const selectedFirmwares = this.firmwareList.filter(item => item.selected); window.open(`${window.location.origin}${baseUrl}/otaMag/download/${uuid}`);
if (selectedFirmwares.length === 0) { } else {
this.$message.warning('请先选择需要下载的固件'); this.$message.error('获取下载链接失败');
return; }
}
selectedFirmwares.forEach(firmware => {
this.downloadFirmware(firmware);
}); });
}, },
formatDate, formatDate,