/////
//
// File : absec_pam.c
// Author : Jean-Luc Cyr
// Date : 2018-10
//
// Description: Using PAM as authentification method
//

#include "absec_authen.h"

#include <security/pam_appl.h>
#include <security/pam_misc.h>


// Global var for passing fake response to PAM callback
struct pam_response *reply;

////////////////////////////////////////////////////////////////
// PAM response callback function
int converse(int n, const struct pam_message **msg,
	struct pam_response **resp, void *data)
{
    // Return globally set response
    *resp = reply;
    return PAM_SUCCESS;
}

////////////////////////////////////////////////////////////////
// define PAM callback function
struct pam_conv conv = { converse, 0 };

int check_user(char* user, char* pass) {
    ////////
    // Connect to PAM to auth user
    pam_handle_t * pamh = NULL;
    int rret;

    if((rret = pam_start("httpd", user, &conv, &pamh)) != PAM_SUCCESS) {
    	return PAM_ERROR_START;
    }

    // Set the PAM callback function response (would call for password)
    reply = (struct pam_response *)malloc(sizeof(struct pam_response));
    reply[0].resp = strdup(pass); // password received in basic auth
    reply[0].resp_retcode = 0;

    if((rret = pam_authenticate(pamh, 0)) != PAM_SUCCESS) {
    	return PAM_ERROR_INVALID_CRED;
    }

    if(pam_end(pamh, rret) != PAM_SUCCESS) {
    }	
}

