package com.quant.comm;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

@Component
public class LoginSecret {
	@Resource
	private ReadPro readPro;
	

	public static String getCookie(HttpServletRequest request,HttpServletResponse response, String key) {

		Cookie[] cookies = request.getCookies();
		if(cookies==null){
//			try {
//				response.sendRedirect(request.getContextPath() + "/user/toLoginCheck.do");
//				return "";
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
			return "";
		}
		for (Cookie c : cookies) {
			if (c.getName().trim().equals(key.trim())) {
				return c.getValue();
			}
		}
		return "";
	}

	public static boolean checkCookie(String _id, String _ts, String extra, String token) {
		String checkToken = MD5.GetMD5Code(_id.toString() + "," + _ts.toString() + "," + extra);
		if (checkToken.equals(token)) {
			return true;
		} else {
			return false;
		}
	}

	public boolean valid_user(HttpServletRequest request,HttpServletResponse response) {
		
		String extra = readPro.readProperties("password");
		String _id = LoginSecret.getCookie(request, response,"_id");
		String _ts = LoginSecret.getCookie(request,response, "_ts");
		String token = LoginSecret.getCookie(request, response,"token");
		return LoginSecret.checkCookie(_id, _ts, extra, token);
	}
}