/*

HTTP WWW AUTHENTICATION TEST CGI PROGRAM WIRITTEN IN C++

AUTHOR: Matt Coan
DATE: Tue May  8 23:15:11 EDT 2018

*/

#include "cookie_auth.h"
#include "cgi.h"

using namespace std;
using namespace cgi_tools;

inline
void print_cookie_list()
{
   CookieListType * pCookieList = getCookieList();
   if(pCookieList) {
      for(CookieListType::iterator p = pCookieList->begin();
          p != pCookieList->end(); p++) {
         Cookie * & pCookieRef = (*p);
         cout << pCookieRef->name() << "=" << pCookieRef->value() << endl;
      }
      deleteCookieList(pCookieList);
   }
}
int
main()
{
   CGI form_data;
   const char * the_user = form_data["user"];
   const char * the_pass = form_data["pass"]; 
   if(the_user == 0) the_user = "";
   if(the_pass == 0) the_pass = "";
   string user = the_user, pass = the_pass;
   if(cookie_auth(user, pass, 60 * 10)) {
      cout << "Content-type: text/html\r\n\r\n" << flush;
      cout << "<HTML>" << endl;
      cout << "<HEAD>" << endl;
      cout << "<TITLE>" << endl;
      cout << "Cookie Athorized..." << endl;
      cout << "</TITLE>" << endl; 
      cout << "</HEAD>" << endl;
      cout << "<BODY BGCOLOR=\"WHITE\">" << endl;
      cout << "Cookie Athorized..." << endl;
      cout << "<PRE>" << endl;
      cout << "----" << endl;
      system("env");
      cout << "----" << endl;
      print_cookie_list();
      cout << "----" << endl;
      cout << "</PRE>" << endl;
      cout << "</BODY>" << endl;
      cout << "</HTML>" << endl << flush;
   }
   else {
      cout << "Content-type: text/html\r\n\r\n" << flush;
      cout << "<HTML>" << endl;
      cout << "<HEAD>" << endl;
      cout << "<TITLE>" << endl;
      cout << "Error..." << endl;
      cout << "</TITLE>" << endl; 
      cout << "</HEAD>" << endl;
      cout << "<BODY BGCOLOR=\"WHITE\">" << endl;
      cout << "ERROR..." << endl;
      cout << "<FORM METHOD=\"GET\" ACTION=\"/~mcoan/cgi-bin/cookie_auth.cgi\">" << endl;
      cout << "USERNAME: <INPUT TYPE=\"TEXT\" NAME=\"user\"><BR>" << endl;
      cout << "PASSWORD: <INPUT TYPE=\"PASSWORD\" NAME=\"pass\"><BR>" << endl;
      cout << "<INPUT TYPE=\"SUBMIT\" VALUE=\"Run CGI\"><BR>" << endl;
      cout << "</FORM>" << endl;
      cout << "<PRE>" << endl;
      cout << "----" << endl;
      system("env");
      cout << "----" << endl;
      print_cookie_list();
      cout << "----" << endl;
      cout << "</PRE>" << endl;
      cout << "</BODY>" << endl;
      cout << "</HTML>" << endl << flush;
   }
   return 0;
}
