#ifndef WWW_AUTH_CODE_H
#define WWW_AUTH_CODE_H

/*

HTTP WWW AUTHENTICATION CGI FUNCTION...

APACHE 2.4 CONFIGURATION CODE:

-----------------------------

LoadModule rewrite_module libexec/apache24/mod_rewrite.so

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

<Directory "/home/mcoan/public_html/cgi-bin2/">
   Options ExecCGI
   SetHandler cgi-script
   AuthType Basic
   #AuthType Digest
   AuthName "LOVE REALM"
   AuthUserFile /usr/local/etc/apache24/htpasswd
   Require valid-user
</Directory>

-----------------------------

Author: Matt Coan
Date: Tue May  8 22:14:42 EDT 2018

*/

#include <iostream>
#include <cstdlib>

#include "base64.h"

namespace cgi_tools {

using namespace std;

inline
void http_header(const string & text) 
{
   cout << text << "\r\n" << flush; 
}

inline
bool www_auth(const string & realm,
              const string & the_user,
              const string & the_pass)
{
   bool ret = false;
   string user;
   string pass;
   if(user == "") {
      char * remote_user = getenv("REMOTE_USER");
      if(remote_user) {
         user = remote_user;
      }
   }
   if(getenv("HTTP_AUTHORIZATION") != 0) {
      pass = getenv("HTTP_AUTHORIZATION");
      string::size_type ptr = pass.find(" ");
      if(ptr != string::npos) {
         pass = b64decode(pass.substr(ptr+1));
         ptr = pass.find(":");
         if(ptr != string::npos) {
            user = pass.substr(0, ptr);
            pass = pass.substr(ptr+1);
         }
      }
   }
   if((user + ":" + pass) == (the_user + ":" + the_pass)) {
      ret = true;
   }
   else {
      http_header("Status: 401");
      http_header("WWW-Authenticate: Basic realm=\"" + realm + "\"");
   }
   return ret;
}

}

#endif /* WWW_AUTH_CODE_H */
