#!/usr/bin/python
# -*- coding: utf-8 -*-

##########################################################
#  adapted to implement gridmap based authentication     
#  needs: 
#        /etc/grid-security/grid-mapfile
#         (created by edg-mkgridmap)
#        /etc/grid-security/accessfile
#  access file contains lines like:
#     /myfed/S3-Atlas atlas rl
#  meaning:
#     authorization is for /myfed/S3-Atlas and below
#     authorization is for anyone in VO atlas
#     authorization is for read and list access
#
#     top level /myfed can be read/listed by anyone
#
#  multiple entries for the same certificate but for 
#  different VOs in grid-mapfile are allowed
#
##########################################################
# version 1, May 2017, M.Ebert, mebert@uvic.ca
#  
#
##########################################################

import sys

# A class that one day may implement an authorization list loaded
# from a file during the initialization of the module.
# If this list is written only during initialization, and used as a read-only thing
# no synchronization primitives (e.g. semaphores) are needed, and the performance will be maximized
class _Authlist(object):
    def __init__(self):
        print "I claim I am loading an authorization list from a file, maybe one day I will but ignored for now :-)"

# Initialize a global instance of the authlist class, to be used inside the isallowed() function
myauthlist = _Authlist()


# The main function that has to be invoked from ugr to determine if a request
# has to be performed or not
def isallowed(clientname="unknown", remoteaddr="nowhere", resource="none", mode="0", fqans=None, keys=None):
    #print "clientname", clientname
    #print "remote address", remoteaddr
    #print "fqans", fqans
    #print "keys", keys
    #print "mode", mode
    #print "resource", resource

    path = resource.split('/')
    if(path[-1] == ''):
      del path[-1]
    if(path[0] == ''):
      del path[0]
    # Allow to list the top level directory by everyone
    # "<=2" needs to be adjusted for the own installation
    # could also be combined with "clientname" or removed if not wanted
    # remove "else" part if authorized people need to write to that area too
    if (len(path) <= 2):
      if (mode == 'r' or mode == 'l'):
        return 0
      else:
        return 1

    # deny to anonymous user if not allowed so far
    if (clientname == 'nobody'):
      return 1

    # allow anyone else who is not nobody access according to the accessfile
    with open('/etc/grid-security/grid-mapfile') as search:
	for line in search:
		if clientname in line:
			fqans = line.split()[-1]
			with open('/etc/grid-security/accessfile') as access:
				for line in access:
					#print "Resource:", resource
					#print "Line: ", line
					#print "Split: ", line.split()[0]
					if line.split()[0] in resource:
						accessFQAN = line.split()[1]
						accesskeys = line.split()[2]
						if (accessFQAN in fqans) and (mode in accesskeys):
							#print "Name:", clientname
							#print "FQAN:", fqans, "  ", accessFQAN
							#print "Mode:", mode, "   ", accesskeys
							#print "Resource ok:", resource
							return 0
			access.close()
    search.close()
    return 1


#------------------------------
if __name__ == "__main__":
    r = isallowed(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5:])
    sys.exit(r)
