#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>
int xauth_user(char *user, char *pass);
int auth_user(char *ipname, char *ipnum, char *user, char *pass	     ,char *postgrps, char *readgrps, char *msg, int bfsz);
char *auth_group(char *user,char *group, int type, char *msg);
#ifndef TRUE
#define FALSE 0
#define TRUE (!FALSE)
#endif


int auth_user(char *ipname, char *ipnum, char *user, char *pass
	     ,char *postgrps, char *readgrps, char *msg, int bfsz);
{
	int r;
	strcpy(msg,""):
	r = xauth_user(user,pass,msg); /* Check against unix passwd file*/
	strncpy(postgrps,"*",bfsz); /* Give full access to all users */
	strncpy(readgrps,"*",bfsz); /* Give full posting access */
	return r;
}

/* This is the standard unix authorization calls, seems
to work on linux and solaris, it probably wont work
if you have any fancy passwd stuff enabled. */

#include <shadow.h>
#include <crypt.h>
int xauth_user(char *user, char *pass, char *msg)
{
    struct spwd *pwd;
    long today;
    char xpass[200];

   	
	/*  Look for the user in the shadow password file */
	if ((pwd = getspnam(user)) == NULL) {
		sprintf(msg,"Account doesn't exist (%s)",user);
		return FALSE;
	}
	today = (long)time((time_t *)NULL)/24/60/60;

	/* Check for expiration date */
	if (pwd->sp_expire > 0 && today > pwd->sp_expire) {
		sprintf(msg,"Account password expired (%s)",user);
		return FALSE;
	}

	/* Check if password is valid */
	if (pwd->sp_max > 0 && today > pwd->sp_lstchg+pwd->sp_max) {
		sprintf(msg,"Account password expired (%s)",user);
		return FALSE;
	}

	if (pwd->sp_pwdp==NULL) {
		sprintf(msg,"Account with no password (%s)",user);
		return TRUE; 
	}
	strcpy(xpass,pwd->sp_pwdp);
	endspent();
	if (strlen(xpass)==0) {
		sprintf(msg,"Account with no password (%s)",user);
		return TRUE; 
	}

	if (strcmp(crypt(pass, xpass), xpass)==0) 
		return TRUE;
/*	if (strcmp(pw_encrypt(pass, xpass), xpass)==0) 
		return TRUE;
*/	sprintf(msg,"Wrong password for user (%s)",user);
	return FALSE;
}

/*----------------------------------------------------------*/
/* This routine MUST be VERY efficient, it will be called
20,000 times when a user does a list command (once for
each group in the active file)
We suggest you construct an internal static array with
hashed lookup for the group name.
Note: you can use auth_user, without implementing auth_group
as auth_user allows simple wild card matching to be used */
enum {T_READ=1,T_POST};
char *auth_group(char *user,char *group, int type, char *msg)
{
	if (type==T_READ) {
		if (strcmp(user,"chrisp")==0) return TRUE;
		if (strcmp(user,"test2")==0) if strcmp(group,"test.one")==0) return TRUE;
		return FALSE;
	}
	if (type==T_POST) {
		if (strcmp(user,"test2")==0) return FALSE;
		return TRUE;
	}
	sprintf(msg,"unknown type %d",type); 
	return FALSE;
}