diff --git a/src/main/java/com/yutou/tools/AuthConfig/AuthConfig.java b/src/main/java/com/yutou/tools/AuthConfig/AuthConfig.java new file mode 100644 index 0000000..fc085cf --- /dev/null +++ b/src/main/java/com/yutou/tools/AuthConfig/AuthConfig.java @@ -0,0 +1,158 @@ +package com.yutou.tools.AuthConfig; + +import com.alibaba.fastjson.JSONObject; +import com.yutou.tools.mybatis.dao.PermissionDao; +import com.yutou.tools.mybatis.dao.UKeyDao; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; + +import javax.annotation.Resource; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@EnableWebSecurity +public class AuthConfig { + @Resource + MyAuthenticationProvider myAuthenticationProvider; + + @Configuration + @Order(1) + public class WebLoginConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + httpConfig(http, "code"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + super.configure(auth); + auth.authenticationProvider(myAuthenticationProvider); + auth.userDetailsService(new UserDetailsServiceManager()); + } + } + + @Configuration + @Order(2) + public class TokenLoginConfig extends WebSecurityConfigurerAdapter { + + + @Override + protected void configure(HttpSecurity http) throws Exception { + httpConfig(http, "token"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + super.configure(auth); + auth.authenticationProvider(myAuthenticationProvider); + auth.userDetailsService(new UserDetailsServiceManager()); + } + } + @Configuration + @Order(3) + public class ShareLoginConfig extends WebSecurityConfigurerAdapter { + + + @Override + protected void configure(HttpSecurity http) throws Exception { + httpConfig(http, "share"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + super.configure(auth); + auth.authenticationProvider(myAuthenticationProvider); + auth.userDetailsService(new UserDetailsServiceManager()); + } + } + + @Resource + UKeyDao keyDao; + @Resource + PermissionDao permissionDao; + + public void httpConfig(HttpSecurity http, String loginParam) throws Exception { + RoleAccessDecisionManager manager = new RoleAccessDecisionManager(keyDao,permissionDao); + http.authorizeRequests() + .accessDecisionManager(manager) + .antMatchers( + "/login/sendCaptcha.do", + // "/login/login.do", + "/login/check.do" + ) + .permitAll() + .anyRequest() + .authenticated() + ; + + http.formLogin() + .usernameParameter(loginParam) + .loginProcessingUrl("/login/login.do") + .loginPage("/") + .successHandler(new AuthenticationSuccessHandler() { + @Override + public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { + System.out.println("login success"); + httpServletResponse.setStatus(HttpServletResponse.SC_OK); + + } + }) + .failureHandler(new AuthenticationFailureHandler() { + @Override + public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { + System.out.println("login fail"); + } + }) + .permitAll(); + http.logout() + .logoutUrl("/login/logout.do") + .logoutSuccessUrl("/") + .logoutSuccessHandler(new LogoutSuccessHandler() { + @Override + public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { + JSONObject json = new JSONObject(); + json.put("code", 0); + json.put("msg", "退出成功"); + httpServletResponse.setStatus(HttpServletResponse.SC_OK); + httpServletResponse.getWriter().write(json.toJSONString()); + } + }) + .deleteCookies("login") + .permitAll(); + + http.exceptionHandling() + .accessDeniedHandler(new AccessDeniedHandler() { + @Override + public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { + JSONObject json = new JSONObject(); + json.put("code", 403); + json.put("msg", "You have no authority."); + httpServletResponse.getWriter().write(json.toJSONString()); + } + }); + + + http.rememberMe() + .rememberMeParameter("login") + .tokenValiditySeconds(60*60*60*24*30); +// http.userDetailsService(new UserDetailsServiceManager()); + http.csrf().disable(); + http.cors(); + } + +} diff --git a/src/main/java/com/yutou/tools/AuthConfig/MyAuthenticationProvider.java b/src/main/java/com/yutou/tools/AuthConfig/MyAuthenticationProvider.java new file mode 100644 index 0000000..4c3042b --- /dev/null +++ b/src/main/java/com/yutou/tools/AuthConfig/MyAuthenticationProvider.java @@ -0,0 +1,86 @@ +package com.yutou.tools.AuthConfig; + +import com.yutou.tools.Tools.GoogleAccount; +import com.yutou.tools.mybatis.dao.UKeyDao; +import com.yutou.tools.mybatis.model.UKey; +import com.yutou.tools.mybatis.model.UKeyExample; +import com.yutou.tools.utils.ConfigTools; +import com.yutou.tools.utils.RedisTools; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +@Component +public class MyAuthenticationProvider implements AuthenticationProvider { + @Resource + UKeyDao keyDao; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + System.out.println("验证账号?"+authentication.getName()); + String secret= (String) ConfigTools.load(ConfigTools.DATA,"secret"); + if(new GoogleAccount().check_code(secret,Long.parseLong(authentication.getName()),System.currentTimeMillis())){ + System.out.println("登陆成功"); + System.out.println(authentication.getAuthorities()); + LoginSuccessAuthentication successAuthentication=new LoginSuccessAuthentication("admin",AuthorityUtils.createAuthorityList("ROLE_USER")); + successAuthentication.setDetails(authentication.getDetails()); + return successAuthentication; + } + UKeyExample example=new UKeyExample(); + example.createCriteria().andKeyEqualTo(authentication.getName()); + List list=keyDao.selectByExample(example); + if(!list.isEmpty()){ + LoginSuccessAuthentication successAuthentication=new LoginSuccessAuthentication(authentication.getName(),AuthorityUtils.createAuthorityList("ROLE_USER")); + successAuthentication.setDetails(authentication.getDetails()); + return successAuthentication; + } + String redis= RedisTools.get(authentication.getName()); + if(redis!=null&&!"-999".equals(redis)){ + LoginSuccessAuthentication successAuthentication=new LoginSuccessAuthentication(authentication.getName(),AuthorityUtils.createAuthorityList("ROLE_USER")); + successAuthentication.setDetails(authentication.getDetails()); + return successAuthentication; + } + System.out.println(authentication); + System.out.println("登陆失败"); + return null; + } + + @Override + public boolean supports(Class aClass) { + System.out.println(UsernamePasswordAuthenticationToken.class); + return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass); + } + static class LoginSuccessAuthentication extends AbstractAuthenticationToken { + String code; + + public LoginSuccessAuthentication( String code,Collection authorities) { + super(authorities); + this.code = code; + } + + @Override + public Object getCredentials() { + return "NotPassword"; + } + + @Override + public Object getPrincipal() { + return code; + } + + @Override + public boolean isAuthenticated() { + return true; + } + } +} diff --git a/src/main/java/com/yutou/tools/AuthConfig/RoleAccessDecisionManager.java b/src/main/java/com/yutou/tools/AuthConfig/RoleAccessDecisionManager.java new file mode 100644 index 0000000..21d2b3a --- /dev/null +++ b/src/main/java/com/yutou/tools/AuthConfig/RoleAccessDecisionManager.java @@ -0,0 +1,105 @@ +package com.yutou.tools.AuthConfig; + +import com.alibaba.fastjson.JSONArray; +import com.yutou.tools.mybatis.dao.PermissionDao; +import com.yutou.tools.mybatis.dao.UKeyDao; +import com.yutou.tools.mybatis.model.Permission; +import com.yutou.tools.mybatis.model.PermissionExample; +import com.yutou.tools.mybatis.model.UKey; +import com.yutou.tools.mybatis.model.UKeyExample; +import com.yutou.tools.utils.RedisTools; +import com.yutou.tools.utils.Tools; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.AccessDecisionManager; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.access.ConfigAttribute; +import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.FilterInvocation; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.List; + +@Component +public class RoleAccessDecisionManager implements AccessDecisionManager { + UKeyDao keyDao; + PermissionDao permissionDao; + + @Autowired + public RoleAccessDecisionManager(UKeyDao keyDao, PermissionDao permissionDao) { + this.keyDao = keyDao; + this.permissionDao = permissionDao; + } + + + @Override + public void decide(Authentication authentication, Object o, Collection collection) throws AccessDeniedException, InsufficientAuthenticationException { + String url= ((FilterInvocation) o).getHttpRequest().getRequestURI(); + String token=((FilterInvocation) o).getHttpRequest().getParameter("token"); + String musicShare=((FilterInvocation) o).getHttpRequest().getParameter("share"); + + switch (url){ + case "/login/sendCaptcha.do": + case "/login/check.do": + return; + } + if(!Tools.isAdminLogin()){ + String redis=RedisTools.get(musicShare); + System.out.println("分享token="+musicShare+" redis="+redis); + if(redis!=null&&!"-999".equals(redis)){ + authentication.setAuthenticated(true); + return; + } + if(token==null){ + error(); + return; + } + try { + url = url.split(url.split("/")[url.split("/").length - 1])[0]; + } catch (Exception e) { + error(); + return; + } + UKeyExample example = new UKeyExample(); + example.createCriteria().andKeyEqualTo(token); + List list = keyDao.selectByExample(example); + if(list.isEmpty()){ + error(); + return; + } + UKey key = list.get(0); + JSONArray powers = JSONArray.parseArray(key.getPower()); + if(powers.toJavaList(String.class).contains("-1")){ + return; + } + PermissionExample pExample = new PermissionExample(); + pExample.createCriteria().andUrlEqualTo(url); + List permissions = permissionDao.selectByExample(pExample); + if (!permissions.isEmpty()) { + if (!powers.toJavaList(String.class).contains(permissions.get(0).getId()+"")) { + error(); + }else{ + authentication.setAuthenticated(true); + } + }else{ + error(); + } + } + } + + private void error() { + System.out.println("无权限跳转"); + throw new AccessDeniedException("/"); + } + + @Override + public boolean supports(ConfigAttribute configAttribute) { + return true; + } + + @Override + public boolean supports(Class aClass) { + return true; + } +} diff --git a/src/main/java/com/yutou/tools/AuthConfig/UserDetailsServiceManager.java b/src/main/java/com/yutou/tools/AuthConfig/UserDetailsServiceManager.java new file mode 100644 index 0000000..7b600ff --- /dev/null +++ b/src/main/java/com/yutou/tools/AuthConfig/UserDetailsServiceManager.java @@ -0,0 +1,16 @@ +package com.yutou.tools.AuthConfig; + +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Component; + +@Component +public class UserDetailsServiceManager implements UserDetailsService { + @Override + public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { + return new User("admin","NotPassword", AuthorityUtils.createAuthorityList("ROLE_USER")); + } +} diff --git a/src/main/java/com/yutou/tools/ToolsApplication.java b/src/main/java/com/yutou/tools/ToolsApplication.java index 9841d68..662dfc2 100644 --- a/src/main/java/com/yutou/tools/ToolsApplication.java +++ b/src/main/java/com/yutou/tools/ToolsApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ToolsApplication { - public static final String version="1.1.5"; + public static final String version="1.2"; public static void main(String[] args) { System.out.println("当前版本号:" + version); diff --git a/src/main/java/com/yutou/tools/interfaces/DownloadInterface.java b/src/main/java/com/yutou/tools/interfaces/DownloadInterface.java index 88be92a..240ebe3 100644 --- a/src/main/java/com/yutou/tools/interfaces/DownloadInterface.java +++ b/src/main/java/com/yutou/tools/interfaces/DownloadInterface.java @@ -3,4 +3,5 @@ package com.yutou.tools.interfaces; public abstract class DownloadInterface { public void onDownload(String file){}; public void onError(Exception e){}; + public void onDownloading(double soFarBytes, double totalBytes){}; } diff --git a/src/main/java/com/yutou/tools/nas/NasManager.java b/src/main/java/com/yutou/tools/nas/NasManager.java index b7745d3..6c78abc 100644 --- a/src/main/java/com/yutou/tools/nas/NasManager.java +++ b/src/main/java/com/yutou/tools/nas/NasManager.java @@ -6,7 +6,9 @@ import com.yutou.tools.mybatis.dao.NasAdminAddressDao; import com.yutou.tools.mybatis.model.NasAdminAddress; import com.yutou.tools.mybatis.model.NasAdminAddressExample; import com.yutou.tools.utils.ConfigTools; +import com.yutou.tools.utils.HttpTools; import com.yutou.tools.utils.RedisTools; +import com.yutou.tools.utils.Tools; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; @@ -17,10 +19,14 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; import java.util.List; +import java.util.UUID; @Controller public class NasManager { + public static final String NasUrl="http://yutou233.cn"; @Resource NasAdminAddressDao adminAddressDao; @ResponseBody @@ -159,8 +165,55 @@ public class NasManager { @ResponseBody public String getLocalHost() { JSONObject json = new JSONObject(); - json.put("data", "http://" + UpdateIp.nas_ip); + if("dev".equals(ConfigTools.load(ConfigTools.CONFIG, "model"))){ + json.put("data", NasUrl+":8001"); + }else { + json.put("data", "http://yutou233.cn:8001"); + } json.put("code", 0); return json.toJSONString(); } + @ResponseBody + @RequestMapping("/nas/music/share.do") + public JSONObject share(String file){ + JSONObject json=new JSONObject(); + String token= Tools.getMD5(UUID.randomUUID() +file); + json.put("token",token); + json.put("file",file); + HashMap header=new HashMap<>(); + header.put("content-type","application/json"); + String data=HttpTools.http_post(NasUrl+":8001/nas/music/share.do",json.toJSONString().getBytes(StandardCharsets.UTF_8),1,header); + System.out.println("分享:"+data); + JSONObject _data=JSONObject.parseObject(data); + RedisTools.set(token,data,3600); + System.out.println("设置分享token:"+token+" -> "+data); + _data.put("token",token); + json.clear(); + json.put("code",0); + json.put("msg","ok"); + json.put("data",_data); + return json; + } + @ResponseBody + @RequestMapping("/nas/music/playShare.do") + public JSONObject playShare(String share){ + JSONObject json=new JSONObject(); + String redis=RedisTools.get(share); + if(redis!=null&&!"-999".equals(redis)) { + String _json=HttpTools.get(NasUrl+":8001/nas/music/playShare.do?token="+JSONObject.parseObject(redis).getJSONObject("data").getString("share")); + System.out.println(_json); + JSONObject item=JSONObject.parseObject(_json); + if(item.getInteger("code")==0) { + json.put("code", 0); + json.put("data", item.getJSONObject("data").getString("file")); + }else{ + json.put("code","-1"); + json.put("msg","分享已过期"); + } + }else{ + json.put("code","-2"); + json.put("msg","连接错误"); + } + return json; + } } diff --git a/src/main/java/com/yutou/tools/other/tools.java b/src/main/java/com/yutou/tools/other/tools.java index 923d241..4e837f7 100644 --- a/src/main/java/com/yutou/tools/other/tools.java +++ b/src/main/java/com/yutou/tools/other/tools.java @@ -126,29 +126,30 @@ public class tools { } return RedisTools.get("request"); } + @RequestMapping("/public/video.do") - public ResponseEntity getVideo(){ + public ResponseEntity getVideo() { return Tools.getFile(new File("Z:\\download\\anim\\鬼灭之刃\\[BeanSub&FZSD&LoliHouse] Kimetsu no Yaiba - 07 [WebRip 1080p HEVC-10bit AAC ASSx2]\\[BeanSub&FZSD&LoliHouse] Kimetsu no Yaiba - 07 [WebRip 1080p HEVC-10bit AAC ASSx2].mkv")); } + //ffmpeg -i "[NC-Raws] 小林家的龙女仆S - 01 [B-Global][WEB-DL][2160p][AVC AAC][CHS_CHT_ENG_TH_SRT][MKV].mkv" -vn -an -map 0:2 sub2.srt @RequestMapping("/public/sub.srt") - public ResponseEntity getVideoSub(){ + public ResponseEntity getVideoSub() { return Tools.getFile(new File("Z:\\download\\anim\\鬼灭之刃\\[BeanSub&FZSD&LoliHouse] Kimetsu no Yaiba - 07 [WebRip 1080p HEVC-10bit AAC ASSx2].SC.ass")); } @RequestMapping("/tools/server.do") @ResponseBody - public String sendServer(String title,String msg){ - Tools.sendServer(title,msg); + public String sendServer(String title, String msg) { + Tools.sendServer(title, msg); return "ok"; } public int getUid(HttpServletRequest request) { String token = request.getParameter("token"); - Cookie cookie = Tools.getCookie(request, "user"); - if (StringUtils.isEmpty(token) && cookie != null) { - if ("ok".equals(RedisTools.get(cookie.getValue()))) { + if (StringUtils.isEmpty(token)) { + if (Tools.isAdminLogin()) { return 1; } } diff --git a/src/main/java/com/yutou/tools/utils/AuthConfig.java b/src/main/java/com/yutou/tools/utils/AuthConfig.java deleted file mode 100644 index 1d45537..0000000 --- a/src/main/java/com/yutou/tools/utils/AuthConfig.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.yutou.tools.utils; - -import com.alibaba.fastjson.JSONObject; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.access.AccessDeniedHandler; -import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; - -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -@Configuration -@EnableWebSecurity -public class AuthConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - //super.configure(http); - http.authorizeRequests() - .antMatchers("/", - "/login/sendCaptcha.do", - "/login/login.do", - "/login/check.do" - ) - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin() - .loginPage("/index.html") - .and() - .exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() { - @Override - public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { - System.out.println("accessDeniedHandler"); - - } - }).and().exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() { - @Override - public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { - System.out.println("无权限"); - JSONObject json = new JSONObject(); - json.put("code", 403); - json.put("msg", "You have no authority."); - httpServletResponse.getWriter().write(json.toJSONString()); - } - }) - ; - - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - super.configure(auth); - System.out.println("wt?"); - } -} diff --git a/src/main/java/com/yutou/tools/utils/CorsConfig.java b/src/main/java/com/yutou/tools/utils/CorsConfig.java index 0e1d8ad..6d93f51 100644 --- a/src/main/java/com/yutou/tools/utils/CorsConfig.java +++ b/src/main/java/com/yutou/tools/utils/CorsConfig.java @@ -1,28 +1,22 @@ package com.yutou.tools.utils; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -public class CorsConfig { - @Bean - public FilterRegistrationBean corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - config.setAllowCredentials(true); - // 设置你要允许的网站域名,如果全允许则设为 * - config.addAllowedOrigin("*"); - // 如果要限制 HEADER 或 METHOD 请自行更改 - config.addAllowedHeader("*"); - config.addAllowedMethod("*"); - source.registerCorsConfiguration("/**", config); - FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); - // 这个顺序很重要哦,为避免麻烦请设置在最前 - bean.setOrder(0); - return bean; +public class CorsConfig implements WebMvcConfigurer { + @Override + public void addCorsMappings(CorsRegistry registry) { + //设置允许跨域的路径 + registry.addMapping("/**") + //设置允许跨域请求的域名 + .allowedOrigins("*") + //是否允许证书 不再默认开启 + .allowCredentials(true) + //设置允许的方法 + .allowedMethods("*") + //跨域允许时间 + .maxAge(3600); } } \ No newline at end of file diff --git a/src/main/java/com/yutou/tools/utils/HttpTools.java b/src/main/java/com/yutou/tools/utils/HttpTools.java index 6d32ca8..91c9834 100644 --- a/src/main/java/com/yutou/tools/utils/HttpTools.java +++ b/src/main/java/com/yutou/tools/utils/HttpTools.java @@ -1,22 +1,43 @@ package com.yutou.tools.utils; import com.alibaba.fastjson.JSONObject; -import com.yutou.tools.utils.Interfaces.NetworkInterface; +import com.yutou.tools.interfaces.DownloadInterface; +import org.springframework.util.StringUtils; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; +import java.net.URLConnection; import java.net.URLEncoder; +import java.util.Map; import java.util.Set; public class HttpTools { + private static final int HttpRequestIndex = 3; + public static String get(String url) { + return https_get(url, null); + } + + public static String post(final String url, final byte[] body) { + return http_post(url, body, 0, null); + } + + public static File syncDownload(final String url, final String saveName) { + return new HttpTools().http_syncDownload(url, saveName); + } + + public static String https_get(String url, Map header) { try { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", getKuKuUA()); + URLConnection connection; + connection = new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", getExtUa()); + if (header != null) { + for (String key : header.keySet()) { + connection.addRequestProperty(key, header.get(key)); + } + } + connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder str = new StringBuilder(); String tmp; @@ -24,59 +45,57 @@ public class HttpTools { str.append(tmp); } reader.close(); - connection.disconnect(); return str.toString(); } catch (Exception e) { + System.err.println("error url = " + url); e.printStackTrace(); } return null; } - public static void post(final String url, final byte[] body, final NetworkInterface networkInterface) { - - new Thread(new Runnable() { - - @Override - public void run() { - String tmp; - StringBuilder str = new StringBuilder(); - try { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setConnectTimeout(5 * 1000); - connection.setReadTimeout(10 * 1000); - //connection.addRequestProperty("Connection", "keep-alive"); - //connection.addRequestProperty("User-Agent", getExtUa()); - //connection.addRequestProperty("content-type", "application/json"); - connection.addRequestProperty("charset", "UTF-8"); - OutputStream outputStream = connection.getOutputStream(); - - outputStream.write(body); - outputStream.flush(); - outputStream.close(); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - while ((tmp = reader.readLine()) != null) { - str.append(tmp); - } - final String finalStr = str.toString(); - - // Log.i(TAG + "[" + url + "?" + toGetSplice(body) + "]", "body:" + str + " (" + connection.getResponseCode() + ")"); - if (networkInterface != null) { - try { - networkInterface.httpGetData(str.toString(), connection.getResponseCode()); - } catch (IOException e) { - e.printStackTrace(); - } - } - connection.disconnect(); - reader.close(); - } catch (Exception e) { - e.printStackTrace(); + public static String http_post(String url, byte[] body, int index, Map headers) { + String tmp; + StringBuilder str = new StringBuilder(); + try { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestMethod("POST"); + if (headers != null) { + for (String key : headers.keySet()) { + connection.addRequestProperty(key, headers.get(key)); } } - }).start(); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.addRequestProperty("User-Agent", getExtUa()); + connection.setConnectTimeout(5 * 1000); + connection.setReadTimeout(10 * 1000); + //connection.addRequestProperty("Connection", "keep-alive"); + //connection.addRequestProperty("User-Agent", getExtUa()); + //connection.addRequestProperty("content-type", "application/json"); + connection.addRequestProperty("charset", "UTF-8"); + OutputStream outputStream = connection.getOutputStream(); + //System.out.println(new String(body)); + outputStream.write(body); + outputStream.flush(); + outputStream.close(); + connection.connect(); + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + while ((tmp = reader.readLine()) != null) { + str.append(tmp); + } + String finalStr = str.toString(); + + connection.disconnect(); + reader.close(); + return finalStr; + } catch (Exception e) { + if (index < HttpRequestIndex) { + return http_post(url, body, index + 1, headers); + } else { + e.printStackTrace(); + return null; + } + } } private static String getExtUa() { @@ -126,7 +145,115 @@ public class HttpTools { } }); }*/ - System.out.println(url); - //String str=get(url); } + + private static String donwloadPath = "tmp" + File.separator; + + public synchronized static void download(final String url, final String saveName, final DownloadInterface downloadInterface) { + new Thread(new Runnable() { + @Override + public void run() { + File jar = null; + try { + File savePath = new File(donwloadPath); + if (!savePath.exists()) { + savePath.mkdirs(); + } + Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.addRequestProperty("User-Agent", getExtUa()); + // Log.i(TAG,"获取到网络请求:"+connection.getResponseCode()); + + + InputStream inputStream = connection.getInputStream(); + jar = new File(donwloadPath + saveName + "_tmp.tmp"); + jar.createNewFile(); + Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath()); + OutputStream outputStream = new FileOutputStream(jar); + byte[] bytes = new byte[1024]; + double size = connection.getContentLength(); + double downSize = 0; + int len; + while ((len = inputStream.read(bytes)) > 0) { + outputStream.write(bytes, 0, len); + downSize += len; + if (downloadInterface != null) { + downloadInterface.onDownloading(downSize, size); + } + } + outputStream.close(); + inputStream.close(); + File oldJar = new File(donwloadPath + saveName); + if (oldJar.exists()) { + oldJar.delete(); + } + jar.renameTo(oldJar); + Log.i("DOWNLOAD", "实际保存:" + oldJar.getAbsolutePath() + " " + oldJar.getName()); + if (downloadInterface != null) { + downloadInterface.onDownload(oldJar.getAbsolutePath()); + + } + + } catch (Exception e) { + e.printStackTrace(); + if (jar != null) { + jar.delete(); + } + if (downloadInterface != null) { + downloadInterface.onError(e); + } + } + } + }).start(); + } + + public synchronized File http_syncDownload(final String url, final String saveName) { + if (StringUtils.isEmpty(url)) { + return null; + } + File jar = null; + try { + File savePath = new File(donwloadPath); + if (!savePath.exists()) { + savePath.mkdirs(); + } + Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.addRequestProperty("User-Agent", getExtUa()); + // Log.i(TAG,"获取到网络请求:"+connection.getResponseCode()); + + + InputStream inputStream = connection.getInputStream(); + jar = new File(donwloadPath + saveName + "_tmp.tmp"); + jar.createNewFile(); + Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath()); + OutputStream outputStream = new FileOutputStream(jar); + byte[] bytes = new byte[1024]; + double size = connection.getContentLength(); + double downSize = 0; + int len; + while ((len = inputStream.read(bytes)) > 0) { + outputStream.write(bytes, 0, len); + downSize += len; + } + outputStream.close(); + inputStream.close(); + File oldJar = new File(donwloadPath + saveName); + if (oldJar.exists()) { + oldJar.delete(); + } + connection.disconnect(); + jar.renameTo(oldJar); + Log.i("DOWNLOAD", "实际保存:" + oldJar.getAbsolutePath() + " " + oldJar.getName()); + return oldJar; + + } catch (Exception e) { + e.printStackTrace(); + if (jar != null) { + jar.delete(); + } + return null; + } + } + } diff --git a/src/main/java/com/yutou/tools/utils/Log.java b/src/main/java/com/yutou/tools/utils/Log.java new file mode 100644 index 0000000..3387d6e --- /dev/null +++ b/src/main/java/com/yutou/tools/utils/Log.java @@ -0,0 +1,15 @@ +package com.yutou.tools.utils; + +public class Log { + public static void i(String tag, Object log) { + i('[' + tag + ']' + log); + } + + public static void i(Object log) { + System.out.printf("[%s]%s%n", + Tools.getToDayNowTimeToString(), + log + ); + + } +} diff --git a/src/main/java/com/yutou/tools/utils/Tools.java b/src/main/java/com/yutou/tools/utils/Tools.java index cc2efca..2d46409 100644 --- a/src/main/java/com/yutou/tools/utils/Tools.java +++ b/src/main/java/com/yutou/tools/utils/Tools.java @@ -3,6 +3,7 @@ package com.yutou.tools.utils; import com.alibaba.fastjson.JSONArray; import com.yutou.tools.interfaces.DownloadInterface; import com.yutou.tools.nas.UpdateIp; +import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.annotation.AnnotationUtils; @@ -11,6 +12,8 @@ import org.springframework.core.type.filter.TypeFilter; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -34,6 +37,7 @@ import java.text.SimpleDateFormat; import java.util.*; public class Tools { + /** * 设置Cookie * @@ -99,8 +103,7 @@ public class Tools { try { System.out.println("title=" + title + " msg=" + msg); HttpTools.post("https://sctapi.ftqq.com/SCT2619Tpqu93OYtQCrK4LOZYEfr2irm.send", - ("title="+URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(msg, "UTF-8")).getBytes(StandardCharsets.UTF_8), - null); + ("title="+URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(msg, "UTF-8")).getBytes(StandardCharsets.UTF_8)); if (!StringUtils.isEmpty(UpdateIp.nas_ip)) { String img = null; msg = msg.replace("
", "\n"); @@ -425,4 +428,24 @@ public class Tools { } return urls; } + public static String getLoginUser(){ + Object user= SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + if(user instanceof String){ + return (String) user; + }else { + return ((User)user).getUsername(); + } + } + public static boolean isAdminLogin(){ + return "admin".equals(getLoginUser()); + } + + public static String getMD5(String str){ + return DigestUtils.md5Hex(str); + } + + public static String getToDayNowTimeToString() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + } + } diff --git a/src/main/java/com/yutou/tools/web/userController.java b/src/main/java/com/yutou/tools/web/userController.java index 4790d63..940ec42 100644 --- a/src/main/java/com/yutou/tools/web/userController.java +++ b/src/main/java/com/yutou/tools/web/userController.java @@ -6,6 +6,8 @@ import com.yutou.tools.Tools.GoogleAccount; import com.yutou.tools.utils.ConfigTools; import com.yutou.tools.utils.RedisTools; import com.yutou.tools.utils.Tools; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.FilterInvocation; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; @@ -17,6 +19,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; +import java.util.Map; import java.util.UUID; @Controller @@ -25,30 +28,24 @@ public class userController { @RequestMapping("/login/check.do") @ResponseBody public String getLoginState(HttpServletRequest request) { + String share=request.getParameter("share"); JSONObject json = new JSONObject(); json.put("code", -1); json.put("msg", "未登录"); - JSONArray array = new JSONArray(); - if (RedisTools.get("ban") != null) { - array = JSONArray.parseArray(RedisTools.get("ban")); - } - if (array.contains(Tools.getRemoteAddress(request))) { - json.put("code", -2); - json.put("msg", "未登录"); - System.out.println("IP已被封禁"); - return json.toJSONString(); - } - Cookie cookie = Tools.getCookie(request, "user"); - if (cookie == null) { - return json.toJSONString(); - } - if ("ok".equals(RedisTools.get(cookie.getValue()))) { + if (Tools.isAdminLogin()) { json.put("code", 0); json.put("msg", "登录成功"); return json.toJSONString(); } - json.put("code", -1); - json.put("msg", "未登录"); + + String redis=RedisTools.get(share); + if(redis!=null&&!"-999".equals(redis)){ + json.put("code", -2); + json.put("msg", "临时账号"); + }else { + json.put("code", -1); + json.put("msg", "未登录"); + } return json.toJSONString(); } diff --git a/web/html/body/nas/music.html b/web/html/body/nas/music.html index 4f46bc9..045004c 100644 --- a/web/html/body/nas/music.html +++ b/web/html/body/nas/music.html @@ -55,6 +55,7 @@