<%@include file="../include/lib.jsp"%>
<%@page import="org.json.simple.*"%>
<%
// Only localhost access allowed.
if(!request.getRemoteAddr().startsWith("127.0.0.1")){
	out.println(request.getRemoteAddr());
	return;
}

// Get params.
String action = paramString("action");
String ip = paramString("ip");
String token = paramString("token");
String uname = paramString("uname");

if(action.equals("ipupdate") && isValidIp(ip) && isNotEmpty(token)){
	UserLoginDao dao = new UserLoginDao(request);
	if(dao.createIpSessionByToken(ip, token)){
		out.print("Login success.");
	}
	else{
		out.print("Login error!");
	}
}
else if(action.equals("createUser") && isNotEmpty(uname)){
	UserData data = new UserData();
	data.name = uname;
	if(new UserDao().insert(data)){
		out.print("User added.");
	}
	else{
		out.print("User not added!");
	}
}
else if(action.equals("selectUser") && isNotEmpty(uname)){
	UserData data = new UserDao().selectOneByName(uname);
	if(data == null){
		out.print("Couldn't find the user!");
		return;
	}

	JSONObject obj = new JSONObject();
	obj.put("name", data.name);
	obj.put("description", data.description);
	obj.put("token", data.token);
	obj.put("expDate", data.getExpDate());
	obj.put("policyName", data.policyName);
	obj.put("ftPolicyName", data.ftPolicyName);
	obj.put("ipLine", data.getIpLine());
	obj.put("groupLine", data.getGroupLine());

	out.print(obj);
}
%>