#! /usr/local/bin/perl
#
#   Akenti version
# 
#   Akenti_chk_access uses the SSL_CLIENT_DN env var and the Akenti
#       inteface module akenti_chk_acc to check a user's privileges
#     Akenti_chk_access called by createdir.pl, delcol, 
#             deletefiles.pl, makeindex,
#             editlist, edrecord, linkobj.pl, mvobj.pl, stagelist
#
#   Akenti_wr_policy Writes .htauthority file
#     Akenti_wr_htaccess called by edform. Rewrites a .htauthority file
#
# usage
#    &Akenti_wr_policy(directory, AuthUserFile, AuthGrpFile, usr|group, 
#                 READ|WRITE|HIRES);
#         directory is the directory to put the new htaccess file in
#         AuthUserFile and AuthGrpFile are put in the htaccess file
#         usr|grp may be a comma separated list of users and/or groups
#           all of which must exist
#    &Akenti_chk_access(directory)  returns the privileges allowed.
#

require 'definitions.pl';

sub Akenti_wr_policy {
    local ($dirname,@CertDir,@UCCAIs,@UCs) = @_;

    unless ( open (HTA, ">$dirname$HTACCESS")) {
	&report_status("Error","wr_htaccess","Can't open file $dirname$HTACCESS");
	return (1);
    }
    foreach $value (@CertDir) {
	print HTA "CertificateDirectory $value\n";
    }
    foreach $value (@UCCAIs){
	print HTA "UseConditionCAandIssuer $value\n";
    }
    foreach $value (@UCs){
	print HTA "UseCondRequired $value\n";
    }
    close HTA;
    return(0);
}

# checks to see if the SSL_CLIENT_DN  has access to $dirname
# $dirname should be relative to the document root:$URLbasedir
# A list of the allowed actions is returned

$akenti_chk_acc = "$URLbasedir$SCRIPTdir/akenti_chk_acc";

$NOTALLOWED = "none";
sub Akenti_chk_access {
   local ($dirname) = @_;
   local (@privs);

    #if no directory return no access
    if (! -d "$URLbasedir$dirname") { 
	&report_status("Not a dir","Akenti_chk_access","$URLbasedir$dirname");
	return $NOTALLOWED;}

   $DN = $ENV{SSL_CLIENT_DN};
   if ($DN eq "") { 
	&report_status("no DN","Akenti_chk_access","$DN");

       return $NOTALLOWED;}


   $authfile = substr($HTACCESS,1);
   # Make sure dirname does not start with a /, but does end with a /
   $dirname =~ s/^\/+//;
   if ($dirname ne "") {
       if ( substr($dirname,-1) ne "/") {
	   $dirname .= "/";
       }
   }
   ($protocol,$host) = split(/:\/\//,$IMGLIBURL);
   # print "calling $akenti_chk_acc -t W -n \"$DN\" -r $dirname -f $AkentiConf\n";
   if (! open (ACC, "$akenti_chk_acc -t W -n \"$DN\" -r $dirname -f $AkentiConf |")){
       &report_status("Error","Akenti_chk_access","open of $akenti_chk_acc failed");
       return $NOTALLOWED;
   }
   while (<ACC>){
       ($key,$rest)=split(/:/);
       if ($key eq "Allowed actions") {
	   @privs=split(/,/,$rest);
	   #print  "Akenti_chk_acesss actions are: @privs from $rest";
	   close ACC;
	   return @privs;
       }
   }
   close ACC;
   return $NOTALLOWED;
}
1;

