#include <http.h>
#include <continuity.h>

int check_user(const char *username, const char *password);
int require_authentication(httpTtrans * t, lstTset * opt);

/* 
 * Check to see if the username and password are valid. 
 * Return 1 if they are, 0 if they are not
 */
int check_user(const char *username, const char *password)
{
    if (strcmp(username, "admin") == 0 && strcmp(password, "pencil") == 0)
        return 1;
    return 0;
}

int require_authentication(httpTtrans * t, lstTset * opt)
{
    char *authorization = lstFset_get(t->req_hdrs, "authorization");
    char b64decode[64];
    int ret;
    char *u = NULL, *p = NULL;
    char *st_p;

    authorization = lstFset_get(t->req_hdrs, "authorization");

    if (authorization != NULL) {
        bzero(b64decode, 64);

        ret =
            b64Fdecode(authorization + 6, (unsigned char *) b64decode,
                       sizeof(b64decode));
        b64decode[ret] = '\0';

        u = strtok_r(b64decode, ":", &st_p);
        p = strtok_r(NULL, ":", &st_p);

        if (u != NULL && p != NULL) {
            ret = check_user(u, p);

            if (ret == 1) {
                lstFset_add(t->vars, "auth-type", "basic");
                lstFset_add(t->vars, "auth-user", u);
                return STATUS_PROCEED;
            }
        }
    }

    /* require authentication */
    httpFset_status(t, HTTP_UNAUTHORIZED, NULL);
    lstFset_add(t->res_hdrs, "WWW-authenticate",
                "basic realm=\"Members Area\"");

    httpFstart_response(t);
    httpFwrite(t, "Authorization required.", 24);

    return STATUS_EXIT;
}
