添加权限管理

This commit is contained in:
昭荣伊
2020-02-19 18:41:25 +08:00
parent c359245c2d
commit 164c852811
74 changed files with 4480 additions and 420 deletions
+8 -1
View File
@@ -63,7 +63,14 @@ mysql -u root -p
```shell
# 创建库
create database app_manager DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
drop database if exists app_manager;
drop user if exists 'app_manager'@'localhost';
-- 支持emoji:需要mysql数据库参数: character_set_server=utf8mb4
create database app_manager default character set utf8mb4 collate utf8mb4_unicode_ci;
use app_manager;
create user 'app_manager'@'localhost' identified by 'app_manager123456';
grant all privileges on app_manager.* to 'app_manager'@'localhost';
flush privileges;
```
##### HTTPS 证书
+5
View File
@@ -27,6 +27,11 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compile group: 'org.apache.shiro', name: 'shiro-spring-boot-web-starter', version: '1.5.0'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.10'
compile group: 'com.aliyun.oss', name: 'aliyun-sdk-oss', version: '3.1.0'
compile group: 'com.qiniu', name: 'qiniu-java-sdk', version: '7.2.28'
compile group: 'com.qcloud', name: 'cos_api', version: '5.6.15'
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'
compile group: 'com.googlecode.plist', name: 'dd-plist', version: '1.21'
compile group: 'net.dongliu', name: 'apk-parser', version: '2.6.9'
-2
View File
@@ -15,8 +15,6 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.annotation.Resource;
@SpringBootApplication
//@EnableJpaRepositories("org.yzr.dao") // JPA扫描该包路径下的Repositorie
//@EntityScan("org.yzr.model") // 扫描Entity实体类
public class Application {
@Resource
private Environment environment;
@@ -0,0 +1,73 @@
package org.yzr.config;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.yzr.shiro.UserAuthorizingRealm;
import org.yzr.shiro.UserWebSessionManager;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public Realm realm() {
return new UserAuthorizingRealm();
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/account/signin", "anon");
filterChainDefinitionMap.put("/account/logout", "anon");
filterChainDefinitionMap.put("/error/unauthorized", "anon");
filterChainDefinitionMap.put("/apps/**", "authc");
shiroFilterFactoryBean.setLoginUrl("/account/signin");
shiroFilterFactoryBean.setSuccessUrl("/apps");
shiroFilterFactoryBean.setUnauthorizedUrl("/error/unauthorized");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SessionManager sessionManager() {
return new UserWebSessionManager();
}
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor =
new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public static DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true);
return creator;
}
}
@@ -6,6 +6,7 @@ import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.yzr.service.UserService;
import javax.annotation.Resource;
@@ -14,32 +15,36 @@ public class WebAppConfigurer extends WebMvcConfigurationSupport {
@Resource
private Environment environment;
@Resource
private UserService userService;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
try {
String path = ResourceUtils.getURL("").getPath();
String prefix = ResourceUtils.FILE_URL_PREFIX + path;
String debug = environment.getProperty("config.debug");
if (debug !=null && debug.equals("debug")) {
if (debug != null && debug.equals("debug")) {
prefix = "classpath:/";
}
registry.addResourceHandler("/android/**").addResourceLocations(prefix+ "static/upload/android/");
registry.addResourceHandler("/android/**").addResourceLocations(prefix + "static/upload/android/");
registry.addResourceHandler("/ios/**").addResourceLocations(prefix + "static/upload/ios/");
registry.addResourceHandler("/crt/**").addResourceLocations(prefix + "static/crt/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
super.addResourceHandlers(registry);
userService.initUsers();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController( "/" ).setViewName( "forward:/apps" );
super.addViewControllers(registry);
}
// @Override
// protected void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/").setViewName("forward:/apps");
// super.addViewControllers(registry);
// }
}
@@ -1,12 +1,19 @@
package org.yzr.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yzr.model.User;
import org.yzr.service.AppService;
import org.yzr.utils.PathManager;
import org.yzr.utils.file.PathManager;
import org.yzr.utils.response.BaseResponse;
import org.yzr.utils.response.ResponseUtil;
import org.yzr.vo.AppViewModel;
import javax.annotation.Resource;
@@ -23,10 +30,13 @@ public class AppController {
@Resource
private PathManager pathManager;
@RequiresAuthentication
@GetMapping("/apps")
public String apps(HttpServletRequest request) {
try{
List<AppViewModel> apps = this.appService.findAll();
try {
Subject currentUser = SecurityUtils.getSubject();
User user = (User) currentUser.getPrincipal();
List<AppViewModel> apps = this.appService.findByUser(user);
request.setAttribute("apps", apps);
request.setAttribute("baseURL", this.pathManager.getBaseURL(false));
} catch (Exception e) {
@@ -36,6 +46,7 @@ public class AppController {
return "index";
}
@RequiresPermissions("/apps/get")
@GetMapping("/apps/{appID}")
public String getAppById(@PathVariable("appID") String appID, HttpServletRequest request) {
AppViewModel appViewModel = this.appService.getById(appID);
@@ -44,6 +55,7 @@ public class AppController {
return "list";
}
@RequiresPermissions("/packageList/get")
@RequestMapping("/packageList/{appID}")
@ResponseBody
public Map<String, Object> getAppPackageList(@PathVariable("appID") String appID) {
@@ -58,17 +70,25 @@ public class AppController {
return map;
}
@RequiresPermissions("/app/delete")
@RequestMapping("/app/delete/{id}")
@ResponseBody
public Map<String, Object> deleteById(@PathVariable("id") String id) {
Map<String, Object> map = new HashMap<>();
public BaseResponse deleteById(@PathVariable("id") String id) {
try {
this.appService.deleteById(id);
map.put("success", true);
Subject currentUser = SecurityUtils.getSubject();
User user = (User) currentUser.getPrincipal();
if (user == null) {
return ResponseUtil.unauthz();
}
AppViewModel viewModel = this.appService.getById(id);
if (viewModel.getUserId().equals(user.getId())) {
this.appService.deleteById(id);
return ResponseUtil.ok("删除成功");
}
return ResponseUtil.unauthz();
} catch (Exception e) {
map.put("success", false);
return ResponseUtil.fail();
}
return map;
}
}
@@ -1,26 +1,37 @@
package org.yzr.controller;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {
public class ErrorController extends BasicErrorController {
/**
* 所有错误都转到首页
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/error")
public void handleError(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.sendRedirect("/apps");
public ErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@Override
public String getErrorPath() {
return "/error";
@RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
String message = body.get("message").toString();
if (message.startsWith("Subject does not have permission")) {
message = "无操作权限";
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", body.get("status"));
map.put("msg", message);
return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
}
}
@@ -4,17 +4,26 @@ package org.yzr.controller;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yzr.model.App;
import org.yzr.model.Package;
import org.yzr.model.User;
import org.yzr.service.AppService;
import org.yzr.service.PackageService;
import org.yzr.utils.PathManager;
import org.yzr.utils.QRCodeUtil;
import org.yzr.service.UserService;
import org.yzr.utils.file.FileType;
import org.yzr.utils.file.FileUtil;
import org.yzr.utils.file.PathManager;
import org.yzr.utils.image.QRCodeUtil;
import org.yzr.utils.ipa.PlistGenerator;
import org.yzr.utils.response.BaseResponse;
import org.yzr.utils.response.ResponseUtil;
import org.yzr.utils.webhook.WebHookClient;
import org.yzr.vo.AppViewModel;
import org.yzr.vo.PackageViewModel;
@@ -27,6 +36,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
public class PackageController {
@Resource
@@ -35,9 +45,12 @@ public class PackageController {
private PackageService packageService;
@Resource
private PathManager pathManager;
@Resource
private UserService userService;
/**
* 预览页
*
* @param code
* @param request
* @return
@@ -54,19 +67,21 @@ public class PackageController {
/**
* 设备列表
*
* @param id
* @param request
* @return
*/
@GetMapping("/devices/{id}")
public String devices(@PathVariable("id") String id, HttpServletRequest request) {
PackageViewModel viewModel= this.packageService.findById(id);
PackageViewModel viewModel = this.packageService.findById(id);
request.setAttribute("app", viewModel);
return "devices";
}
/**
* 安装教程
*
* @param platform
* @param request
* @return
@@ -79,18 +94,35 @@ public class PackageController {
/**
* 上传包
*
* @param file
* @param request
* @return
*/
@RequestMapping("/app/upload")
@ResponseBody
public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
public BaseResponse upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
try {
String token = request.getParameter("token");
User user = this.userService.findByToken(token);
if (user == null) {
Subject currentUser = SecurityUtils.getSubject();
user = (User) currentUser.getPrincipal();
}
// 无用户信息不允许上传
if (user == null) {
return ResponseUtil.unauthz();
}
String filePath = transfer(file);
Package aPackage = this.packageService.buildPackage(filePath);
Map<String , String> extra = new HashMap<>();
FileType fileType = FileUtil.getType(filePath);
if (fileType == null || fileType != FileType.ZIP) {
// 文件类型错误
FileUtils.forceDelete(new File(filePath));
return ResponseUtil.badArgument();
}
Package aPackage = this.packageService.buildPackage(filePath, user);
Map<String, String> extra = new HashMap<>();
String jobName = request.getParameter("jobName");
String buildNumber = request.getParameter("buildNumber");
if (StringUtils.hasLength(jobName)) {
@@ -102,26 +134,21 @@ public class PackageController {
if (!extra.isEmpty()) {
aPackage.setExtra(JSON.toJSONString(extra));
}
App app = this.appService.getByPackage(aPackage);
app.getPackageList().add(aPackage);
app.setCurrentPackage(aPackage);
aPackage.setApp(app);
app = this.appService.save(app);
App app = this.appService.savePackage(aPackage, user);
// URL
String codeURL = this.pathManager.getBaseURL(false) + "p/code/" + app.getCurrentPackage().getId();
// 发送WebHook消息
WebHookClient.sendMessage(app, pathManager);
map.put("code", codeURL);
map.put("success", true);
return ResponseUtil.ok(codeURL);
} catch (Exception e) {
map.put("success", false);
e.printStackTrace();
return ResponseUtil.badArgument();
}
return map;
}
/**
* 下载文件源文件(ipa 或 apk)
*
* @param id
* @param response
*/
@@ -131,11 +158,11 @@ public class PackageController {
Package aPackage = this.packageService.get(id);
String path = PathManager.getFullPath(aPackage) + aPackage.getFileName();
File file = new File(path);
if(file.exists()){ //判断文件父目录是否存在
if (file.exists()) { //判断文件父目录是否存在
response.setContentType("application/force-download");
// 文件名称转换
String fileName = aPackage.getName() + "_" + aPackage.getVersion();
String ext = "." + FilenameUtils.getExtension(aPackage.getFileName());
String ext = "." + FilenameUtils.getExtension(aPackage.getFileName());
String appName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + appName + ext);
@@ -144,7 +171,7 @@ public class PackageController {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
@@ -158,6 +185,7 @@ public class PackageController {
/**
* 获取 manifest
*
* @param id
* @param response
*/
@@ -178,6 +206,7 @@ public class PackageController {
/**
* 获取包二维码
*
* @param id
* @param response
*/
@@ -196,9 +225,11 @@ public class PackageController {
/**
* 删除包
*
* @param id
* @return
*/
@RequiresPermissions("/p/delete")
@RequestMapping("/p/delete/{id}")
@ResponseBody
public Map<String, Object> deleteById(@PathVariable("id") String id) {
@@ -214,11 +245,13 @@ public class PackageController {
/**
* 转存文件
*
* @param srcFile
* @return
*/
private String transfer(MultipartFile srcFile) {
try {
// 获取文件后缀
String fileName = srcFile.getOriginalFilename();
String ext = FilenameUtils.getExtension(fileName);
@@ -0,0 +1,104 @@
package org.yzr.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.yzr.model.Storage;
import org.yzr.service.StorageService;
import org.yzr.storage.StorageUtil;
import org.yzr.utils.CharUtil;
import org.yzr.utils.response.ResponseUtil;
import java.io.IOException;
@Controller
public class StorageController {
@Autowired
private StorageUtil storageUtil;
@Autowired
private StorageService storageService;
private String generateKey(String originalFilename) {
int index = originalFilename.lastIndexOf('.');
String suffix = originalFilename.substring(index);
String key = null;
Storage storageInfo = null;
do {
key = CharUtil.generate(20) + suffix;
storageInfo = storageService.findByKey(key);
}
while (storageInfo != null);
return key;
}
@PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
Storage Storage = storageUtil.store(file.getInputStream(), file.getSize(), file.getContentType(), originalFilename);
return ResponseUtil.ok(Storage);
}
/**
* 访问存储对象
*
* @param key 存储对象key
* @return
*/
@GetMapping("/fetch/{key:.+}")
public ResponseEntity<Resource> fetch(@PathVariable String key) {
Storage Storage = storageService.findByKey(key);
if (key == null) {
return ResponseEntity.notFound().build();
}
if (key.contains("../")) {
return ResponseEntity.badRequest().build();
}
String type = Storage.getType();
MediaType mediaType = MediaType.parseMediaType(type);
Resource file = storageUtil.loadAsResource(key);
if (file == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().contentType(mediaType).body(file);
}
/**
* 访问存储对象
*
* @param key 存储对象key
* @return
*/
@GetMapping("/download/{key:.+}")
public ResponseEntity<Resource> download(@PathVariable String key) {
Storage Storage = storageService.findByKey(key);
if (key == null) {
return ResponseEntity.notFound().build();
}
if (key.contains("../")) {
return ResponseEntity.badRequest().build();
}
String type = Storage.getType();
MediaType mediaType = MediaType.parseMediaType(type);
Resource file = storageUtil.loadAsResource(key);
if (file == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + file.getFilename() + "\"").body(file);
}
}
@@ -0,0 +1,96 @@
package org.yzr.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yzr.model.User;
import org.yzr.service.UserService;
import org.yzr.utils.IpUtil;
import org.yzr.utils.response.BaseResponse;
import org.yzr.utils.response.ResponseUtil;
import javax.servlet.http.HttpServletRequest;
import static org.yzr.utils.response.ResponseCode.USER_INVALID_ACCOUNT;
@Controller
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/account/login")
@ResponseBody
public BaseResponse login(@RequestBody User user, HttpServletRequest request) {
String username = user.getUsername();
String password = user.getPassword();
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
return ResponseUtil.badArgument();
}
return login(request, username, password);
}
@NotNull
private BaseResponse login(HttpServletRequest request, String username, String password) {
User user;
Subject currentUser = SecurityUtils.getSubject();
try {
currentUser.login(new UsernamePasswordToken(username, password));
} catch (UnknownAccountException uae) {
return ResponseUtil.fail(USER_INVALID_ACCOUNT, "用户帐号或密码不正确");
} catch (LockedAccountException lae) {
return ResponseUtil.fail(USER_INVALID_ACCOUNT, "用户帐号已锁定不可用");
} catch (AuthenticationException ae) {
return ResponseUtil.fail(USER_INVALID_ACCOUNT, "认证失败");
}
user = (User) currentUser.getPrincipal();
user.setLastLoginIp(IpUtil.getIpAddr(request));
user.setLastLoginTime(System.currentTimeMillis());
userService.updateById(user);
return ResponseUtil.ok();
}
@PostMapping("/account/register")
@ResponseBody
public BaseResponse register(@RequestBody User user, HttpServletRequest request) {
String username = user.getUsername();
String password = user.getPassword();
if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
return ResponseUtil.badArgument();
}
user = this.userService.createUser(username, password);
return login(request, username, password);
}
@GetMapping("/account/logout")
@ResponseBody
public BaseResponse logout() {
Subject currentUser = SecurityUtils.getSubject();
currentUser.logout();
return ResponseUtil.ok();
}
@GetMapping("/account/signin")
public String signin(HttpServletRequest request) {
return "signin";
}
@GetMapping("/account/signup")
public String signup(HttpServletRequest request) {
return "signup";
}
}
+6 -2
View File
@@ -4,11 +4,12 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.yzr.model.App;
import org.yzr.model.User;
public interface AppDao extends CrudRepository<App, String> {
@Query("select a from App a where a.bundleID=:bundleID and a.platform=:platform")
public App get(@Param("bundleID") String bundleID, @Param("platform") String platform);
@Query("select a from App a where a.bundleID=:bundleID and a.platform=:platform and a.owner=:owner")
public App getByBundleIDAndPlatformAndOwner(@Param("bundleID") String bundleID, @Param("platform") String platform, @Param("owner") User owner);
@Query("select a from App a where a.shortCode=:shortCode")
public App findByShortCode(@Param("shortCode") String shortCode);
@@ -16,4 +17,7 @@ public interface AppDao extends CrudRepository<App, String> {
@Override
@Query("select a from App a order by a.currentPackage.createTime desc ")
Iterable<App> findAll();
@Query("select a from App a where a.owner=:user order by a.currentPackage.createTime desc ")
Iterable<App> findByUser(@Param("user") User user);
}
@@ -0,0 +1,9 @@
package org.yzr.dao;
import org.springframework.data.repository.CrudRepository;
import org.yzr.model.Permission;
import org.yzr.model.User;
public interface PermissionDao extends CrudRepository<Permission, String> {
}
+11
View File
@@ -0,0 +1,11 @@
package org.yzr.dao;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.yzr.model.Role;
public interface RoleDao extends CrudRepository<Role, String> {
@Query("select r from Role r where r.name=:name")
Role findByName(@Param("name") String name);
}
+12
View File
@@ -0,0 +1,12 @@
package org.yzr.dao;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.yzr.model.Storage;
public interface StorageDao extends CrudRepository<Storage, String> {
@Query("select s from Storage s where s.key=:key")
public Storage findByKey(@Param("key") String key);
}
+22
View File
@@ -0,0 +1,22 @@
package org.yzr.dao;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.yzr.model.User;
public interface UserDao extends CrudRepository<User, String> {
@Query("select u from User u where u.username=:username and u.password=:password")
public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
@Query("select u from User u where u.username=:username")
public User findByUsername(@Param("username") String username);
@Override
@Query("select u from User u order by u.createTime desc ")
Iterable<User> findAll();
@Query("select u from User u where u.token=:token")
User findByToken(@Param("token") String token);
}
+18 -3
View File
@@ -4,10 +4,11 @@ package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "tb_app", uniqueConstraints = {@UniqueConstraint(columnNames={"platform", "bundleID"})})
@Table(name = "tb_app", uniqueConstraints = {@UniqueConstraint(columnNames = {"platform", "bundleID", "userId"})})
public class App {
// 主键
@Id
@@ -36,8 +37,11 @@ public class App {
private List<WebHook> webHookList;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// 当前包
@JoinColumn(name = "currentID",referencedColumnName = "id")
private Package currentPackage;
@JoinColumn(name = "currentID", referencedColumnName = "id")
private Package currentPackage;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User owner;
public String getId() {
return id;
@@ -96,6 +100,9 @@ public class App {
}
public List<Package> getPackageList() {
if (packageList == null) {
this.packageList = new ArrayList<>();
}
return packageList;
}
@@ -118,4 +125,12 @@ public class App {
public void setCurrentPackage(Package currentPackage) {
this.currentPackage = currentPackage;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
+6 -4
View File
@@ -6,7 +6,7 @@ import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name="tb_package")
@Table(name = "tb_package")
public class Package {
// 主键
@Id
@@ -34,13 +34,15 @@ public class Package {
private String extra;
// 文件名
private String fileName;
private Storage sourceFile;
private Storage iconFile;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name="appId")
@JoinColumn(name = "appId")
private App app;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// Provision 文件
@JoinColumn(name = "provisionId",referencedColumnName = "id")
private Provision provision;
@JoinColumn(name = "provisionId", referencedColumnName = "id")
private Provision provision;
public String getId() {
return id;
@@ -0,0 +1,64 @@
package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name = "tb_perm")
public class Permission {
// 主键
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
private String id;
@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
@JoinColumn(name = "roleId")
private Role role;
private String permission;
private long createTime;
private long updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
}
+8 -8
View File
@@ -3,11 +3,11 @@ package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name="tb_provision")
@Table(name = "tb_provision")
public class Provision {
// 主键
@Id
@@ -17,8 +17,8 @@ public class Provision {
private String id;
private String teamName;
private String teamID;
private Date createDate;
private Date expirationDate;
private long createDate;
private long expirationDate;
private String UUID;
@Column(length = 80000)
private String[] devices;
@@ -50,19 +50,19 @@ public class Provision {
this.teamID = teamID;
}
public Date getCreateDate() {
public long getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
public void setCreateDate(long createDate) {
this.createDate = createDate;
}
public Date getExpirationDate() {
public long getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
public void setExpirationDate(long expirationDate) {
this.expirationDate = expirationDate;
}
+97
View File
@@ -0,0 +1,97 @@
package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "tb_role")
public class Role {
// 主键
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
private String id;
// 角色名
private String name;
// 描述
private String description;
// 是否启用
private Boolean enabled;
// 创建时间
private long createTime;
// 更新时间
private long updateTime;
// 权限列表
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "role")
private List<Permission> permissionList;
@ManyToMany(targetEntity = User.class, mappedBy = "roleList", cascade = CascadeType.PERSIST) //让Usert维护外键表
private List<User> userList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public List<Permission> getPermissionList() {
return permissionList;
}
public void setPermissionList(List<Permission> permissionList) {
this.permissionList = permissionList;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
+98
View File
@@ -0,0 +1,98 @@
package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name = "tb_storage")
public class Storage {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
private String id;
@Column(name = "key_")
private String key;
@Column(name = "name_")
private String name;
private String type;
private Integer size;
private String url;
private long createTime;
private long updateTime;
private Boolean deleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
}
+147
View File
@@ -0,0 +1,147 @@
package org.yzr.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "tb_user")
public class User {
// 主键
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length = 32)
private String id;
// 用户名
@Column(unique = true)
private String username;
// 密码
private String password;
// token用于上传,用户名和密码的组合签名
@Column(length = 32)
private String token;
// 最近登录ip
private String lastLoginIp;
// 最近登录时间
private long lastLoginTime;
// 头像
private String avatar;
// 创建时间
private long createTime;
// 更新时间
private long updateTime;
// 角色
// 使用JoinTable来描述中间表,并描述中间表中外键与User,Role的映射关系
// joinColumns它是用来描述User与中间表中的映射关系
// inverseJoinColumns它是用来描述Role与中间表中的映射关系
@ManyToMany(targetEntity = Role.class)
@JoinTable(name = "tb_u_r",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")}
)
private Set<Role> roleList;
// 状态
private Boolean enable;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "owner")
private Set<App> appList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
public long getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(long lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public Set<Role> getRoleList() {
return roleList;
}
public void setRoleList(Set<Role> roleList) {
this.roleList = roleList;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public Set<App> getAppList() {
return appList;
}
public void setAppList(Set<App> appList) {
this.appList = appList;
}
}
+45 -23
View File
@@ -1,20 +1,20 @@
package org.yzr.service;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.yzr.dao.AppDao;
import org.yzr.dao.PackageDao;
import org.yzr.dao.UserDao;
import org.yzr.model.App;
import org.yzr.model.Package;
import org.yzr.utils.CodeGenerator;
import org.yzr.utils.PathManager;
import org.yzr.model.User;
import org.yzr.utils.CharUtil;
import org.yzr.utils.file.PathManager;
import org.yzr.vo.AppViewModel;
import org.yzr.vo.PackageViewModel;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -24,19 +24,25 @@ public class AppService {
@Resource
private AppDao appDao;
@Resource
private UserDao userDao;
@Resource
private PackageDao packageDao;
@Resource
private PathManager pathManager;
@Transactional
public App save(App app) {
App app1 = this.appDao.save(app);
app1.getCurrentPackage();
public App save(App app, User user) {
user = this.userDao.findById(user.getId()).get();
app.setOwner(user);
app = this.appDao.save(app);
app.getCurrentPackage();
try {
// 触发级联查询
app1.getWebHookList().forEach(webHook -> {});
app.getWebHookList().forEach(webHook -> {
});
} catch (Exception e) {
e.printStackTrace();
}
return app1;
return app;
}
@Transactional
@@ -55,7 +61,8 @@ public class AppService {
Optional<App> optionalApp = this.appDao.findById(appID);
App app = optionalApp.get();
if (app != null) {
app.getPackageList().forEach(aPackage -> {});
app.getPackageList().forEach(aPackage -> {
});
AppViewModel appViewModel = new AppViewModel(app, this.pathManager, true);
return appViewModel;
}
@@ -63,25 +70,29 @@ public class AppService {
}
@Transactional
public App getByPackage(Package aPackage) {
App app = this.appDao.get(aPackage.getBundleID(), aPackage.getPlatform());
public App savePackage(Package aPackage, User user) {
aPackage = this.packageDao.save(aPackage);
user = this.userDao.findByUsername(user.getUsername());
App app = this.appDao.getByBundleIDAndPlatformAndOwner(aPackage.getBundleID(), aPackage.getPlatform(), user);
if (app == null) {
app = new App();
String shortCode = CodeGenerator.generate(4);
String shortCode = CharUtil.generate(4);
while (this.appDao.findByShortCode(shortCode) != null) {
shortCode = CodeGenerator.generate(4);
shortCode = CharUtil.generate(4);
}
BeanUtils.copyProperties(aPackage, app);
app.setShortCode(shortCode);
app.setOwner(user);
} else {
app.setName(aPackage.getName());
// 触发级联查询
app.getPackageList().forEach(p->{});
// 级联查询
app.getPackageList().forEach(aPackage1 -> {
});
app.getWebHookList().forEach(webHook -> {});
}
if (app.getPackageList() == null) {
app.setPackageList(new ArrayList<>());
}
app.setName(aPackage.getName());
app.getPackageList().add(aPackage);
app.setCurrentPackage(aPackage);
app = this.appDao.save(app);
return app;
}
@@ -94,11 +105,11 @@ public class AppService {
String path = PathManager.getAppPath(app);
PathManager.deleteDirectory(path);
}
}
/**
* 通过 code 和 packageId 查询
*
* @param code
* @param packageId
* @return
@@ -109,4 +120,15 @@ public class AppService {
AppViewModel viewModel = new AppViewModel(app, pathManager, packageId);
return viewModel;
}
@Transactional
public List<AppViewModel> findByUser(User user) {
Iterable<App> apps = this.appDao.findByUser(user);
List<AppViewModel> list = new ArrayList<>();
for (App app : apps) {
AppViewModel appViewModel = new AppViewModel(app, this.pathManager, false);
list.add(appViewModel);
}
return list;
}
}
@@ -5,9 +5,11 @@ import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.yzr.dao.PackageDao;
import org.yzr.model.App;
import org.yzr.model.Package;
import org.yzr.utils.ImageUtils;
import org.yzr.utils.PathManager;
import org.yzr.model.User;
import org.yzr.utils.file.PathManager;
import org.yzr.utils.image.ImageUtils;
import org.yzr.utils.parser.ParserClient;
import org.yzr.vo.PackageViewModel;
@@ -23,9 +25,13 @@ public class PackageService {
@Resource
private PathManager pathManager;
public Package buildPackage(String filePath) {
public Package buildPackage(String filePath, User user) throws ClassNotFoundException {
Package aPackage = ParserClient.parse(filePath);
try {
App app = new App();
app.setOwner(user);
aPackage.setApp(app);
String fileName = aPackage.getPlatform() + "." + FilenameUtils.getExtension(filePath);
// 更新文件名
aPackage.setFileName(fileName);
@@ -47,6 +53,7 @@ public class PackageService {
} catch (Exception e) {
e.printStackTrace();
}
aPackage.setApp(null);
return aPackage;
}
@@ -58,6 +65,8 @@ public class PackageService {
@Transactional
public Package get(String id) {
Package aPackage = this.packageDao.findById(id).get();
// 级联查询用户
aPackage.getApp().getOwner().getId();
return aPackage;
}
@@ -0,0 +1,20 @@
package org.yzr.service;
import org.springframework.stereotype.Service;
import org.yzr.dao.PermissionDao;
import org.yzr.model.Permission;
import javax.annotation.Resource;
import javax.transaction.Transactional;
@Service
public class PermissionService {
@Resource
private PermissionDao permissionDao;
@Transactional
public Permission save(Permission permission) {
return this.permissionDao.save(permission);
}
}
@@ -0,0 +1,21 @@
package org.yzr.service;
import org.springframework.stereotype.Service;
import org.yzr.dao.RoleDao;
import org.yzr.model.Role;
import javax.annotation.Resource;
import javax.transaction.Transactional;
@Service
public class RoleService {
@Resource
private RoleDao roleDao;
@Transactional
public Role save(Role role) {
return this.roleDao.save(role);
}
}
@@ -0,0 +1,25 @@
package org.yzr.service;
import org.springframework.stereotype.Service;
import org.yzr.dao.StorageDao;
import org.yzr.model.Storage;
import javax.annotation.Resource;
import javax.transaction.Transactional;
@Service
public class StorageService {
@Resource
private StorageDao storageDao;
@Transactional
public Storage save(Storage storage) {
return this.storageDao.save(storage);
}
@Transactional
public Storage findByKey(String key) {
return this.storageDao.findByKey(key);
}
}
@@ -0,0 +1,165 @@
package org.yzr.service;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yzr.dao.PermissionDao;
import org.yzr.dao.RoleDao;
import org.yzr.dao.UserDao;
import org.yzr.model.Permission;
import org.yzr.model.Role;
import org.yzr.model.User;
import org.yzr.utils.bcrypt.BCryptPasswordEncoder;
import org.yzr.utils.bcrypt.TokenManager;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class UserService {
@Resource
private UserDao userDao;
@Resource
private PermissionDao permissionDao;
@Resource
private RoleDao roleDao;
@Resource
private Environment environment;
@Transactional
public User save(User user) {
updateToken(user);
return this.userDao.save(user);
}
/**
* 更新token
*
* @param user
*/
private void updateToken(User user) {
String token = user.getToken();
User tokenUser = this.userDao.findByToken(token);
if (tokenUser == null) {
token = TokenManager.generateToken(user.getUsername(), user.getPassword());
} else {
if (!(user.getUsername().equals(tokenUser.getUsername())
&& user.getPassword().equals(tokenUser.getPassword()))) {
token = TokenManager.generateToken(user.getUsername(), user.getPassword());
}
}
user.setToken(token);
}
@Transactional
public List<User> findAll() {
Iterable<User> users = this.userDao.findAll();
List<User> list = new ArrayList<>();
for (User user : users) {
list.add(user);
}
return list;
}
@Transactional
public User login(String username, String password) {
User user = this.userDao.findByUsername(username);
if (user != null) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if (!encoder.matches(password, user.getPassword())) return null;
// 级联查询
user.getRoleList().forEach(role -> {
role.getPermissionList().forEach(permission -> {
});
});
}
return user;
}
@Transactional
public User findByToken(String token) {
if (StringUtils.isEmpty(token)) return null;
return this.userDao.findByToken(token);
}
@Transactional
public void deleteById(String id) {
User user = this.userDao.findById(id).get();
if (user != null) {
this.userDao.deleteById(id);
}
}
@Transactional
public void updateById(User user) {
this.userDao.save(user);
}
@Transactional
public User createUser(String username, String password) {
User user = new User();
user.setEnable(true);
user.setUsername(username);
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
user.setPassword(encoder.encode(password));
user.setCreateTime(System.currentTimeMillis());
Role role = this.roleDao.findByName("管理员");
Set<Role> roleList = new HashSet<>();
roleList.add(role);
user.setRoleList(roleList);
updateToken(user);
this.userDao.save(user);
return user;
}
@Transactional
public void initUsers() {
String username = environment.getProperty("admin.username");
String password = environment.getProperty("admin.password");
if (this.userDao.findByUsername(username) == null) {
long currentTime = System.currentTimeMillis();
Role role = new Role();
role.setCreateTime(currentTime);
role.setDescription("管理员");
role.setName("管理员");
role.setEnabled(true);
this.roleDao.save(role);
List<Permission> permissionList = new ArrayList<>();
String[] perms = new String[]{
"/apps",
"/apps/get",
// "/apps/delete",
"/packageList/get"
};
for (String string : perms) {
Permission permission = new Permission();
permission.setCreateTime(currentTime);
permission.setPermission(string);
permission.setUpdateTime(currentTime);
permission.setRole(role);
this.permissionDao.save(permission);
permissionList.add(permission);
}
User user = new User();
user.setEnable(true);
user.setUsername(username);
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
user.setPassword(encoder.encode(password));
user.setCreateTime(currentTime);
Set<Role> roleList = new HashSet<>();
roleList.add(role);
user.setRoleList(roleList);
updateToken(user);
this.userDao.save(user);
}
}
}
@@ -0,0 +1,81 @@
package org.yzr.shiro;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.yzr.model.Permission;
import org.yzr.model.Role;
import org.yzr.model.User;
import org.yzr.service.UserService;
import org.yzr.utils.bcrypt.BCryptPasswordEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class UserAuthorizingRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
if (principals == null) {
throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
}
User user = (User) getAvailablePrincipal(principals);
Set<String> roles = toRoles(user.getRoleList());
Set<String> permissions = toPermissions(user.getRoleList());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(roles);
info.setStringPermissions(permissions);
return info;
}
private Set<String> toRoles(Set<Role> roleList) {
Set<String> roles = new HashSet<>();
for (Role role : roleList) {
roles.add(role.getName());
}
return roles;
}
private Set<String> toPermissions(Set<Role> roleList) {
Set<String> permissions = new HashSet<>();
for (Role role : roleList) {
for (Permission permission : role.getPermissionList()) {
permissions.add(permission.getPermission());
}
}
return permissions;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
String password = new String(upToken.getPassword());
if (StringUtils.isEmpty(username)) {
throw new AccountException("用户名不能为空");
}
if (StringUtils.isEmpty(password)) {
throw new AccountException("密码不能为空");
}
User user = userService.login(username, password);
Assert.state(user != null, "用户名或密码错误");
if (user == null) {
throw new UnknownAccountException("用户名或密码错误");
}
return new SimpleAuthenticationInfo(user, password, getName());
}
}
@@ -0,0 +1,29 @@
package org.yzr.shiro;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
public class UserWebSessionManager extends DefaultWebSessionManager {
public static final String LOGIN_TOKEN_KEY = "token";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
String id = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY);
if (!StringUtils.isEmpty(id)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return id;
} else {
return super.getSessionId(request, response);
}
}
}
@@ -0,0 +1,130 @@
package org.yzr.storage;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;
public class AliyunStorage implements IStorage {
private final Log logger = LogFactory.getLog(AliyunStorage.class);
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* 获取阿里云OSS客户端对象
*
* @return ossClient
*/
private OSSClient getOSSClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
private String getBaseUrl() {
return "https://" + bucketName + "." + endpoint + "/";
}
/**
* 阿里云OSS对象存储简单上传实现
*/
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
try {
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(contentLength);
objectMetadata.setContentType(contentType);
// 对象键(Key)是对象在存储桶中的唯一标识。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
@Override
public Stream<Path> loadAll() {
return null;
}
@Override
public Path load(String keyName) {
return null;
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(getBaseUrl() + keyName);
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public void delete(String keyName) {
try {
getOSSClient().deleteObject(bucketName, keyName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public String generateUrl(String keyName) {
return getBaseUrl() + keyName;
}
}
@@ -0,0 +1,33 @@
package org.yzr.storage;
import org.springframework.core.io.Resource;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* 对象存储接口
*/
public interface IStorage {
/**
* 存储一个文件对象
*
* @param inputStream 文件输入流
* @param contentLength 文件长度
* @param contentType 文件类型
* @param keyName 文件名
*/
void store(InputStream inputStream, long contentLength, String contentType, String keyName);
Stream<Path> loadAll();
Path load(String keyName);
Resource loadAsResource(String keyName);
void delete(String keyName);
String generateUrl(String keyName);
}
@@ -0,0 +1,110 @@
package org.yzr.storage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
/**
* 服务器本地对象存储服务
*/
public class LocalStorage implements IStorage {
private final Log logger = LogFactory.getLog(LocalStorage.class);
private String storagePath;
private String address;
private Path rootLocation;
public String getStoragePath() {
return storagePath;
}
public void setStoragePath(String storagePath) {
this.storagePath = storagePath;
this.rootLocation = Paths.get(storagePath);
try {
Files.createDirectories(rootLocation);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
try {
Files.copy(inputStream, rootLocation.resolve(keyName), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Failed to store file " + keyName, e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(rootLocation, 1)
.filter(path -> !path.equals(rootLocation))
.map(path -> rootLocation.relativize(path));
} catch (IOException e) {
throw new RuntimeException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public void delete(String filename) {
Path file = load(filename);
try {
Files.delete(file);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
@Override
public String generateUrl(String keyName) {
return address + keyName;
}
}
@@ -0,0 +1,125 @@
package org.yzr.storage;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;
public class QiniuStorage implements IStorage {
private final Log logger = LogFactory.getLog(QiniuStorage.class);
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
private Auth auth;
private UploadManager uploadManager;
private BucketManager bucketManager;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* 七牛云OSS对象存储简单上传实现
*/
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
if (uploadManager == null) {
if (auth == null) {
auth = Auth.create(accessKey, secretKey);
}
uploadManager = new UploadManager(new Configuration());
}
try {
String upToken = auth.uploadToken(bucketName);
uploadManager.put(inputStream, keyName, upToken, null, contentType);
} catch (QiniuException ex) {
logger.error(ex.getMessage(), ex);
}
}
@Override
public Stream<Path> loadAll() {
return null;
}
@Override
public Path load(String keyName) {
return null;
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(generateUrl(keyName));
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
return null;
}
@Override
public void delete(String keyName) {
if (bucketManager == null) {
if (auth == null) {
auth = Auth.create(accessKey, secretKey);
}
bucketManager = new BucketManager(auth, new Configuration());
}
try {
bucketManager.delete(bucketName, keyName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public String generateUrl(String keyName) {
return endpoint + "/" + keyName;
}
}
@@ -0,0 +1,96 @@
package org.yzr.storage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.yzr.model.Storage;
import org.yzr.utils.CharUtil;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* 提供存储服务类,所有存储服务均由该类对外提供
*/
public class StorageUtil {
private String active;
private IStorage storage;
@Autowired
private org.yzr.service.StorageService storageService;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public IStorage getStorage() {
return storage;
}
public void setStorage(IStorage storage) {
this.storage = storage;
}
/**
* 存储一个文件对象
*
* @param inputStream 文件输入流
* @param contentLength 文件长度
* @param contentType 文件类型
* @param fileName 文件索引名
*/
public Storage store(InputStream inputStream, long contentLength, String contentType, String fileName) {
String key = generateKey(fileName);
storage.store(inputStream, contentLength, contentType, key);
String url = generateUrl(key);
Storage storageInfo = new Storage();
storageInfo.setName(fileName);
storageInfo.setSize((int) contentLength);
storageInfo.setType(contentType);
storageInfo.setKey(key);
storageInfo.setUrl(url);
this.storageService.save(storageInfo);
return storageInfo;
}
private String generateKey(String originalFilename) {
int index = originalFilename.lastIndexOf('.');
String suffix = originalFilename.substring(index);
String key = null;
Storage storageInfo = null;
do {
key = CharUtil.generate(20) + suffix;
storageInfo = this.storageService.findByKey(key);
}
while (storageInfo != null);
return key;
}
public Stream<Path> loadAll() {
return storage.loadAll();
}
public Path load(String keyName) {
return storage.load(keyName);
}
public Resource loadAsResource(String keyName) {
return storage.loadAsResource(keyName);
}
public void delete(String keyName) {
storage.delete(keyName);
}
private String generateUrl(String keyName) {
return storage.generateUrl(keyName);
}
}
@@ -0,0 +1,137 @@
package org.yzr.storage;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* 腾讯对象存储服务
*/
public class TencentStorage implements IStorage {
private final Log logger = LogFactory.getLog(TencentStorage.class);
private String secretId;
private String secretKey;
private String region;
private String bucketName;
private COSClient cosClient;
public String getSecretId() {
return secretId;
}
public void setSecretId(String secretId) {
this.secretId = secretId;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
private COSClient getCOSClient() {
if (cosClient == null) {
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
cosClient = new COSClient(cred, clientConfig);
}
return cosClient;
}
private String getBaseUrl() {
return "https://" + bucketName + ".cos." + region + ".myqcloud.com/";
}
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
try {
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(contentLength);
objectMetadata.setContentType(contentType);
// 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg`
// 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
getCOSClient().putObject(putObjectRequest);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
@Override
public Stream<Path> loadAll() {
return null;
}
@Override
public Path load(String keyName) {
return null;
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(getBaseUrl() + keyName);
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
return null;
}
@Override
public void delete(String keyName) {
try {
getCOSClient().deleteObject(bucketName, keyName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@Override
public String generateUrl(String keyName) {
return getBaseUrl() + keyName;
}
}
@@ -0,0 +1,79 @@
package org.yzr.storage.config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.yzr.storage.*;
@Configuration
@EnableConfigurationProperties(StorageProperties.class)
public class StorageAutoConfiguration {
private final StorageProperties properties;
public StorageAutoConfiguration(StorageProperties properties) {
this.properties = properties;
}
@Bean
public StorageUtil StorageUtil() {
StorageUtil StorageUtil = new StorageUtil();
String active = this.properties.getActive();
StorageUtil.setActive(active);
if (active.equals("local")) {
StorageUtil.setStorage(localStorage());
} else if (active.equals("aliyun")) {
StorageUtil.setStorage(aliyunStorage());
} else if (active.equals("tencent")) {
StorageUtil.setStorage(tencentStorage());
} else if (active.equals("qiniu")) {
StorageUtil.setStorage(qiniuStorage());
} else {
throw new RuntimeException("当前存储模式 " + active + " 不支持");
}
return StorageUtil;
}
@Bean
public LocalStorage localStorage() {
LocalStorage localStorage = new LocalStorage();
StorageProperties.Local local = this.properties.getLocal();
localStorage.setAddress(local.getAddress());
localStorage.setStoragePath(local.getStoragePath());
return localStorage;
}
@Bean
public AliyunStorage aliyunStorage() {
AliyunStorage aliyunStorage = new AliyunStorage();
StorageProperties.Aliyun aliyun = this.properties.getAliyun();
aliyunStorage.setAccessKeyId(aliyun.getAccessKeyId());
aliyunStorage.setAccessKeySecret(aliyun.getAccessKeySecret());
aliyunStorage.setBucketName(aliyun.getBucketName());
aliyunStorage.setEndpoint(aliyun.getEndpoint());
return aliyunStorage;
}
@Bean
public TencentStorage tencentStorage() {
TencentStorage tencentStorage = new TencentStorage();
StorageProperties.Tencent tencent = this.properties.getTencent();
tencentStorage.setSecretId(tencent.getSecretId());
tencentStorage.setSecretKey(tencent.getSecretKey());
tencentStorage.setBucketName(tencent.getBucketName());
tencentStorage.setRegion(tencent.getRegion());
return tencentStorage;
}
@Bean
public QiniuStorage qiniuStorage() {
QiniuStorage qiniuStorage = new QiniuStorage();
StorageProperties.Qiniu qiniu = this.properties.getQiniu();
qiniuStorage.setAccessKey(qiniu.getAccessKey());
qiniuStorage.setSecretKey(qiniu.getSecretKey());
qiniuStorage.setBucketName(qiniu.getBucketName());
qiniuStorage.setEndpoint(qiniu.getEndpoint());
return qiniuStorage;
}
}
+190
View File
@@ -0,0 +1,190 @@
package org.yzr.storage.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "storage")
public class StorageProperties {
private String active;
private Local local;
private Aliyun aliyun;
private Tencent tencent;
private Qiniu qiniu;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public Local getLocal() {
return local;
}
public void setLocal(Local local) {
this.local = local;
}
public Aliyun getAliyun() {
return aliyun;
}
public void setAliyun(Aliyun aliyun) {
this.aliyun = aliyun;
}
public Tencent getTencent() {
return tencent;
}
public void setTencent(Tencent tencent) {
this.tencent = tencent;
}
public Qiniu getQiniu() {
return qiniu;
}
public void setQiniu(Qiniu qiniu) {
this.qiniu = qiniu;
}
public static class Local {
private String address;
private String storagePath;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStoragePath() {
return storagePath;
}
public void setStoragePath(String storagePath) {
this.storagePath = storagePath;
}
}
public static class Tencent {
private String secretId;
private String secretKey;
private String region;
private String bucketName;
public String getSecretId() {
return secretId;
}
public void setSecretId(String secretId) {
this.secretId = secretId;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
}
public static class Aliyun {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
}
public static class Qiniu {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
}
}
@@ -2,7 +2,7 @@ package org.yzr.utils;
import java.util.Random;
public class CodeGenerator {
public class CharUtil {
// 所有编码
private static final String ALL_CODE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
// 随机种子
+53
View File
@@ -0,0 +1,53 @@
package org.yzr.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* IP地址相关工具类
*/
public class IpUtil {
private static final Log logger = LogFactory.getLog(IpUtil.class);
public static String getIpAddr(HttpServletRequest request) {
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
logger.error(e.getMessage(), e);
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
}
@@ -0,0 +1,633 @@
package org.yzr.utils.bcrypt;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
public class BCrypt {
// BCrypt parameters
static final int MIN_LOG_ROUNDS = 4;
static final int MAX_LOG_ROUNDS = 31;
private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private static final int BCRYPT_SALT_LEN = 16;
// Blowfish parameters
private static final int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule
private static final int P_orig[] = {0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b};
private static final int S_orig[] = {0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7,
0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5,
0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27,
0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993,
0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af,
0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5,
0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68,
0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4,
0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248,
0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4,
0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd,
0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc,
0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0,
0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8,
0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01,
0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64,
0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8,
0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86,
0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e,
0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a,
0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6,
0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7,
0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546,
0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941,
0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c,
0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856,
0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87,
0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70,
0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1,
0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1,
0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa,
0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37,
0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24,
0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7,
0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f,
0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71,
0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74,
0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0,
0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df,
0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641,
0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de,
0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5,
0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212,
0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315,
0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d,
0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6,
0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da,
0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d,
0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc,
0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2,
0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8,
0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46,
0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40,
0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e,
0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d,
0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b,
0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667,
0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb,
0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df,
0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891,
0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5,
0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00,
0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76,
0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0,
0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6};
// bcrypt IV: "OrpheanBeholderScryDoubt"
static private final int bf_crypt_ciphertext[] = {0x4f727068, 0x65616e42,
0x65686f6c, 0x64657253, 0x63727944, 0x6f756274};
// Table for Base64 encoding
static private final char base64_code[] = {'.', '/', 'A', 'B', 'C', 'D', 'E', 'F',
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
// Table for Base64 decoding
static private final byte index_64[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1};
// Expanded Blowfish key
private int P[];
private int S[];
/**
* Encode a byte array using bcrypt's slightly-modified base64 encoding scheme. Note
* that this is <strong>not</strong> compatible with the standard MIME-base64
* encoding.
*
* @param d the byte array to encode
* @param len the number of bytes to encode
* @param rs the destination buffer for the base64-encoded string
* @throws IllegalArgumentException if the length is invalid
*/
static void encode_base64(byte d[], int len, StringBuilder rs)
throws IllegalArgumentException {
int off = 0;
int c1, c2;
if (len <= 0 || len > d.length) {
throw new IllegalArgumentException("Invalid len");
}
while (off < len) {
c1 = d[off++] & 0xff;
rs.append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.append(base64_code[c1 & 0x3f]);
rs.append(base64_code[c2 & 0x3f]);
}
}
/**
* Look up the 3 bits base64-encoded by the specified character, range-checking
* against conversion table
*
* @param x the base64-encoded value
* @return the decoded value of x
*/
private static byte char64(char x) {
if (x > index_64.length) {
return -1;
}
return index_64[x];
}
/**
* Decode a string encoded using bcrypt's base64 scheme to a byte array. Note that
* this is *not* compatible with the standard MIME-base64 encoding.
*
* @param s the string to decode
* @param maxolen the maximum number of bytes to decode
* @return an array containing the decoded bytes
* @throws IllegalArgumentException if maxolen is invalid
*/
static byte[] decode_base64(String s, int maxolen) throws IllegalArgumentException {
ByteArrayOutputStream out = new ByteArrayOutputStream(maxolen);
int off = 0, slen = s.length(), olen = 0;
byte c1, c2, c3, c4, o;
if (maxolen <= 0) {
throw new IllegalArgumentException("Invalid maxolen");
}
while (off < slen - 1 && olen < maxolen) {
c1 = char64(s.charAt(off++));
c2 = char64(s.charAt(off++));
if (c1 == -1 || c2 == -1) {
break;
}
o = (byte) (c1 << 2);
o |= (c2 & 0x30) >> 4;
out.write(o);
if (++olen >= maxolen || off >= slen) {
break;
}
c3 = char64(s.charAt(off++));
if (c3 == -1) {
break;
}
o = (byte) ((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2;
out.write(o);
if (++olen >= maxolen || off >= slen) {
break;
}
c4 = char64(s.charAt(off++));
o = (byte) ((c3 & 0x03) << 6);
o |= c4;
out.write(o);
++olen;
}
return out.toByteArray();
}
/**
* Cycically extract a word of key material
*
* @param data the string to extract the data from
* @param offp a "pointer" (as a one-entry array) to the current offset into data
* @return the next word of material from data
*/
private static int streamtoword(byte data[], int offp[]) {
int i;
int word = 0;
int off = offp[0];
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
offp[0] = off;
return word;
}
static long roundsForLogRounds(int log_rounds) {
if (log_rounds < 4 || log_rounds > 31) {
throw new IllegalArgumentException("Bad number of rounds");
}
return 1L << log_rounds;
}
/**
* Hash a password using the OpenBSD bcrypt scheme
*
* @param password the password to hash
* @param salt the salt to hash with (perhaps generated using BCrypt.gensalt)
* @return the hashed password
* @throws IllegalArgumentException if invalid salt is passed
*/
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
throw new IllegalArgumentException("salt cannot be null");
}
int saltLength = salt.length();
if (saltLength < 28) {
throw new IllegalArgumentException("Invalid salt");
}
if (salt.charAt(0) != '$' || salt.charAt(1) != '2') {
throw new IllegalArgumentException("Invalid salt version");
}
if (salt.charAt(2) == '$') {
off = 3;
} else {
minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$') {
throw new IllegalArgumentException("Invalid salt revision");
}
off = 4;
}
if (saltLength - off < 25) {
throw new IllegalArgumentException("Invalid salt");
}
// Extract number of rounds
if (salt.charAt(off + 2) > '$') {
throw new IllegalArgumentException("Missing salt rounds");
}
rounds = Integer.parseInt(salt.substring(off, off + 2));
real_salt = salt.substring(off + 3, off + 25);
try {
passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF-8 is not supported");
}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCrypt();
hashed = B.crypt_raw(passwordb, saltb, rounds);
rs.append("$2");
if (minor >= 'a') {
rs.append(minor);
}
rs.append("$");
if (rounds < 10) {
rs.append("0");
}
rs.append(rounds);
rs.append("$");
encode_base64(saltb, saltb.length, rs);
encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs);
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
*
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds. Minimum 4, maximum 31.
* @param random an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
if (log_rounds < MIN_LOG_ROUNDS || log_rounds > MAX_LOG_ROUNDS) {
throw new IllegalArgumentException("Bad number of rounds");
}
StringBuilder rs = new StringBuilder();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10) {
rs.append("0");
}
rs.append(log_rounds);
rs.append("$");
encode_base64(rnd, rnd.length, rs);
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
*
* @param log_rounds the log2 of the number of rounds of hashing to apply - the work
* factor therefore increases as 2**log_rounds. Minimum 4, maximum 31.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
return gensalt(log_rounds, new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method, selecting a reasonable
* default for the number of hashing rounds to apply
*
* @return an encoded salt value
*/
public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Check that a plaintext password matches a previously hashed one
*
* @param plaintext the plaintext password to verify
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
return equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed));
}
static boolean equalsNoEarlyReturn(String a, String b) {
char[] caa = a.toCharArray();
char[] cab = b.toCharArray();
if (caa.length != cab.length) {
return false;
}
byte ret = 0;
for (int i = 0; i < caa.length; i++) {
ret |= caa[i] ^ cab[i];
}
return ret == 0;
}
/**
* Blowfish encipher a single 64-bit block encoded as two 32-bit halves
*
* @param lr an array containing the two 32-bit half blocks
* @param off the position in the array of the blocks
*/
private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2; ) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
n ^= S[0x200 | ((l >> 8) & 0xff)];
n += S[0x300 | (l & 0xff)];
r ^= n ^ P[++i];
// Feistel substitution on right word
n = S[(r >> 24) & 0xff];
n += S[0x100 | ((r >> 16) & 0xff)];
n ^= S[0x200 | ((r >> 8) & 0xff)];
n += S[0x300 | (r & 0xff)];
l ^= n ^ P[++i];
}
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
}
/**
* Initialise the Blowfish key schedule
*/
private void init_key() {
P = (int[]) P_orig.clone();
S = (int[]) S_orig.clone();
}
/**
* Key the Blowfish cipher
*
* @param key an array containing the key
*/
private void key(byte key[]) {
int i;
int koffp[] = {0};
int lr[] = {0, 0};
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++) {
P[i] = P[i] ^ streamtoword(key, koffp);
}
for (i = 0; i < plen; i += 2) {
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Perform the "enhanced key schedule" step described by Provos and Mazieres in
* "A Future-Adaptable Password Scheme" http://www.openbsd.org/papers/bcrypt-paper.ps
*
* @param data salt information
* @param key password information
*/
private void ekskey(byte data[], byte key[]) {
int i;
int koffp[] = {0}, doffp[] = {0};
int lr[] = {0, 0};
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++) {
P[i] = P[i] ^ streamtoword(key, koffp);
}
for (i = 0; i < plen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Perform the central password hashing step in the bcrypt scheme
*
* @param password the password to hash
* @param salt the binary salt to hash with the password
* @param log_rounds the binary logarithm of the number of rounds of hashing to apply
* @return an array containing the binary hashed password
*/
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) {
int cdata[] = (int[]) bf_crypt_ciphertext.clone();
int clen = cdata.length;
byte ret[];
long rounds = roundsForLogRounds(log_rounds);
init_key();
ekskey(salt, password);
for (long i = 0; i < rounds; i++) {
key(password);
key(salt);
}
for (int i = 0; i < 64; i++) {
for (int j = 0; j < (clen >> 1); j++) {
encipher(cdata, j << 1);
}
}
ret = new byte[clen * 4];
for (int i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte) ((cdata[i] >> 24) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 16) & 0xff);
ret[j++] = (byte) ((cdata[i] >> 8) & 0xff);
ret[j++] = (byte) (cdata[i] & 0xff);
}
return ret;
}
}
@@ -0,0 +1,60 @@
package org.yzr.utils.bcrypt;
import java.security.SecureRandom;
import java.util.regex.Pattern;
public class BCryptPasswordEncoder {
private final int strength;
private final SecureRandom random;
private Pattern BCRYPT_PATTERN = Pattern
.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
public BCryptPasswordEncoder() {
this(-1);
}
/**
* @param strength the log rounds to use, between 4 and 31
*/
public BCryptPasswordEncoder(int strength) {
this(strength, null);
}
/**
* @param strength the log rounds to use, between 4 and 31
* @param random the secure random instance to use
*/
public BCryptPasswordEncoder(int strength, SecureRandom random) {
if (strength != -1 && (strength < BCrypt.MIN_LOG_ROUNDS || strength > BCrypt.MAX_LOG_ROUNDS)) {
throw new IllegalArgumentException("Bad strength");
}
this.strength = strength;
this.random = random;
}
public String encode(CharSequence rawPassword) {
String salt;
if (strength > 0) {
if (random != null) {
salt = BCrypt.gensalt(strength, random);
} else {
salt = BCrypt.gensalt(strength);
}
} else {
salt = BCrypt.gensalt();
}
return BCrypt.hashpw(rawPassword.toString(), salt);
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword == null || encodedPassword.length() == 0) {
return false;
}
if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
return false;
}
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
}
@@ -0,0 +1,21 @@
package org.yzr.utils.bcrypt;
import com.qcloud.cos.utils.Md5Utils;
public class TokenManager {
// 秘钥
static final String SECRET = "X-app-manager-Token";
/**
* 生成token
*
* @param username 用户名
* @param password 密码
* @return
*/
public static String generateToken(String username, String password) {
return Md5Utils.md5Hex(username + "&&" + password + "&&" + SECRET);
}
}
@@ -0,0 +1,46 @@
package org.yzr.utils.date;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtil {
/**
* 获取毫秒时间戳
*
* @param date
* @return
*/
public static long getTimeMillis(Date date) {
return date.getTime();
}
public static Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second) {
if (date == null) {
date = new Date();
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
if (year != 0) {
cal.add(Calendar.YEAR, year);
}
if (month != 0) {
cal.add(Calendar.MONTH, month);
}
if (day != 0) {
cal.add(Calendar.DATE, day);
}
if (hour != 0) {
cal.add(Calendar.HOUR_OF_DAY, hour);
}
if (minute != 0) {
cal.add(Calendar.MINUTE, minute);
}
if (second != 0) {
cal.add(Calendar.SECOND, second);
}
return cal.getTime();
}
}
@@ -0,0 +1,158 @@
package org.yzr.utils.file;
public enum FileType {
/**
* JPEG
*/
JPEG("FFD8FF"),
/**
* PNG
*/
PNG("89504E47"),
/**
* GIF
*/
GIF("47494638"),
/**
* TIFF
*/
TIFF("49492A00"),
/**
* Windows bitmap
*/
BMP("424D"),
/**
* CAD
*/
DWG("41433130"),
/**
* Adobe photoshop
*/
PSD("38425053"),
/**
* Rich Text Format
*/
RTF("7B5C727466"),
/**
* XML
*/
XML("3C3F786D6C"),
/**
* HTML
*/
HTML("68746D6C3E"),
/**
* Outlook Express
*/
DBX("CFAD12FEC5FD746F "),
/**
* Outlook
*/
PST("2142444E"),
/**
* doc;xls;dot;ppt;xla;ppa;pps;pot;msi;sdw;db
*/
OLE2("0xD0CF11E0A1B11AE1"),
/**
* Microsoft Word/Excel
*/
XLS_DOC("D0CF11E0"),
/**
* Microsoft Access
*/
MDB("5374616E64617264204A"),
/**
* Word Perfect
*/
WPB("FF575043"),
/**
* Postscript
*/
EPS_PS("252150532D41646F6265"),
/**
* Adobe Acrobat
*/
PDF("255044462D312E"),
/**
* Windows Password
*/
PWL("E3828596"),
/**
* ZIP Archive
*/
ZIP("504B0304"),
/**
* ARAR Archive
*/
RAR("52617221"),
/**
* WAVE
*/
WAV("57415645"),
/**
* AVI
*/
AVI("41564920"),
/**
* Real Audio
*/
RAM("2E7261FD"),
/**
* Real Media
*/
RM("2E524D46"),
/**
* Quicktime
*/
MOV("6D6F6F76"),
/**
* Windows Media
*/
ASF("3026B2758E66CF11"),
/**
* MIDI
*/
MID("4D546864");
private String value = "";
private FileType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,65 @@
package org.yzr.utils.file;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileUtil {
/**
* 判断文件类型
*/
public static FileType getType(String filePath) throws IOException {
// 获取文件头
String fileHead = getFileHeader(filePath);
if (fileHead != null && fileHead.length() > 0) {
fileHead = fileHead.toUpperCase();
FileType[] fileTypes = FileType.values();
for (FileType type : fileTypes) {
if (fileHead.startsWith(type.getValue())) {
return type;
}
}
}
return null;
}
/**
* 读取文件头
*/
private static String getFileHeader(String filePath) throws IOException {
byte[] b = new byte[28];
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
inputStream.read(b, 0, 28);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return bytesToHex(b);
}
/**
* 将字节数组转换成16进制字符串
*/
private static String bytesToHex(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}
@@ -1,10 +1,6 @@
package org.yzr.utils;
package org.yzr.utils.file;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.net.InetAddress;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
@@ -12,6 +8,8 @@ import org.yzr.model.App;
import org.yzr.model.Package;
import javax.annotation.Resource;
import java.io.File;
import java.net.InetAddress;
@Component
public class PathManager {
@@ -21,8 +19,100 @@ public class PathManager {
private String httpsBaseURL;
private String httpBaseURL;
/**
* 获取图标的临时路径
*
* @param aPackage
* @return
*/
public static String getTempIconPath(Package aPackage) {
if (aPackage == null) return null;
StringBuilder path = new StringBuilder();
path.append(FileUtils.getTempDirectoryPath()).append(File.separator).append(aPackage.getPlatform());
path.append(File.separator).append(aPackage.getBundleID());
// 如果目录不存在创建目录
File dir = new File(path.toString());
if (!dir.exists()) dir.mkdirs();
path.append(File.separator).append(aPackage.getCreateTime()).append(".png");
return path.toString();
}
/**
* 获取上传路径
*
* @return
*/
public static String getUploadPath() {
try {
//获取跟目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) path = new File("");
//如果上传目录为/static/upload/则可以如下获取
File upload = new File(path.getAbsolutePath(), "static/upload/");
if (!upload.exists()) upload.mkdirs();
return upload.getPath();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取 APP 路径
*
* @param app
* @return
*/
public static String getAppPath(App app) {
return getUploadPath() + File.separator + app.getPlatform() + File.separator + app.getBundleID() + File.separator;
}
/**
* 获取包的完整路径
*
* @param aPackage
* @return
*/
public static String getFullPath(Package aPackage) {
return getUploadPath() + File.separator + getRelativePath(aPackage);
}
/**
* 获取包的相对路径
*
* @param aPackage
* @return
*/
public static String getRelativePath(Package aPackage) {
if (aPackage == null) return null;
StringBuilder path = new StringBuilder();
path.append(aPackage.getPlatform()).append(File.separator);
path.append(aPackage.getApp().getOwner().getId()).append(File.separator);
path.append(aPackage.getBundleID()).append(File.separator);
path.append(aPackage.getCreateTime()).append(File.separator);
return path.toString();
}
/**
* 清除目录
*
* @param path
*/
public static void deleteDirectory(String path) {
File dir = new File(path);
if (dir.exists()) {
try {
FileUtils.deleteDirectory(dir);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取基础路径
*
* @param isHttps
* @return
*/
@@ -40,7 +130,7 @@ public class PathManager {
try {
// URL
InetAddress address = InetAddress.getLocalHost();
String domain=environment.getProperty("server.domain");
String domain = environment.getProperty("server.domain");
if (domain == null) {
domain = address.getHostAddress();
}
@@ -71,104 +161,24 @@ public class PathManager {
/**
* 获取包所在路径
*
* @param aPackage
* @param isHttps
* @return
*/
public String getPackageResourceURL(Package aPackage, boolean isHttps) {
String baseURL = getBaseURL(isHttps);
String resourceURL = baseURL + aPackage.getPlatform() + "/" + aPackage.getBundleID() + "/" + aPackage.getCreateTime() + "/";
String resourceURL = baseURL + aPackage.getPlatform() + "/" + aPackage.getBundleID()
+ "/" + aPackage.getCreateTime() + "/";
return resourceURL;
}
/**
* 获取证书路径
*
* @return
*/
public String getCAPath() {
return getBaseURL(false) + "crt/ca.crt";
}
/**
* 获取图标的临时路径
* @param aPackage
* @return
*/
public static String getTempIconPath(Package aPackage) {
if (aPackage == null) return null;
StringBuilder path = new StringBuilder();
path.append(FileUtils.getTempDirectoryPath()).append(File.separator).append(aPackage.getPlatform());
path.append(File.separator).append(aPackage.getBundleID());
// 如果目录不存在创建目录
File dir = new File(path.toString());
if (!dir.exists()) dir.mkdirs();
path.append(File.separator).append(aPackage.getCreateTime()).append(".png");
return path.toString();
}
/**
* 获取上传路径
* @return
*/
public static String getUploadPath() {
try {
//获取跟目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
//如果上传目录为/static/upload/则可以如下获取
File upload = new File(path.getAbsolutePath(),"static/upload/");
if(!upload.exists()) upload.mkdirs();
return upload.getPath();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取 APP 路径
* @param app
* @return
*/
public static String getAppPath(App app) {
return getUploadPath() + File.separator + app.getPlatform() + File.separator + app.getBundleID() + File.separator;
}
/**
* 获取包的完整路径
* @param aPackage
* @return
*/
public static String getFullPath(Package aPackage) {
return getUploadPath() + File.separator + getRelativePath(aPackage);
}
/**
* 获取包的相对路径
* @param aPackage
* @return
*/
public static String getRelativePath(Package aPackage) {
if (aPackage == null) return null;
StringBuilder path = new StringBuilder();
path.append(aPackage.getPlatform()).append(File.separator);
path.append(aPackage.getBundleID()).append(File.separator);
path.append(aPackage.getCreateTime()).append(File.separator);
return path.toString();
}
/**
* 清除目录
* @param path
*/
public static void deleteDirectory(String path) {
File dir = new File(path);
if (dir.exists()) {
try {
FileUtils.deleteDirectory(dir);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@@ -1,4 +1,4 @@
package org.yzr.utils;
package org.yzr.utils.file;
import org.apache.commons.io.FileUtils;
@@ -9,7 +9,7 @@ import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtils {
public class ZipUtil {
public static String unzip(String path) {
try {
@@ -18,7 +18,7 @@ public class ZipUtils {
ZipFile zipFile = new ZipFile(path);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
String dirPath = destDirPath + File.separator + entry.getName();
File dir = new File(dirPath);
@@ -1,4 +1,4 @@
package org.yzr.utils;
package org.yzr.utils.image;
import java.awt.*;
import java.awt.image.BufferedImage;
@@ -1,4 +1,4 @@
package org.yzr.utils;
package org.yzr.utils.image;
import com.jcraft.jzlib.Deflater;
import com.jcraft.jzlib.GZIPException;
@@ -1,4 +1,4 @@
package org.yzr.utils;
package org.yzr.utils.image;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
@@ -0,0 +1,79 @@
package org.yzr.utils.ipa;
import java.util.List;
public class InfoPlist {
private Plist plist;
private String appName;
private String version;
private String buildVersion;
private String bundleID;
private String minimumOSVersion;
private String iconName;
public InfoPlist(Plist plist) {
this.plist = plist;
// 应用名
String appName = this.plist.stringValueForKeyPath("CFBundleDisplayName");
if (appName == null) {
appName = this.plist.stringValueForKeyPath("CFBundleName");
}
this.appName = appName;
// 主版本号
String version = this.plist.stringValueForPath("CFBundleShortVersionString");
this.version = version;
// 构建版本号
String buildVersion = this.plist.stringValueForPath("CFBundleVersion");
this.buildVersion = buildVersion;
// 应用ID
String bundleID = this.plist.stringValueForPath("CFBundleIdentifier");
this.bundleID = bundleID;
// 系统最低版本号
String minimumOSVersion = this.plist.stringValueForPath("MinimumOSVersion");
this.minimumOSVersion = minimumOSVersion;
// 图标名称
String iconName = this.plist.stringValueForPath("CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName");
if (iconName == null) {
iconName = this.plist.stringValueForKeyPath("CFBundleIconFile");
}
if (iconName == null) {
List<String> iconFiles = this.plist.arrayValueForPath("CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles");
if (iconFiles != null && iconFiles.size() > 0) {
iconName = iconFiles.get(iconFiles.size() - 1);
}
}
this.iconName = iconName;
}
public String getAppName() {
return appName;
}
public String getVersion() {
return version;
}
public String getBuildVersion() {
return buildVersion;
}
public String getBundleID() {
return bundleID;
}
public String getMinimumOSVersion() {
return minimumOSVersion;
}
public String getIconName() {
return iconName;
}
}
@@ -5,10 +5,10 @@ import net.dongliu.apk.parser.bean.ApkMeta;
import net.dongliu.apk.parser.bean.IconFace;
import org.apache.commons.io.FileUtils;
import org.yzr.model.Package;
import org.yzr.utils.PathManager;
import org.yzr.utils.file.PathManager;
import java.io.File;
import java.util.UUID;
public class APKParser implements PackageParser {
@Override
@@ -17,7 +17,6 @@ public class APKParser implements PackageParser {
File file = new File(filePath);
if (!file.exists()) return null;
ApkFile apkFile = new ApkFile(file);
long currentTimeMillis = System.currentTimeMillis();
Package aPackage = new Package();
aPackage.setSize(file.length());
ApkMeta meta = apkFile.getApkMeta();
@@ -35,7 +34,7 @@ public class APKParser implements PackageParser {
aPackage.setBundleID(meta.getPackageName());
aPackage.setMinVersion(meta.getMinSdkVersion());
aPackage.setPlatform("android");
aPackage.setCreateTime(currentTimeMillis);
aPackage.setCreateTime(System.currentTimeMillis());
int iconCount = apkFile.getAllIcons().size();
if (iconCount > 0) {
IconFace icon = apkFile.getAllIcons().get(iconCount - 1);
@@ -45,7 +44,7 @@ public class APKParser implements PackageParser {
}
apkFile.close();
return aPackage;
}catch (Exception e){
} catch (Exception e) {
}
return null;
@@ -3,70 +3,23 @@ package org.yzr.utils.parser;
import com.dd.plist.NSDate;
import org.apache.commons.io.FileUtils;
import org.yzr.model.Package;
import org.yzr.utils.PNGConverter;
import org.yzr.utils.PathManager;
import org.yzr.utils.ZipUtils;
import org.yzr.utils.ipa.Plist;
import org.yzr.model.Provision;
import org.yzr.utils.file.PathManager;
import org.yzr.utils.file.ZipUtil;
import org.yzr.utils.image.PNGConverter;
import org.yzr.utils.ipa.InfoPlist;
import org.yzr.utils.ipa.Plist;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class IPAParser implements PackageParser {
@Override
public Package parse(String filePath) {
try {
Package aPackage = new Package();
// 解压 IPA 包
String targetPath = ZipUtils.unzip(filePath);
String appPath = appPath(targetPath);
String infoPlistPath = appPath + File.separator + "Info.plist";
infoPlistPath = infoPlistPath.replaceAll("//", "/");
File infoPlistFile = new File(infoPlistPath);
// Plist 文件获取失败
if (!infoPlistFile.exists()) return null;
// 获取 infoPlist
Plist infoPlist = Plist.parseWithFile(infoPlistFile);
File ipaFile = new File(filePath);
long currentTimeMillis = System.currentTimeMillis();
aPackage.setSize(ipaFile.length());
aPackage.setName(infoPlist.stringValueForPath("CFBundleDisplayName"));
if (aPackage.getName() == null) {
aPackage.setName(infoPlist.stringValueForPath("CFBundleName"));
}
aPackage.setVersion(infoPlist.stringValueForPath("CFBundleShortVersionString"));
aPackage.setBuildVersion(infoPlist.stringValueForPath("CFBundleVersion"));
aPackage.setBundleID(infoPlist.stringValueForPath("CFBundleIdentifier"));
aPackage.setMinVersion(infoPlist.stringValueForPath("MinimumOSVersion"));
aPackage.setCreateTime(currentTimeMillis);
aPackage.setPlatform("ios");
// 获取应用图标
String iconName = infoPlist.stringValueForKeyPath("CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName");
if (iconName == null) {
iconName = infoPlist.stringValueForKeyPath("CFBundleIconFile");
}
String iconPath = appIcon(appPath, iconName);
String iconTempPath = PathManager.getTempIconPath(aPackage);
PNGConverter.convert(iconPath, iconTempPath);
// 解析 Provision
aPackage.setProvision(getProvision(appPath));
// 清除目录
FileUtils.deleteDirectory(new File(targetPath));
return aPackage;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/*获取 APP 路径*/
private static String appPath(String path) {
try {
@@ -96,7 +49,7 @@ public class IPAParser implements PackageParser {
File appFile = new File(appPath);
File[] listFiles = appFile.listFiles();
for (File file : listFiles) {
String pattern = iconName + "[4,6]0x[4,6]0@[2,3]?x.png";
String pattern = iconName + "([4,6]0x[4,6]0)?(@[2,3]x)?(\\.png)?";
boolean isMatch = Pattern.matches(pattern, file.getName());
if (isMatch) {
iconNames.add(file.getName());
@@ -113,10 +66,17 @@ public class IPAParser implements PackageParser {
private static Provision getProvision(String appPath) {
Provision provision = new Provision();
String profile = appPath + File.separator + "embedded.mobileprovision";
File profileFile = new File(profile);
// 文件不存在
if (!profileFile.exists()) {
provision.setType("Release");
return provision;
}
try {
boolean started = false;
boolean ended = false;
BufferedReader reader = new BufferedReader(new FileReader(profile));
BufferedReader reader = new BufferedReader(new FileReader(profileFile));
StringBuffer plist = new StringBuffer();
String str = null;
while ((str = reader.readLine()) != null) {
@@ -125,7 +85,7 @@ public class IPAParser implements PackageParser {
plist.append("</plist>").append("\n");
} else if (started && !ended) {
plist.append(str).append("\n");
} else if (str.contains("<?xml")) {
} else if (str.contains("<?xml")) {
started = true;
plist.append(str.substring(str.indexOf("<?xml"))).append("\n");
}
@@ -140,8 +100,10 @@ public class IPAParser implements PackageParser {
provision.setDeviceCount(devices.length);
provision.setTeamName(provisionFile.stringValueForPath("TeamName"));
provision.setTeamID(provisionFile.arrayValueForPath("TeamIdentifier").get(0));
provision.setCreateDate(((NSDate)provisionFile.valueForKeyPath("CreationDate")).getDate());
provision.setExpirationDate(((NSDate)provisionFile.valueForKeyPath("ExpirationDate")).getDate());
long createDate =((NSDate) provisionFile.valueForKeyPath("CreationDate")).getDate().getTime();
provision.setCreateDate(createDate);
long expirationDate = ((NSDate) provisionFile.valueForKeyPath("ExpirationDate")).getDate().getTime();
provision.setExpirationDate(expirationDate);
provision.setUUID(provisionFile.stringValueForPath("UUID"));
provision.setType(provision.getDeviceCount() > 0 ? "AdHoc" : "Release");
} catch (Exception e) {
@@ -149,4 +111,48 @@ public class IPAParser implements PackageParser {
}
return provision;
}
@Override
public Package parse(String filePath) {
try {
Package aPackage = new Package();
// 解压 IPA 包
String targetPath = ZipUtil.unzip(filePath);
String appPath = appPath(targetPath);
String infoPlistPath = appPath + File.separator + "Info.plist";
infoPlistPath = infoPlistPath.replaceAll("//", "/");
File infoPlistFile = new File(infoPlistPath);
// Plist 文件获取失败
if (!infoPlistFile.exists()) return null;
// 获取 infoPlist
Plist plist = Plist.parseWithFile(infoPlistFile);
InfoPlist infoPlist = new InfoPlist(plist);
File ipaFile = new File(filePath);
aPackage.setSize(ipaFile.length());
aPackage.setName(infoPlist.getAppName());
aPackage.setVersion(infoPlist.getVersion());
aPackage.setBuildVersion(infoPlist.getBuildVersion());
aPackage.setBundleID(infoPlist.getBundleID());
aPackage.setMinVersion(infoPlist.getMinimumOSVersion());
aPackage.setCreateTime(System.currentTimeMillis());
aPackage.setPlatform("ios");
// 获取应用图标
String iconName = infoPlist.getIconName();
String iconPath = appIcon(appPath, iconName);
String iconTempPath = PathManager.getTempIconPath(aPackage);
PNGConverter.convert(iconPath, iconTempPath);
// 解析 Provision
aPackage.setProvision(getProvision(appPath));
// 清除目录
FileUtils.deleteDirectory(new File(targetPath));
return aPackage;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@@ -10,7 +10,7 @@ public class ParserClient {
* @param filePath 文件路径
* @return
*/
public static Package parse(String filePath) {
public static Package parse(String filePath) throws ClassNotFoundException {
PackageParser parser = getParser(filePath);
if (parser != null) {
return parser.parse(filePath);
@@ -23,11 +23,11 @@ public class ParserClient {
* @param filePath
* @return
*/
private static PackageParser getParser(String filePath) {
private static PackageParser getParser(String filePath) throws ClassNotFoundException {
String extension = FilenameUtils.getExtension(filePath);
// 动态获取解析器
Class aClass = Class.forName("org.yzr.utils.parser." + extension.toUpperCase()+"Parser");
try {
// 动态获取解析器
Class aClass = Class.forName("org.yzr.utils.parser." + extension.toUpperCase()+"Parser");
PackageParser packageParser = (PackageParser)aClass.newInstance();
return packageParser;
} catch (Exception e) {
@@ -0,0 +1,32 @@
package org.yzr.utils.response;
public class BaseResponse<T> {
private Integer code;
private String msg;
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
@@ -0,0 +1,52 @@
package org.yzr.utils.response;
import java.util.List;
public class PageData<T> {
private Integer total;
private Integer page;
private Integer pageSize;
private Integer totalPage;
private List<T> list;
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
@@ -0,0 +1,10 @@
package org.yzr.utils.response;
public class ResponseCode {
public static final Integer USER_INVALID_ACCOUNT = 601;
public static final Integer USER_NAME_EXIST = 602;
public static final Integer ROLE_NAME_EXIST = 603;
public static final Integer ROLE_SUPER_SUPERMISSION = 604;
public static final Integer ROLE_USER_EXIST = 605;
}
@@ -0,0 +1,111 @@
package org.yzr.utils.response;
import java.util.List;
/**
* 响应操作结果
* <pre>
* {
* errno 错误码,
* errmsg:错误消息,
* data 响应数据
* }
* </pre>
*
* <p>
* 错误码:
* <ul>
* <li> 0,成功;
* <li> 4xx,前端错误,说明前端开发者需要重新了解后端接口使用规范:
* <ul>
* <li> 401,参数错误,即前端没有传递后端需要的参数;
* <li> 402,参数值错误,即前端传递的参数值不符合后端接收范围。
* </ul>
* <li> 5xx,后端错误,除501外,说明后端开发者应该继续优化代码,尽量避免返回后端错误码:
* <ul>
* <li> 501,验证失败,即后端要求用户登录;
* <li> 502,系统内部错误,即没有合适命名的后端内部错误;
* <li> 503,业务不支持,即后端虽然定义了接口,但是还没有实现功能;
* <li> 504,更新数据失效,即后端采用了乐观锁更新,而并发更新时存在数据更新失效;
* <li> 505,更新数据失败,即后端数据库更新失败(正常情况应该更新成功)。
* </ul>
* <li> 6xx,小商城后端业务错误码,
* 具体见scoremall-admin-api模块的AdminResponseCode。
* <li> 7xx,管理后台后端业务错误码,
* 具体见scoremall-app-api模块的WxResponseCode。
* </ul>
*/
public class ResponseUtil {
public static BaseResponse ok() {
BaseResponse obj = new BaseResponse();
obj.setCode(0);
obj.setMsg("成功");
return obj;
}
public static <T> BaseResponse ok(T data) {
BaseResponse obj = new BaseResponse();
obj.setCode(0);
obj.setMsg("成功");
obj.setData(data);
return obj;
}
public static <T> BaseResponse okList(List<T> list) {
PageData pageData = new PageData();
pageData.setList(list);
pageData.setTotal(list.size());
pageData.setPage(1);
pageData.setPageSize(list.size());
pageData.setTotalPage(1);
return ok(pageData);
}
public static BaseResponse fail() {
BaseResponse obj = new BaseResponse();
obj.setCode(-1);
obj.setMsg("错误");
return obj;
}
public static BaseResponse fail(int errno, String errmsg) {
BaseResponse obj = new BaseResponse();
obj.setCode(errno);
obj.setMsg(errmsg);
return obj;
}
public static BaseResponse badArgument() {
return fail(401, "参数不对");
}
public static BaseResponse badArgumentValue() {
return fail(402, "参数值不对");
}
public static BaseResponse unlogin() {
return fail(501, "请登录");
}
public static BaseResponse serious() {
return fail(502, "系统内部错误");
}
public static BaseResponse unsupport() {
return fail(503, "业务不支持");
}
public static BaseResponse updatedDateExpired() {
return fail(504, "更新数据已经失效");
}
public static BaseResponse updatedDataFailed() {
return fail(505, "更新数据失败");
}
public static BaseResponse unauthz() {
return fail(506, "无操作权限");
}
}
@@ -7,9 +7,9 @@ import org.springframework.util.StringUtils;
import org.yzr.model.App;
import org.yzr.model.Package;
import org.yzr.model.WebHook;
import org.yzr.utils.ImageUtils;
import org.yzr.utils.PathManager;
import org.yzr.utils.QRCodeUtil;
import org.yzr.utils.image.ImageUtils;
import org.yzr.utils.file.PathManager;
import org.yzr.utils.image.QRCodeUtil;
import java.io.File;
import java.util.HashMap;
@@ -1,7 +1,7 @@
package org.yzr.utils.webhook;
import org.yzr.model.App;
import org.yzr.utils.PathManager;
import org.yzr.utils.file.PathManager;
public interface IWebHook {
void sendMessage(App app, PathManager pathManager);
@@ -2,7 +2,7 @@ package org.yzr.utils.webhook;
import org.yzr.model.App;
import org.yzr.model.WebHook;
import org.yzr.utils.PathManager;
import org.yzr.utils.file.PathManager;
import java.util.HashMap;
import java.util.Map;
+9 -1
View File
@@ -2,7 +2,7 @@ package org.yzr.vo;
import org.yzr.model.App;
import org.yzr.model.Package;
import org.yzr.utils.PathManager;
import org.yzr.utils.file.PathManager;
import java.util.ArrayList;
import java.util.List;
@@ -30,6 +30,8 @@ public class AppViewModel {
private String installPath;
private String userId;
private List<PackageViewModel> packageList;
private PackageViewModel currentPackage;
@@ -44,6 +46,8 @@ public class AppViewModel {
this.id = app.getId();
this.platform = app.getPlatform();
this.bundleID = app.getBundleID();
app.getCurrentPackage().setApp(app);
this.userId = app.getOwner().getId();
this.icon = PathManager.getRelativePath(app.getCurrentPackage()) + "icon.png";
Package aPackage = findPackageById(app, null);
this.version = aPackage.getVersion();
@@ -149,4 +153,8 @@ public class AppViewModel {
public PackageViewModel getCurrentPackage() {
return currentPackage;
}
public String getUserId() {
return userId;
}
}
@@ -4,10 +4,13 @@ import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;
import org.yzr.model.Package;
import org.yzr.utils.PathManager;
import org.yzr.utils.date.DateUtil;
import org.yzr.utils.file.PathManager;
import java.net.URLEncoder;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -52,7 +55,9 @@ public class PackageViewModel {
String url = pathManager.getBaseURL(true) + "m/" + aPackage.getId();
try {
this.installURL = "itms-services://?action=download-manifest&url=" + URLEncoder.encode(url, "utf-8");
} catch (Exception e){e.printStackTrace();}
} catch (Exception e) {
e.printStackTrace();
}
} else if (aPackage.getPlatform().equals("android")) {
this.iOS = false;
this.installURL = pathManager.getPackageResourceURL(aPackage, false) + aPackage.getFileName();
@@ -64,7 +69,7 @@ public class PackageViewModel {
} else {
if (aPackage.getProvision().isEnterprise()) {
this.type = "企业版";
} else {
} else {
if ("AdHoc".equalsIgnoreCase(aPackage.getProvision().getType())) {
this.type = "内测版";
} else {
+30 -4
View File
@@ -1,9 +1,9 @@
########################################################
### Mysql
########################################################
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/app_manager?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/app_manager?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=app_manager
spring.datasource.password=app_manager123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
########################################################
@@ -37,8 +37,34 @@ server.ssl.key-store-password=123456
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=1
# 对象存储配置
# 当前工作的对象存储模式,分别是local、aliyun、tencent、qiniu
storage.active=local
# 本地对象存储配置信息
storage.local.storagePath=storage
# 这个地方应该是wx模块的WxStorageController的fetch方法对应的地址
storage.local.address=http://localhost:8080/app/storage/fetch/
# 阿里云对象存储配置信息
storage.aliyun.endpoint=oss-cn-shenzhen.aliyuncs.com
storage.aliyun.accessKeyId=111111
storage.aliyun.accessKeySecret=xxxxxx
storage.aliyun.bucketName=app_manager
# 腾讯对象存储配置信息
# 请参考 https://cloud.tencent.com/document/product/436/6249
storage.tencent.secretId=AKIDOccMr856uoU1Tsa2MQL5aqseBUWRrb5i
storage.tencent.secretKey=XqtgEhIdrupTs4ygaWlkUUXv3w3FiwuD
storage.tencent.region=ap-shanghai
storage.tencent.bucketName=vytech-1300096589
# 七牛云对象存储配置信息
storage.qiniu.endpoint=http://pd5cb6ulu.bkt.clouddn.com
storage.qiniu.accessKey=111111
storage.qiniu.secretKey=xxxxxx
storage.qiniu.bucketName=app_manager
# 自定义配置
server.port=443
server.http.port=80
config.debug=debug
server.domain=127.0.0.1
server.domain=127.0.0.1
admin.username=admin
admin.password=admin123456
@@ -0,0 +1,28 @@
/**
* jQuery toast plugin created by Kamran Ahmed copyright MIT license 2014
*/
.jq-toast-wrap { display: block; position: fixed; width: 250px; pointer-events: none !important; margin: 0; padding: 0; letter-spacing: normal; z-index: 9000 !important; }
.jq-toast-wrap * { margin: 0; padding: 0; }
.jq-toast-wrap.bottom-left { bottom: 20px; left: 20px; }
.jq-toast-wrap.bottom-right { bottom: 20px; right: 40px; }
.jq-toast-wrap.top-left { top: 20px; left: 20px; }
.jq-toast-wrap.top-right { top: 20px; right: 40px; }
.jq-toast-single { display: block; width: 100%; padding: 10px; margin: 0px 0px 5px; border-radius: 4px; font-size: 12px; font-family: arial, sans-serif; line-height: 17px; position: relative; pointer-events: all !important; background-color: #444444; color: white; }
.jq-toast-single h2 { font-family: arial, sans-serif; font-size: 14px; margin: 0px 0px 7px; background: none; color: inherit; line-height: inherit; letter-spacing: normal; }
.jq-toast-single a { color: #eee; text-decoration: none; font-weight: bold; border-bottom: 1px solid white; padding-bottom: 3px; font-size: 12px; }
.jq-toast-single ul { margin: 0px 0px 0px 15px; background: none; padding:0px; }
.jq-toast-single ul li { list-style-type: disc !important; line-height: 17px; background: none; margin: 0; padding: 0; letter-spacing: normal; }
.close-jq-toast-single { position: absolute; top: 3px; right: 7px; font-size: 14px; cursor: pointer; }
.jq-toast-loader { display: block; position: absolute; top: -2px; height: 5px; width: 0%; left: 0; border-radius: 5px; background: red; }
.jq-toast-loaded { width: 100%; }
.jq-has-icon { padding: 10px 10px 10px 50px; background-repeat: no-repeat; background-position: 10px; }
.jq-icon-info { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII='); background-color: #31708f; color: #d9edf7; border-color: #bce8f1; }
.jq-icon-warning { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII='); background-color: #8a6d3b; color: #fcf8e3; border-color: #faebcc; }
.jq-icon-error { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII='); background-color: #a94442; color: #f2dede; border-color: #ebccd1; }
.jq-icon-success { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg=='); color: #dff0d8; background-color: #3c763d; border-color: #d6e9c6; }
File diff suppressed because one or more lines are too long
@@ -0,0 +1,354 @@
;
// jQuery toast plugin created by Kamran Ahmed copyright MIT license 2015
if ( typeof Object.create !== 'function' ) {
Object.create = function( obj ) {
function F() {}
F.prototype = obj;
return new F();
};
}
(function( $, window, document, undefined ) {
"use strict";
var Toast = {
_positionClasses : ['bottom-left', 'bottom-right', 'top-right', 'top-left', 'bottom-center', 'top-center', 'mid-center'],
_defaultIcons : ['success', 'error', 'info', 'warning'],
init: function (options, elem) {
this.prepareOptions(options, $.toast.options);
this.process();
},
prepareOptions: function(options, options_to_extend) {
var _options = {};
if ( ( typeof options === 'string' ) || ( options instanceof Array ) ) {
_options.text = options;
} else {
_options = options;
}
this.options = $.extend( {}, options_to_extend, _options );
},
process: function () {
this.setup();
this.addToDom();
this.position();
this.bindToast();
this.animate();
},
setup: function () {
var _toastContent = '';
this._toastEl = this._toastEl || $('<div></div>', {
class : 'jq-toast-single'
});
// For the loader on top
_toastContent += '<span class="jq-toast-loader"></span>';
if ( this.options.allowToastClose ) {
_toastContent += '<span class="close-jq-toast-single">&times;</span>';
};
if ( this.options.text instanceof Array ) {
if ( this.options.heading ) {
_toastContent +='<h2 class="jq-toast-heading">' + this.options.heading + '</h2>';
};
_toastContent += '<ul class="jq-toast-ul">';
for (var i = 0; i < this.options.text.length; i++) {
_toastContent += '<li class="jq-toast-li" id="jq-toast-item-' + i + '">' + this.options.text[i] + '</li>';
}
_toastContent += '</ul>';
} else {
if ( this.options.heading ) {
_toastContent +='<h2 class="jq-toast-heading">' + this.options.heading + '</h2>';
};
_toastContent += this.options.text;
}
this._toastEl.html( _toastContent );
if ( this.options.bgColor !== false ) {
this._toastEl.css("background-color", this.options.bgColor);
};
if ( this.options.textColor !== false ) {
this._toastEl.css("color", this.options.textColor);
};
if ( this.options.textAlign ) {
this._toastEl.css('text-align', this.options.textAlign);
}
if ( this.options.icon !== false ) {
this._toastEl.addClass('jq-has-icon');
if ( $.inArray(this.options.icon, this._defaultIcons) !== -1 ) {
this._toastEl.addClass('jq-icon-' + this.options.icon);
};
};
},
position: function () {
if ( ( typeof this.options.position === 'string' ) && ( $.inArray( this.options.position, this._positionClasses) !== -1 ) ) {
if ( this.options.position === 'bottom-center' ) {
this._container.css({
left: ( $(window).outerWidth() / 2 ) - this._container.outerWidth()/2,
bottom: 20
});
} else if ( this.options.position === 'top-center' ) {
this._container.css({
left: ( $(window).outerWidth() / 2 ) - this._container.outerWidth()/2,
top: 20
});
} else if ( this.options.position === 'mid-center' ) {
this._container.css({
left: ( $(window).outerWidth() / 2 ) - this._container.outerWidth()/2,
top: ( $(window).outerHeight() / 2 ) - this._container.outerHeight()/2
});
} else {
this._container.addClass( this.options.position );
}
} else if ( typeof this.options.position === 'object' ) {
this._container.css({
top : this.options.position.top ? this.options.position.top : 'auto',
bottom : this.options.position.bottom ? this.options.position.bottom : 'auto',
left : this.options.position.left ? this.options.position.left : 'auto',
right : this.options.position.right ? this.options.position.right : 'auto'
});
} else {
this._container.addClass( 'bottom-left' );
}
},
bindToast: function () {
var that = this;
this._toastEl.on('afterShown', function () {
that.processLoader();
});
this._toastEl.find('.close-jq-toast-single').on('click', function ( e ) {
e.preventDefault();
if( that.options.showHideTransition === 'fade') {
that._toastEl.trigger('beforeHide');
that._toastEl.fadeOut(function () {
that._toastEl.trigger('afterHidden');
});
} else if ( that.options.showHideTransition === 'slide' ) {
that._toastEl.trigger('beforeHide');
that._toastEl.slideUp(function () {
that._toastEl.trigger('afterHidden');
});
} else {
that._toastEl.trigger('beforeHide');
that._toastEl.hide(function () {
that._toastEl.trigger('afterHidden');
});
}
});
if ( typeof this.options.beforeShow == 'function' ) {
this._toastEl.on('beforeShow', function () {
that.options.beforeShow();
});
};
if ( typeof this.options.afterShown == 'function' ) {
this._toastEl.on('afterShown', function () {
that.options.afterShown();
});
};
if ( typeof this.options.beforeHide == 'function' ) {
this._toastEl.on('beforeHide', function () {
that.options.beforeHide();
});
};
if ( typeof this.options.afterHidden == 'function' ) {
this._toastEl.on('afterHidden', function () {
that.options.afterHidden();
});
};
},
addToDom: function () {
var _container = $('.jq-toast-wrap');
if ( _container.length === 0 ) {
_container = $('<div></div>',{
class: "jq-toast-wrap"
});
$('body').append( _container );
} else if ( !this.options.stack || isNaN( parseInt(this.options.stack, 10) ) ) {
_container.empty();
}
_container.find('.jq-toast-single:hidden').remove();
_container.append( this._toastEl );
if ( this.options.stack && !isNaN( parseInt( this.options.stack ), 10 ) ) {
var _prevToastCount = _container.find('.jq-toast-single').length,
_extToastCount = _prevToastCount - this.options.stack;
if ( _extToastCount > 0 ) {
$('.jq-toast-wrap').find('.jq-toast-single').slice(0, _extToastCount).remove();
};
}
this._container = _container;
},
canAutoHide: function () {
return ( this.options.hideAfter !== false ) && !isNaN( parseInt( this.options.hideAfter, 10 ) );
},
processLoader: function () {
// Show the loader only, if auto-hide is on and loader is demanded
if (!this.canAutoHide() || this.options.loader === false) {
return false;
}
var loader = this._toastEl.find('.jq-toast-loader');
// 400 is the default time that jquery uses for fade/slide
// Divide by 1000 for milliseconds to seconds conversion
var transitionTime = (this.options.hideAfter - 400) / 1000 + 's';
var loaderBg = this.options.loaderBg;
var style = loader.attr('style') || '';
style = style.substring(0, style.indexOf('-webkit-transition')); // Remove the last transition definition
style += '-webkit-transition: width ' + transitionTime + ' ease-in; \
-o-transition: width ' + transitionTime + ' ease-in; \
transition: width ' + transitionTime + ' ease-in; \
background-color: ' + loaderBg + ';';
loader.attr('style', style).addClass('jq-toast-loaded');
},
animate: function () {
var that = this;
this._toastEl.hide();
this._toastEl.trigger('beforeShow');
if ( this.options.showHideTransition.toLowerCase() === 'fade' ) {
this._toastEl.fadeIn(function ( ){
that._toastEl.trigger('afterShown');
});
} else if ( this.options.showHideTransition.toLowerCase() === 'slide' ) {
this._toastEl.slideDown(function ( ){
that._toastEl.trigger('afterShown');
});
} else {
this._toastEl.show(function ( ){
that._toastEl.trigger('afterShown');
});
}
if (this.canAutoHide()) {
var that = this;
window.setTimeout(function(){
if ( that.options.showHideTransition.toLowerCase() === 'fade' ) {
that._toastEl.trigger('beforeHide');
that._toastEl.fadeOut(function () {
that._toastEl.trigger('afterHidden');
});
} else if ( that.options.showHideTransition.toLowerCase() === 'slide' ) {
that._toastEl.trigger('beforeHide');
that._toastEl.slideUp(function () {
that._toastEl.trigger('afterHidden');
});
} else {
that._toastEl.trigger('beforeHide');
that._toastEl.hide(function () {
that._toastEl.trigger('afterHidden');
});
}
}, this.options.hideAfter);
};
},
reset: function ( resetWhat ) {
if ( resetWhat === 'all' ) {
$('.jq-toast-wrap').remove();
} else {
this._toastEl.remove();
}
},
update: function(options) {
this.prepareOptions(options, this.options);
this.setup();
this.bindToast();
}
};
$.toast = function(options) {
var toast = Object.create(Toast);
toast.init(options, this);
return {
reset: function ( what ) {
toast.reset( what );
},
update: function( options ) {
toast.update( options );
}
}
};
$.toast.options = {
text: '',
heading: '温馨提示',
showHideTransition: 'fade',
allowToastClose: false,
hideAfter: 2000,
loader: false,
loaderBg: '#9EC600',
stack: 1,
position: 'mid-center',
bgColor: false,
textColor: false,
textAlign: 'left',
icon: false,
beforeShow: function () {},
afterShown: function () {},
beforeHide: function () {},
afterHidden: function () {}
};
})( jQuery, window, document );
+3 -1
View File
@@ -227,9 +227,11 @@ function bindActions() {
console.log(li);
var self = $("." + li);
$.post(url, function (result) {
if (result.success) {
var success = result.code == 0;
if (success) {
self.remove();
}
$.toast({text: result.msg, icon: success ? "success" : "error"});
});
});
}
+29
View File
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="minimal-ui,width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<meta name="format-detection" content="telephone=no">
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}"/>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" th:href="@{/css/index.css}">
<title>错误</title>
</head>
<body class="app">
<div class="container">
<div class="jumbotron">
<h1 class="text-center">无权限访问</h1>
</div>
</div>
</body>
</html>
+160 -146
View File
@@ -7,175 +7,189 @@
<meta name="renderer" content="webkit">
<title>应用列表</title>
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}" />
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}"/>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" th:href="@{/css/index.css}">
<link rel="stylesheet" th:href="@{/css/jquery.toast.css}">
<script type="text/javascript" th:src="@{/js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery.toast.js}"></script>
</head>
<body class="ng-scope">
<nav class="navbar navbar-transparent fade-out navbar-black" role="navigation">
<div class="navbar-header"><a class="navbar-brand" href="/apps"><i class="icon-logo"></i> </a></div>
<div class="collapse navbar-collapse navbar-ex1-collapse ng-scope" ng-controller="NavbarController">
<div class="dropdown">
<div></div>
</div>
<nav class="navbar navbar-transparent fade-out navbar-black" role="navigation">
<div class="navbar-header"><a class="navbar-brand" href="/apps"><i class="icon-logo"></i> </a></div>
<div class="collapse navbar-collapse navbar-ex1-collapse ng-scope" ng-controller="NavbarController">
<div class="dropdown">
<div></div>
</div>
</nav>
<div class="menu-toggle fade-out"><i class="icon-menu"></i></div>
<div class="navbar-wrapper ng-scope">
<div ng-controller="NavbarController" class="ng-scope">
<div class="navbar-header-wrap">
<div class="middle-wrapper">
<nav>
<h1 class="navbar-title logo">
<i class="icon-logo"></i>
</h1>
<i class="icon-angle-right"></i>
<div class="navbar-title primary-title">
<a class="ng-binding" th:href="${baseURL} + 'apps'">我的应用</a>
</div>
<i class="icon-angle-right ng-hide"></i>
</nav>
</div>
</div>
</div>
</div><!-- ngInclude: '/templates_manage/upload_modal.html' -->
<section data-ui-view="" class="ng-scope" style="">
<div class="page-apps ng-scope">
</div>
</nav>
<div class="menu-toggle fade-out"><i class="icon-menu"></i></div>
<div class="navbar-wrapper ng-scope">
<div ng-controller="NavbarController" class="ng-scope">
<div class="navbar-header-wrap">
<div class="middle-wrapper">
</div><!-- ngIf: !appsReady -->
<div class="middle-wrapper container-fluid" ng-show="appsReady">
<div class="apps row">
<upload-card id="uploadCard" class="components-upload-card col-xs-4 col-sm-4 col-md-4 app-animator" >
<div class="card text-center">
<div class="dashed-space">
<table>
<tbody>
<tr>
<td>
<i class="icon-upload-cloud2"></i>
<div class="text drag-state">
<span id="upload-progress" translate="DRAG_TO_UPLOAD" class="ng-scope">拖拽到这里上传</span>
<span translate="DROP_TO_UPLOAD" class="ng-scope">快松手</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</upload-card>
<div th:each="app : ${apps}" class="col-xs-4 col-sm-4 col-md-4 app-animator ng-scope">
<div th:class="'card app ' + @{'card-' + ${app.platform}}">
<i th:class="'type-icon ' + @{'icon-' + ${app.platform}}"></i>
<div class="type-mark"></div>
<a class="appicon" th:href="'/apps/' + ${app.id}" target="_blank">
<img class="icon ng-isolate-scope" width="100" height="100" th:src="@{'/' + ${app.icon}}" />
</a>
<!-- ngIf: app.has_combo --><br>
<p class="appname" th:data="@{${baseURL} + 'apps/' + ${app.id}}">
<i class="icon-owner"></i>
<span class="ng-binding">[[${app.name}]]</span></p>
<nav>
<h1 class="navbar-title logo">
<i class="icon-logo"></i>
</h1>
<i class="icon-angle-right"></i>
<div class="navbar-title primary-title">
<a class="ng-binding" th:href="${baseURL} + 'apps'">我的应用</a>
</div>
<i class="icon-angle-right ng-hide"></i>
</nav>
</div>
</div>
</div>
</div><!-- ngInclude: '/templates_manage/upload_modal.html' -->
<section data-ui-view="" class="ng-scope" style="">
<div class="page-apps ng-scope">
<div class="middle-wrapper">
</div><!-- ngIf: !appsReady -->
<div class="middle-wrapper container-fluid" ng-show="appsReady">
<div class="apps row">
<upload-card id="uploadCard" class="components-upload-card col-xs-4 col-sm-4 col-md-4 app-animator">
<div class="card text-center">
<div class="dashed-space">
<table>
<tbody>
<tr>
<td class="ng-binding">短链接:</td>
<td><span class="ng-binding">[[${baseURL}]]s/[[${app.shortCode}]]</span></td>
</tr>
<tr>
<td class="ng-binding">包名:</td>
<td>
<span title="com.mistong.ewt360" class="ng-binding">[[${app.bundleID}]]</span>
</td>
</tr>
<tr>
<td class="ng-binding">版本:</td>
<td>
<span class="ng-binding">[[${app.version}]] ( Build [[${app.buildVersion}]] )</span>
</td>
</tr>
<tr>
<td>
<i class="icon-upload-cloud2"></i>
<div class="text drag-state">
<span id="upload-progress" translate="DRAG_TO_UPLOAD" class="ng-scope">拖拽到这里上传</span>
<span translate="DROP_TO_UPLOAD" class="ng-scope">快松手</span>
</div>
</td>
</tr>
</tbody>
</table>
<div class="action">
<a class="ng-binding" th:href="'/apps/' + ${app.id}">
<i class="icon-pen"></i> 编辑</a>
<a th:href="@{${baseURL}+'s/'+${app.shortCode}}" target="_blank" class="ng-binding">
<i class="icon-eye"></i> 预览</a>
<button class="btn btn-remove ng-scope" th:data="${app.id}">
<i class="icon icon-trash"></i>
</button>
</div>
</div>
</div>
</upload-card>
<div th:each="app : ${apps}" class="col-xs-4 col-sm-4 col-md-4 app-animator ng-scope">
<div th:class="'card app ' + @{'card-' + ${app.platform}}">
<i th:class="'type-icon ' + @{'icon-' + ${app.platform}}"></i>
<div class="type-mark"></div>
<a class="appicon" th:href="'/apps/' + ${app.id}" target="_blank">
<img class="icon ng-isolate-scope" width="100" height="100" th:src="@{'/' + ${app.icon}}"/>
</a>
<!-- ngIf: app.has_combo --><br>
<p class="appname" th:data="@{${baseURL} + 'apps/' + ${app.id}}">
<i class="icon-owner"></i>
<span class="ng-binding">[[${app.name}]]</span></p>
<table>
<tbody>
<tr>
<td class="ng-binding">短链接:</td>
<td><span class="ng-binding">[[${baseURL}]]s/[[${app.shortCode}]]</span></td>
</tr>
<tr>
<td class="ng-binding">包名:</td>
<td>
<span title="com.mistong.ewt360" class="ng-binding">[[${app.bundleID}]]</span>
</td>
</tr>
<tr>
<td class="ng-binding">版本:</td>
<td>
<span class="ng-binding">[[${app.version}]] ( Build [[${app.buildVersion}]] )</span>
</td>
</tr>
</tbody>
</table>
<div class="action">
<a class="ng-binding" th:href="'/apps/' + ${app.id}">
<i class="icon-pen"></i> 编辑</a>
<a th:href="@{${baseURL}+'s/'+${app.shortCode}}" target="_blank" class="ng-binding">
<i class="icon-eye"></i> 预览</a>
<button class="btn btn-remove ng-scope" th:data="${app.id}">
<i class="icon icon-trash"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</section>
<div alert-bar="" class="alert-bar ng-hide" ng-show="anyErrors">
<div class="action" ng-click="close()"></div>
<div class="inner">
<p ng-bind="errors" class="ng-binding"></p>
</div>
</div>
<script type="text/javascript">
var dashboard = document.getElementById("uploadCard")
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
// 必须要禁用浏览器默认事件
e.preventDefault()
e.stopPropagation()
var files = this.files || e.dataTransfer.files
var file = files[0]
//上传
var xhr = new XMLHttpRequest();
xhr.open("post", "/app/upload", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// 获取上传进度
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var percent = Math.floor(event.loaded / event.total * 100);
var uploadText = "拖拽到这里上传"
var uploadElement = document.getElementById("upload-progress")
if (percent < 100) {
uploadElement.innerText="正在上传:" + percent + "%"
} else {
uploadElement.innerText=uploadText
}
</section>
<div alert-bar="" class="alert-bar ng-hide" ng-show="anyErrors">
<div class="action" ng-click="close()"></div>
<div class="inner">
<p ng-bind="errors" class="ng-binding"></p>
</div>
</div>
<script type="text/javascript">
var dashboard = document.getElementById("uploadCard")
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
// 必须要禁用浏览器默认事件
e.preventDefault()
e.stopPropagation()
var files = this.files || e.dataTransfer.files
var file = files[0]
//上传
var xhr = new XMLHttpRequest();
xhr.open("post", "/app/upload", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// 获取上传进度
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
var percent = Math.floor(event.loaded / event.total * 100);
var uploadText = "拖拽到这里上传"
var uploadElement = document.getElementById("upload-progress")
if (percent < 100) {
uploadElement.innerText = "正在上传:" + percent + "%"
} else {
uploadElement.innerText = uploadText
}
};
// 上传完成
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
window.location.href=window.location.href
}
};
// 上传完成
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var result = JSON.parse(xhr.response);
console.log(result);
var success = result.code == 0;
$.toast({text: result.msg, icon: success ? 'success' : 'error'});
if (success) {
// window.location.href = window.location.href;
// window.location.reload;
}
}
}
var fd = new FormData();
fd.append('file', file);
xhr.send(fd);
})
$(".btn-remove").click(function () {
var url = "/app/delete/" + $(this).attr("data");
$.ajax({
url: url, success: function (result) {
console.log(result);
if (result.code != 0) {
$.toast({text: result.msg, icon: 'error'});
} else {
window.location.href = window.location.href
window.location.reload
}
}
var fd = new FormData();
fd.append('file', file);
xhr.send(fd);
})
$(".btn-remove").click(function () {
var url = "/app/delete/" + $(this).attr("data");
$.ajax({url:url,success:function(result){
window.location.href=window.location.href
window.location.reload
}
});
});
$(".appname").click(function () {
window.open($(this).attr("data"))
});
</script>
});
$(".appname").click(function () {
window.open($(this).attr("data"))
});
</script>
</body>
</html>
+2
View File
@@ -9,7 +9,9 @@
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}" />
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" th:href="@{/css/index.css}">
<link rel="stylesheet" th:href="@{/css/jquery.toast.css}">
<script type="text/javascript" th:src="@{/js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery.toast.js}"></script>
<script type="text/javascript" th:src="@{/js/clipboard.min.js}"></script>
</head>
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="minimal-ui,width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<meta name="format-detection" content="telephone=no">
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}"/>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" th:href="@{/css/index.css}">
<script type="text/javascript" th:src="@{/js/jquery-1.11.0.min.js}"></script>
<title>登录</title>
</head>
<body class="app">
<div class="container">
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<h2 class="text-center">登录</h2>
</div>
</div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input class="form-control" id="username" value="admin" placeholder="输入用户名">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" value="admin123456" placeholder="密码">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="submit" class="btn btn-warning btn-lg btn-block">登录</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<a href="/account/signup" class="btn btn-default btn-lg btn-block">注册</a>
</div>
</div>
</form>
</div>
<script type="application/javascript">
$("#submit").click(function () {
var data = {
username: $("#username").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
contentType: "application/json;charset=UTF-8",
url: "/account/login",
data: JSON.stringify(data),
dataType: 'json',
success: function(result) {
if (result.code == 0) {
window.location.href = "/apps"
}
console.log(result);
}
});
})
</script>
</body>
</html>
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="minimal-ui,width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="white">
<meta name="format-detection" content="telephone=no">
<link rel="icon" type="image/x-icon" th:href="@{/images/favicon.ico}"/>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" th:href="@{/css/index.css}">
<script type="text/javascript" th:src="@{/js/jquery-1.11.0.min.js}"></script>
<title>注册</title>
</head>
<body class="app">
<div class="container">
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<h2 class="text-center">注册</h2>
</div>
</div>
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input class="form-control" id="username" placeholder="输入用户名">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" placeholder="密码">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="submit" class="btn btn-warning btn-lg btn-block">注册</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<a href="/account/signin" class="btn btn-default btn-lg btn-block">登录</a>
</div>
</div>
</form>
</div>
<script type="application/javascript">
$("#submit").click(function () {
var data = {
username: $("#username").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
contentType: "application/json;charset=UTF-8",
url: "/account/register",
data: JSON.stringify(data),
dataType: 'json',
success: function (result) {
if (result.code == 0) {
window.location.href = "/apps"
}
console.log(result);
}
});
})
</script>
</body>
</html>