新增SpringSecurity来认证

新增音乐分享功能
修改跨域代码
http工具改为同步
This commit is contained in:
Yutousama 2021-10-23 13:03:45 +08:00
parent 90af00b235
commit 98da63a0d5
16 changed files with 779 additions and 217 deletions

View File

@ -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();
}
}

View File

@ -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<UKey> 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<? extends GrantedAuthority> authorities) {
super(authorities);
this.code = code;
}
@Override
public Object getCredentials() {
return "NotPassword";
}
@Override
public Object getPrincipal() {
return code;
}
@Override
public boolean isAuthenticated() {
return true;
}
}
}

View File

@ -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<ConfigAttribute> 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<UKey> 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<Permission> 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;
}
}

View File

@ -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"));
}
}

View File

@ -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);

View File

@ -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){};
}

View File

@ -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<String,String> 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;
}
}

View File

@ -126,29 +126,30 @@ public class tools {
}
return RedisTools.get("request");
}
@RequestMapping("/public/video.do")
public ResponseEntity<FileSystemResource> getVideo(){
public ResponseEntity<FileSystemResource> 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<FileSystemResource> getVideoSub(){
public ResponseEntity<FileSystemResource> 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;
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View File

@ -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<String, String> 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,27 +45,28 @@ 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() {
public static String http_post(String url, byte[] body, int index, Map<String, String> 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));
}
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.addRequestProperty("User-Agent", getExtUa());
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(10 * 1000);
//connection.addRequestProperty("Connection", "keep-alive");
@ -52,31 +74,28 @@ public class HttpTools {
//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);
}
final String finalStr = str.toString();
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();
return finalStr;
} catch (Exception e) {
if (index < HttpRequestIndex) {
return http_post(url, body, index + 1, headers);
} else {
e.printStackTrace();
return null;
}
}
}).start();
}
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;
}
}
}

View File

@ -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
);
}
}

View File

@ -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("<br/>", "\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());
}
}

View File

@ -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();
}
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();
}

View File

@ -55,6 +55,7 @@
<script type="text/html" id="music">
<a class="layui-btn layui-btn-xs" lay-event="download">下载</a>
<a class="layui-btn layui-btn-xs" lay-event="play">播放</a>
<a class="layui-btn layui-btn-xs" lay-event="share">分享</a>
</script>
<script>
let localhost = "";
@ -62,24 +63,33 @@
let isRandom = true;
let playIndex = 0;
let playNow = ""
$.get("/nas/music/getlocalhost.do?token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk", function (obj) {
let share=getParam('share');
if(share!=null){
$('#playlist').remove()
$('#reload').remove()
$('#next').remove()
}
$.get("/nas/music/getlocalhost.do",{share:share}, function (obj) {
try {
let json = JSON.parse(obj);
localhost = json.data + ":8000";
console.log("音频地址:" + localhost)
if(json.code===403){
layer.msg('您没有权限访问')
return;
}
localhost = json.data ;
if (localhost === 'http://null:8000' || localhost === ":8000") {
localhost = "http://127.0.0.1"
localhost = "http://"+window.location.host;
}
} catch (e) {
localhost = ""
console.log(e)
}
localhost = "http://120.55.85.10:8001";
layui.use(['table', 'element'], function () {
let table = layui.table;
let element = layui.element;
let listTable = table.render({
elem: '#playlist'
, url: localhost + '/nas/music/list.do?token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk' //数据接口
, url: localhost + '/nas/music/list.do?token=' //数据接口
, method: 'post'
, where: {
path: 'root',
@ -91,9 +101,9 @@
{field: 'title', title: '标题', width: 400, sort: true, templet: "#listTemplet"}
, {field: 'artist', title: '艺术家', width: 200}
, {field: 'album', title: '专辑', width: 200}
, {field: 'composer', title: '作曲', width: 200}
, {field: 'composer', title: '作曲', width: 150}
, {field: 'track', title: '音轨号', width: 100, sort: true}
, {field: "right", width: 150, toolbar: '#music'}
, {field: "right", width: 200, toolbar: '#music'}
]]
, done: function (res, curr, count) {
musicLib = res.data
@ -101,6 +111,7 @@
}
})
table.on('rowDouble(music)', function (obj) {
console.log("双击:"+obj)
//obj 同上
if (obj.data.isdir === 1) {
listTable.reload({
@ -123,7 +134,7 @@
let data = obj.data;
if (obj.event === 'download') {
if (data.isdir === 0) {
window.open(localhost + "/nas/music/play.do?token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk&random=false&filePath=" + new Base64().encode(data.file))
window.open(localhost + "/nas/music/play.do?token=&random=false&filePath=" + new Base64().encode(data.file))
}
} else if (obj.event === 'play') {
$.ajax({
@ -151,6 +162,15 @@
}
})
}else if(obj.event==='share'){
$.post('/nas/music/share.do',{file:data.file},function (json){
if(json.code===0){
layer.prompt({
title:"分享链接",
value:"http://"+window.location.host+"/html/body/nas/music.html?share="+json.data.token
})
}
})
}
});
element.on('nav(menus)', function (elem) {
@ -183,11 +203,14 @@
$('#footer').load("/html/footer.html");
$('#side').load("/html/body/nas/side.html");
$('#img').click(function () {
if(share!==null){
return;
}
isRandom = true;
random()
});
$('#download').click(function () {
window.open(localhost + "/nas/music/play.do?token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk&random=false&filePath=" + playNow)
window.open(localhost + "/nas/music/play.do?token=&random=false&filePath=" + playNow)
});
$('#next').click(function () {
playNext()
@ -222,7 +245,7 @@
if (json.code === 0) {
playNow = json.data
player.updateSource({
source: localhost + "/nas/music/play.do?random=false&filePath=" + json.data + "&token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk"
source: localhost + "/nas/music/play.do?random=false&filePath=" + json.data
});
update(json.data)
player.play()
@ -236,8 +259,9 @@
function play(file) {
let filePath = escape(new Base64().encode(file))
playNow = filePath
console.log(localhost + "/nas/music/play.do?random=false&filePath=" + filePath )
player.updateSource({
source: localhost + "/nas/music/play.do?random=false&filePath=" + filePath + "&token=PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk"
source: localhost + "/nas/music/play.do?random=false&filePath=" + filePath
});
update(filePath)
player.play()
@ -280,7 +304,17 @@
})
$('#img').attr("src",localhost+'/nas/music/web/image.do?fileName='+fileName);
}
function playShare(){
console.log("播放分享:"+share)
$.get('/nas/music/playShare.do?share='+share,function (json) {
isRandom = false;
playIndex =0;
play(json.data)
})
}
if(share!==null){
playShare()
}
</script>
<style>

View File

@ -46,19 +46,55 @@
<script src="/js/qrcode.min.js"></script>
<script src="/layui/layui.js"></script>
<script src="/js/jquery-3.2.1.js"></script>
<script src="/js/myjs.js"></script>
<script>
let loginStatus = false;
$.get("/login/check.do", function (data) {
window.onload=function (){
if(getParam('type')==='login'&&!loginStatus){
onLogin()
}
}
$.get("/login/check.do",{share:getParam("share")}, function (data) {
try {
let json = JSON.parse(data);
console.log(data)
if (json.code === 0) {
$('#login_text').text('已登录')
loginStatus = true;
}else if(json.code===-1&&getParam("type")!=='login'){
window.location.href='/?type=login'
}
}catch (e) {
window.location.href='/'
}
})
$('#login').click(function () {
if (loginStatus) {
return;
}
onLogin()
})
$('#logout').click(function () {
$.post('/login/logout.do', function (data) {
let json = JSON.parse(data);
layer.msg(json.msg)
window.location.href = "/"
})
});
$('#open_pc').click(function () {
layer.open({
title: "远程开机",
content: "确定开机?",
yes: function (index) {
$.post("/tools/openpc.do");
layer.close(index)
}
})
})
function onLogin(){
$.get('/login/sendCaptcha.do', function (data) {
let json = JSON.parse(data);
if (json.code === 1) {
@ -79,12 +115,12 @@
}
})
}
function openLoginCode() {
layer.prompt({
title: '安全登录码'
}, function (value, index, elem) {
$.post('/login/login.do', {code: value}, function (data) {
$.post('/login/login.do', {code: value,"login":true}, function (data) {
let json = JSON.parse(data);
layer.msg(json.msg, function () {
window.location.reload()
@ -93,24 +129,6 @@
layer.close(index);
})
}
})
$('#logout').click(function () {
$.post('/login/logout.do', function (data) {
let json = JSON.parse(data);
layer.msg(json.msg)
window.location.href = "/"
})
});
$('#open_pc').click(function () {
layer.open({
title: "远程开机",
content: "确定开机?",
yes: function (index) {
$.post("/tools/openpc.do");
layer.close(index)
}
})
})
$(document).ready(function () {
let mobile = layui.device().mobile;
if (mobile) {