Ejemplo n.º 1
0
def getUserData():
    userData = []
    username = credentials.getUsername()
    if not username or username == "anonymous":
        userData.append("username : '******'")
    else:
        userData.append("username : '******'" % username)
        userData.append("group : '%s'" % credentials.getSelectedGroup())
        properties = credentials.getProperties(credentials.getSelectedGroup())
        if len(properties) > 0:
            userData.append("groupProperties : %s" % properties)
        else:
            userData.append("groupProperties : []")
        availableGroups = list()
        for groupName in credentials.getAvailableGroups():
            properties = credentials.getProperties(groupName)
            if not len(properties) > 0:
                continue
            if ("Pilot" in properties) or ("GenericPilot" in properties):
                continue
            url = diracURL(controller="web/userdata", action="changeGroup", id=groupName)
            availableGroups.append("{ text : '%s', url : '%s' }" % (groupName, url))
        userData.append("groupMenu : [%s]" % ",".join(availableGroups))
    dn = credentials.getUserDN()
    if not dn:
        if "REQUEST_URI" in request.environ:
            uri = str(request.environ["REQUEST_URI"])
        else:
            uri = ""
        dn = '<a href="https://%s%s">certificate login</a>' % (str(request.environ["HTTP_HOST"]), uri)
    userData.append("DN : '%s'" % dn)
    return "{%s}" % ",".join(userData)
Ejemplo n.º 2
0
def getUserData():
  userData = []
  username = credentials.getUsername()
  if not username or username == "anonymous":
    userData.append( "username : '******'" )
  else:
    userData.append( "username : '******'" % username )
    userData.append( "group : '%s'" % credentials.getSelectedGroup() )
    properties = credentials.getProperties( credentials.getSelectedGroup() )
    if len( properties ) > 0:
      userData.append( "groupProperties : %s" % properties )
    else:
      userData.append( "groupProperties : []" )
    availableGroups = list()
    for groupName in credentials.getAvailableGroups():
      properties = credentials.getProperties( groupName )
      if not len( properties ) > 0:
        continue
      if ( "Pilot" in properties ) or ( "GenericPilot" in properties ):
        continue
      url = diracURL( controller = 'web/userdata',
                      action = 'changeGroup',
                      id = groupName )
      availableGroups.append( "{ text : '%s', url : '%s' }" %
                                ( groupName , url ) )
    userData.append( "groupMenu : [%s]" % ",".join( availableGroups ) )
  dn = credentials.getUserDN()
  if not dn:
    if 'REQUEST_URI' in request.environ:
      uri = str( request.environ[ 'REQUEST_URI' ] )
    else:
      uri = ""
    dn = "<a href=\"https://%s%s\">certificate login</a>" % ( str( request.environ[ 'HTTP_HOST' ] ), uri )
  userData.append( "DN : '%s'" % dn )
  return "{%s}" % ",".join( userData )
Ejemplo n.º 3
0
  def getUserByProperty( self , prop = "NormalUser" ):

    """
    Get usernames based on group property
    Argument is a string. Return value is a list
    """

    groupList = list()
    result = gConfig.getSections( "/Registry/Groups" )
    gLogger.debug( "Group response: %s" % result )
    if not result[ "OK" ]:
      return groupList

    groups = result[ "Value" ]
    for j in groups:
      props = getProperties( j )
      gLogger.debug( "%s properties: %s" % ( j , props ) )
      if prop in props:
        groupList.append( j )

    if not len( groupList ) > 0:
      return groupList
    groupList = uniqueElements( groupList )
    gLogger.debug( "Chosen group(s): %s" % groupList )

    userList = list()
    for i in groupList:
      users = gConfig.getValue( "/Registry/Groups/%s/Users" % i , [] )
      gLogger.debug( "%s users: %s" % ( i , users ) )
      if len( users ) > 0:
        userList.extend( users )

    return userList
Ejemplo n.º 4
0
 def __canRunJobs(self):
     groupPropertie = credentials.getProperties(
         credentials.getSelectedGroup())
     if "NormalUser" in groupPropertie:
         return True
     else:
         return False
Ejemplo n.º 5
0
    def getUserByProperty(self, prop="NormalUser"):
        """
    Get usernames based on group property
    Argument is a string. Return value is a list
    """

        groupList = list()
        result = gConfig.getSections("/Registry/Groups")
        gLogger.debug("Group response: %s" % result)
        if not result["OK"]:
            return groupList

        groups = result["Value"]
        for j in groups:
            props = getProperties(j)
            gLogger.debug("%s properties: %s" % (j, props))
            if prop in props:
                groupList.append(j)

        if not len(groupList) > 0:
            return groupList
        groupList = uniqueElements(groupList)
        gLogger.debug("Chosen group(s): %s" % groupList)

        userList = list()
        for i in groupList:
            users = gConfig.getValue("/Registry/Groups/%s/Users" % i, [])
            gLogger.debug("%s users: %s" % (i, users))
            if len(users) > 0:
                userList.extend(users)

        return userList
Ejemplo n.º 6
0
def getUserData():
  userData = []
  username = credentials.getUsername()
  if not username or username == "anonymous":
    userData.append( "username : '******'" )
  else:
    userData.append( "username : '******'" % username )
    userData.append( "group : '%s'" % credentials.getSelectedGroup() )
    properties = credentials.getProperties( credentials.getSelectedGroup() )
    if len( properties ) > 0:
      userData.append( "groupProperties : %s" % properties )
    else:
      userData.append( "groupProperties : []" )
    availableGroups = [ "{ text : '%s', url : '%s' }" % ( groupName,
                                                                        diracURL( controller = 'web/userdata',
                                                                                  action = 'changeGroup',
                                                                                  id = groupName )
                                                                         ) for groupName in credentials.getAvailableGroups() ]
    userData.append( "groupMenu : [%s]" % ",".join( availableGroups ) )
  dn = credentials.getUserDN()
  if not dn:
    if 'REQUEST_URI' in request.environ:
      uri = str( request.environ[ 'REQUEST_URI' ] )
    else:
      uri = ""
    dn = "<a href=\"https://%s%s\">certificate login</a>" % ( str( request.environ[ 'HTTP_HOST' ] ), uri )
  userData.append( "DN : '%s'" % dn )
  return "{%s}" % ",".join( userData )
Ejemplo n.º 7
0
 def submit(self):
   pagestart = time()
   RPC = getRPCClient("WorkloadManagement/JobMonitoring")
   user = str(credentials.getUsername())
   result = RPC.getOwners()
   if result["OK"]:
     defaultGroup = gConfig.getValue("/Registry/DefaultGroup","")
     if defaultGroup == "":
       return {"success":"false","error":"Option /Registry/DefaultGroup is undefined, please set the default group in the CS"}
     group = str(credentials.getSelectedGroup())
     groupProperty = credentials.getProperties(group)
     if user not in result["Value"] and ( "JobAdministrator" or "JobSharing" ) not in groupProperty:
       c.result = {"success":"false","error":"You don't have any jobs in the DIRAC system"}
       return c.result
   else:
     c.result = {"success":"false","error":result["Message"]}
     return c.result
   req = self.__request()
   gLogger.always("getJobPageSummaryWeb(%s,%s,%s,%s)" % (req,globalSort,pageNumber,numberOfJobs))
   result = RPC.getJobPageSummaryWeb(req,globalSort,pageNumber,numberOfJobs)
   gLogger.always(" - REZ: " %result)
   if result["OK"]:
     result = result["Value"]
     gLogger.info("ReS",result)
     if result.has_key("TotalRecords"):
       if  result["TotalRecords"] > 0:
         if result.has_key("ParameterNames") and result.has_key("Records"):
           if len(result["ParameterNames"]) > 0:
             if len(result["Records"]) > 0:
               c.result = []
               jobs = result["Records"]
               head = result["ParameterNames"]
               headLength = len(head)
               for i in jobs:
                 tmp = {}
                 for j in range(0,headLength):
                   tmp[head[j]] = i[j]
                 c.result.append(tmp)
               total = result["TotalRecords"]
               timestamp = Time.dateTime().strftime("%Y-%m-%d %H:%M [UTC]")
               if result.has_key("Extras"):
                 st = self.__dict2string(req)
                 extra = result["Extras"]
                 c.result = {"success":"true","result":c.result,"total":total,"extra":extra,"request":st,"date":timestamp}
               else:
                 c.result = {"success":"true","result":c.result,"total":total,"date":timestamp}
             else:
               c.result = {"success":"false","result":"","error":"There are no data to display"}
           else:
             c.result = {"success":"false","result":"","error":"ParameterNames field is missing"}
         else:
           c.result = {"success":"false","result":"","error":"Data structure is corrupted"}
       else:
         c.result = {"success":"false","result":"","error":"There were no data matching your selection"}
     else:
       c.result = {"success":"false","result":"","error":"Data structure is corrupted"}
   else:
     c.result = {"success":"false","error":result["Message"]}
   gLogger.info("\033[0;31mJOB SUBMIT REQUEST:\033[0m %s" % (time() - pagestart))
   return c.result
Ejemplo n.º 8
0
def checkPropertiesWithUser(properties):
    if "all" in properties:
        return True
    if credentials.getSelectedGroup() != "visitor" and "authenticated" in properties:
        return True
    for userProp in credentials.getProperties():
        if userProp in properties:
            return True
    return False
Ejemplo n.º 9
0
def checkPropertiesWithUser( properties ):
  if 'all' in properties:
    return True
  if credentials.getSelectedGroup() != 'visitor' and 'authenticated' in properties:
    return True
  for userProp in credentials.getProperties():
    if userProp in properties:
      return True
  return False
Ejemplo n.º 10
0
def checkPropertiesWithUser( properties ):
  if 'all' in properties:
    return True
  if credentials.getSelectedGroup() != 'visitor' and 'authenticated' in properties:
    return True
  for userProp in credentials.getProperties():
    if userProp in properties:
      return True
  return False
Ejemplo n.º 11
0
 def display(self):
   pagestart = time()
   group = credentials.getSelectedGroup()
   if group == "visitor" and credentials.getUserDN == "":
     return render("/login.mako")
   c.select = self.__getSelectionData()
   if not c.select.has_key("extra"):
     groupProperty = credentials.getProperties(group)
     if ( "JobAdministrator" or "JobSharing" ) not in groupProperty: #len(groupProperty) == 1 and groupProperty[0] == "NormalUser":
       c.select["extra"] = {"owner":credentials.getUsername()}
   return render("jobs/JobMonitor.mako")
Ejemplo n.º 12
0
 def __canRunJobs(self):
   groupPropertie = credentials.getProperties( credentials.getSelectedGroup() )
   if "NormalUser" in groupPropertie:
     return True
   else:
     return False
Ejemplo n.º 13
0
 def __request(self):
   gLogger.always("!!!  PARAMS: ",str(request.params))
   req = {}
   group = credentials.getSelectedGroup()
   user = str(credentials.getUsername())
   global pageNumber
   global numberOfJobs
   global globalSort
   if request.params.has_key("limit") and len(request.params["limit"]) > 0:
     numberOfJobs = int(request.params["limit"])
     if request.params.has_key("start") and len(request.params["start"]) > 0:
       pageNumber = int(request.params["start"])
     else:
       pageNumber = 0
   else:
     numberOfJobs = 25
     pageNumber = 0
   if request.params.has_key("id") and len(request.params["id"]) > 0:
     testString = str(request.params["id"])
     testString = testString.strip(';, ')
     testString = testString.split(', ')
     if len(testString) == 1:
       testString = testString[0].split('; ')
       if len(testString) == 1:
         testString = testString[0].split(' ')
         if len(testString) == 1:
           testString = testString[0].split(',')
           if len(testString) == 1:
             testString = testString[0].split(';')
             if len(testString) == 1:
               req["JobID"] = testString[0]
             else:
               req["JobID"] = testString
           else:
             req["JobID"] = testString
         else:
           req["JobID"] = testString
       else:
         req["JobID"] = testString
     else:
       req["JobID"] = testString
     for i in req["JobID"]:
       testI = i.split('-')
       if len(testI) == 2:
         testI[0] = testI[0].strip(' ')
         testI[1] = testI[1].strip(' ')
         rangeID = range(testI[0],testI[1])
         gLogger.info("RANGE:",rangeID)
   else:
     groupProperty = credentials.getProperties(group)
     gLogger.always("### groupProperty: ",str(groupProperty))
     result = gConfig.getOption("/Website/ListSeparator")
     if result["OK"]:
       separator = result["Value"]
     else:
       separator = ":::"
     if request.params.has_key("prod") and len(request.params["prod"]) > 0:
       if str(request.params["prod"]) != "All":
         req["JobGroup"] = str(request.params["prod"]).split(separator)
     if request.params.has_key("site") and len(request.params["site"]) > 0:
       if str(request.params["site"]) != "All":
         req["Site"] = [x.strip() for x in str(request.params["site"]).split(separator)]
     if request.params.has_key("status") and len(request.params["status"]) > 0:
       if str(request.params["status"]) != "All":
         req["Status"] = str(request.params["status"]).split(separator)
     if request.params.has_key("minorstat") and len(request.params["minorstat"]) > 0:
       if str(request.params["minorstat"]) != "All":
         req["MinorStatus"] = str(request.params["minorstat"]).split(separator)
     if request.params.has_key("app") and len(request.params["app"]) > 0:
       if str(request.params["app"]) != "All":
         req["ApplicationStatus"] = str(request.params["app"]).split(separator)
     if request.params.has_key("types") and len(request.params["types"]) > 0:
       if str(request.params["types"]) != "All":
         req["JobType"] = str(request.params["types"]).split(separator)
     if not "JobAdministrator" in groupProperty and not "JobSharing" in groupProperty:
       if not request.params.has_key("globalStat"):
         req["Owner"] = str(user)
     else:
       if request.params.has_key("owner") and len(request.params["owner"]) > 0:
         if str(request.params["owner"]) != "All":
           req["Owner"] = str(request.params["owner"]).split(separator)
     if request.params.has_key("startDate") and len(request.params["startDate"]) > 0:
       if str(request.params["startDate"]) != "YYYY-mm-dd":
         if request.params.has_key("startTime") and len(request.params["startTime"]) > 0:
           req["FromDate"] = str(request.params["startDate"] + " " + request.params["startTime"])
         else:
           req["FromDate"] = str(request.params["startDate"])
     if request.params.has_key("endDate") and len(request.params["endDate"]) > 0:
       if str(request.params["endDate"]) != "YYYY-mm-dd":
         if request.params.has_key("endTime") and len(request.params["endTime"]) > 0:
           req["ToDate"] = str(request.params["endDate"] + " " + request.params["endTime"])
         else:
           req["ToDate"] = str(request.params["endDate"])
     if request.params.has_key("date") and len(request.params["date"]) > 0:
       if str(request.params["date"]) != "YYYY-mm-dd":
         req["LastUpdate"] = str(request.params["date"])
     if request.params.has_key("sort") and len(request.params["sort"]) > 0:
       globalSort = str(request.params["sort"])
       key,value = globalSort.split(" ")
       globalSort = [[str(key),str(value)]]
     else:
       globalSort = [["JobID","DESC"]]
   gLogger.always("REQUEST:",req)
   return req
Ejemplo n.º 14
0
  def __getSelectionData(self):
    callback = {}
    group = credentials.getSelectedGroup()
    user = str(credentials.getUsername())
    if len(request.params) > 0:
      tmp = {}
      for i in request.params:
        tmp[i] = str(request.params[i])
      callback["extra"] = tmp
      if callback["extra"].has_key("prod"):
        callback["extra"]["prod"] = callback["extra"]["prod"].zfill(8)
        if callback["extra"]["prod"] == "00000000":
          callback["extra"]["prod"] = ""
      gLogger.info(" - ",callback["extra"])
    if user == "Anonymous":
      callback["prod"] = [["Insufficient rights"]]
    else:
      RPC = getRPCClient("WorkloadManagement/JobMonitoring")
      result = RPC.getProductionIds()
      if result["OK"]:
        prod = []
        prods = result["Value"]
        if len(prods)>0:
          prod.append([str("All")])
          tmp = []
          for keys in prods:
            try:
              id = str(int(keys)).zfill(8)
            except:
              id = str(keys)
            tmp.append(str(id))
          tmp.sort(reverse=True)
          for i in tmp:
            prod.append([str(i)])
        else:
          prod = [["Nothing to display"]]
      else:
        gLogger.error("RPC.getProductionIds() return error: %s" % result["Message"])
        prod = [["Error happened on service side"]]
      callback["prod"] = prod
###
    RPC = getRPCClient("WorkloadManagement/JobMonitoring")
    result = RPC.getSites()
    if result["OK"]:
      tier1 = gConfig.getValue("/Website/PreferredSites",[]) # Always return a list
      site = []
      if len(result["Value"])>0:
        s = list(result["Value"])
        site.append([str("All")])
        for i in tier1:
          site.append([str(i)])
        for i in s:
          if i not in tier1:
            site.append([str(i)])    
      else:
        site = [["Nothing to display"]]
    else:
      gLogger.error("RPC.getSites() return error: %s" % result["Message"])
      site = [["Error happened on service side"]]
    callback["site"] = site
###
    result = RPC.getStates()
    if result["OK"]:
      stat = []
      if len(result["Value"])>0:
        stat.append([str("All")])
        for i in result["Value"]:
          stat.append([str(i)])
      else:
        stat = [["Nothing to display"]]
    else:
      gLogger.error("RPC.getStates() return error: %s" % result["Message"])
      stat = [["Error happened on service side"]]
    callback["status"] = stat
###
    result = RPC.getMinorStates()
    if result["OK"]:
      stat = []
      if len(result["Value"])>0:
        stat.append([str("All")])
        for i in result["Value"]:
          i = i.replace(",",";")
          stat.append([i])
      else:
        stat = [["Nothing to display"]]
    else:
      gLogger.error("RPC.getMinorStates() return error: %s" % result["Message"])
      stat = [["Error happened on service side"]]
    callback["minorstat"] = stat
###
    result = RPC.getApplicationStates()
    if result["OK"]:
      app = []
      if len(result["Value"])>0:
        app.append([str("All")])
        for i in result["Value"]:
          i = i.replace(",",";")
          app.append([i])
      else:
        app = [["Nothing to display"]]
    else:
      gLogger.error("RPC.getApplicationstates() return error: %s" % result["Message"])
      app = [["Error happened on service side"]]
    callback["app"] = app
###
    result = RPC.getJobTypes()
    if result["OK"]:
      types = []
      if len(result["Value"])>0:
        types.append([str("All")])
        for i in result["Value"]:
          i = i.replace(",",";")
          types.append([i])
      else:
        types = [["Nothing to display"]]
    else:
      gLogger.error("RPC.getJobTypes() return error: %s" % result["Message"])
      types = [["Error happened on service side"]]
    callback["types"] = types
###
    groupProperty = credentials.getProperties(group)
    if user == "Anonymous":
      callback["owner"] = [["Insufficient rights"]]
    elif ( "JobAdministrator" or "JobSharing" ) not in groupProperty:
      callback["owner"] = [["All"],[str(credentials.getUsername())]]
    else:
      result = RPC.getOwners()
      if result["OK"]:
        owner = []
        if len(result["Value"])>0:
          owner.append([str("All")])
          for i in result["Value"]:
            owner.append([str(i)])
        else:
          owner = [["Nothing to display"]]
      else:
        gLogger.error("RPC.getOwners() return error: %s" % result["Message"])
        owner = [["Error happened on service side"]]
      callback["owner"] = owner
    return callback
Ejemplo n.º 15
0
  def registerUser(self,paramcopy):
# Unfortunately there is no way to get rid of empty text values in JS, so i have to hardcode it on server side. Hate it!
    default_values = ["John Smith","jsmith","*****@*****.**","+33 9 10 00 10 00","Select prefered virtual organization(s)"]
    default_values.append("Select your country")
    default_values.append("Any additional information you want to provide to administrators")
    dn = getUserDN()
    username = getUsername()
    if not username == "anonymous":
      return {"success":"false","error":"You are already registered in DIRAC with username: %s" % username}
    else:
      if not dn:
        return {"success":"false","error":"You have to load certificate to your browser before trying to register"}
    body = ""
    userMail = False
    vo = []
    for i in paramcopy:
      if not paramcopy[i] in default_values:
        if i == "email":
          userMail = paramcopy[i]
        if i == "vo":
          vo = paramcopy[i].split(",")
        body = body + str(i) + ' - "' + str(paramcopy[i]) + '"\n'
    if not userMail:
      return {"success":"false","error":"Can not get your email from the request"}
    gLogger.info("!!! VO: ",vo)
# TODO Check for previous requests
    if not len(vo) > 0:
      mails = gConfig.getValue("/Website/UserRegistrationEmail",[])
    else:
      mails = []
      for i in vo:
        i = i.strip()
        voadm = gConfig.getValue("/Registry/VO/%s/VOAdmin" % i,"")
        failsafe = False
        if voadm:
          tmpmail = gConfig.getValue("/Registry/Users/%s/Email" % voadm,"")
          if tmpmail:
            mails.append(tmpmail)
          else:
            gLogger.error("Can not find value for option /Registry/Users/%s/Email Trying failsafe option" % voadm)
            failsafe = True
        else:
          gLogger.error("Can not find value for option /Registry/VO/%s/VOAdmin Trying failsafe option" % i)
          failsafe = True
        if failsafe:
          failsafe = gConfig.getValue("/Website/UserRegistrationEmail",[])
          if len(failsafe) > 0:
            for j in failsafe:
              mails.append(j)
          else:
              gLogger.error("Can not find value for failsafe option /Website/UserRegistrationEmail User registration for VO %s is failed" % i)
    mails = uniqueElements(mails)
    if not len(mails) > 0:
      groupList = list()
      allGroups = gConfig.getSections("/Registry/Groups")
      if not allGroups["OK"]:
        return {"success":"false","error":"No groups found at this DIRAC installation"}
      allGroups = allGroups["Value"]
      for j in allGroups:
        props = getProperties(j)
        if "UserAdministrator" in props: # property which usd for user administration
          groupList.append(j)
      groupList = uniqueElements(groupList)
      if not len(groupList) > 0:
        return {"success":"false","error":"No groups, resposible for user administration, found"}
      userList = list()
      for i in groupList:
        users = gConfig.getValue("/Registry/Groups/%s/Users" % i,[])
        for j in users:
          userList.append(j)
      userList = uniqueElements(userList)
      if not len(userList) > 0:
        return {"success":"false","error":"Can not find a person resposible for user administration, your request can not be approuved"}
      mails = list()
      mail2name = dict()
      for i in userList:
        tmpmail = gConfig.getValue("/Registry/Users/%s/Email" % i,"")
        if tmpmail:
          mails.append(tmpmail)
        else:
          gLogger.error("Can not find value for option /Registry/Users/%s/Email" % i)
      mails = uniqueElements(mails)
      if not len(mails) > 0:
        return {"success":"false","error":"Can not find an email of the person resposible for the users administration, your request can not be approuved"}
    gLogger.info("Admins emails: ",mails)
    if not len(mails) > 0:
      return {"success":"false","error":"Can not find any emails of DIRAC Administrators"}
    allUsers = gConfig.getSections("/Registry/Users")
    if not allUsers["OK"]:
      return {"success":"false","error":"No users found at this DIRAC installation"}
    allUsers = allUsers["Value"]
    mail2name = dict()
    for i in allUsers:
      tmpmail = gConfig.getValue("/Registry/Users/%s/Email" % i,"")
      if tmpmail in mails:
        mail2name[tmpmail] = gConfig.getValue("/Registry/Users/%s/FullName" % i,i)
    sentFailed = list()
    sentSuccess = list()
    errorMessage = list()
    ntc = NotificationClient( getRPCClient )
    for i in mails:
      i = i.strip()
      result = ntc.sendMail(i,"New user has registered",body,userMail,False)
      if not result["OK"]:
        sentFailed.append(mail2name[i])
        errorMessage.append(result["Message"])
      else:
        sentSuccess.append(mail2name[i])
    gLogger.info("Sent success: ",sentSuccess)
    gLogger.info("Sent failure: ",sentFailed)
    errorMessage = uniqueElements(errorMessage)
    if len(sentSuccess) == 0:
      if not len(errorMessage) > 0:
        return {"success":"false","error":"No messages were sent to administrators due techincal reasons"}
      errorMessage = ", ".join(errorMessage)
      return {"success":"false","error":errorMessage}
    sName = ", ".join(sentSuccess)
    fName = ", ".join(sentFailed)
    if len(sentFailed) > 0:
      return {"success":"true","result":"Your registration request were sent successfuly to %s. Failed to sent request to %s." % (sName, fName)}
    return {"success":"true","result":"Your registration request were sent successfuly to %s." % sName}
Ejemplo n.º 16
0
 def registerUser(self, paramcopy):
     # Unfortunately there is no way to get rid of empty text values in JS, so i have to hardcode it on server side. Hate it!
     default_values = [
         "John Smith", "jsmith", "*****@*****.**",
         "+33 9 10 00 10 00", "Select prefered virtual organization(s)"
     ]
     default_values.append("Select your country")
     default_values.append(
         "Any additional information you want to provide to administrators")
     dn = getUserDN()
     username = getUsername()
     if not username == "anonymous":
         return {
             "success":
             "false",
             "error":
             "You are already registered in DIRAC with username: %s" %
             username
         }
     else:
         if not dn:
             return {
                 "success":
                 "false",
                 "error":
                 "You have to load certificate to your browser before trying to register"
             }
     body = ""
     userMail = False
     vo = []
     for i in paramcopy:
         if not paramcopy[i] in default_values:
             if i == "email":
                 userMail = paramcopy[i]
             if i == "vo":
                 vo = paramcopy[i].split(",")
             body = body + str(i) + ' - "' + str(paramcopy[i]) + '"\n'
     if not userMail:
         return {
             "success": "false",
             "error": "Can not get your email from the request"
         }
     gLogger.info("!!! VO: ", vo)
     # TODO Check for previous requests
     if not len(vo) > 0:
         mails = gConfig.getValue("/Website/UserRegistrationEmail", [])
     else:
         mails = []
         for i in vo:
             i = i.strip()
             voadm = gConfig.getValue("/Registry/VO/%s/VOAdmin" % i, "")
             failsafe = False
             if voadm:
                 tmpmail = gConfig.getValue(
                     "/Registry/Users/%s/Email" % voadm, "")
                 if tmpmail:
                     mails.append(tmpmail)
                 else:
                     gLogger.error(
                         "Can not find value for option /Registry/Users/%s/Email Trying failsafe option"
                         % voadm)
                     failsafe = True
             else:
                 gLogger.error(
                     "Can not find value for option /Registry/VO/%s/VOAdmin Trying failsafe option"
                     % i)
                 failsafe = True
             if failsafe:
                 failsafe = gConfig.getValue(
                     "/Website/UserRegistrationEmail", [])
                 if len(failsafe) > 0:
                     for j in failsafe:
                         mails.append(j)
                 else:
                     gLogger.error(
                         "Can not find value for failsafe option /Website/UserRegistrationEmail User registration for VO %s is failed"
                         % i)
     mails = uniqueElements(mails)
     if not len(mails) > 0:
         groupList = list()
         allGroups = gConfig.getSections("/Registry/Groups")
         if not allGroups["OK"]:
             return {
                 "success": "false",
                 "error": "No groups found at this DIRAC installation"
             }
         allGroups = allGroups["Value"]
         for j in allGroups:
             props = getProperties(j)
             if "UserAdministrator" in props:  # property which usd for user administration
                 groupList.append(j)
         groupList = uniqueElements(groupList)
         if not len(groupList) > 0:
             return {
                 "success": "false",
                 "error":
                 "No groups, resposible for user administration, found"
             }
         userList = list()
         for i in groupList:
             users = gConfig.getValue("/Registry/Groups/%s/Users" % i, [])
             for j in users:
                 userList.append(j)
         userList = uniqueElements(userList)
         if not len(userList) > 0:
             return {
                 "success":
                 "false",
                 "error":
                 "Can not find a person resposible for user administration, your request can not be approuved"
             }
         mails = list()
         mail2name = dict()
         for i in userList:
             tmpmail = gConfig.getValue("/Registry/Users/%s/Email" % i, "")
             if tmpmail:
                 mails.append(tmpmail)
             else:
                 gLogger.error(
                     "Can not find value for option /Registry/Users/%s/Email"
                     % i)
         mails = uniqueElements(mails)
         if not len(mails) > 0:
             return {
                 "success":
                 "false",
                 "error":
                 "Can not find an email of the person resposible for the users administration, your request can not be approuved"
             }
     gLogger.info("Admins emails: ", mails)
     if not len(mails) > 0:
         return {
             "success": "false",
             "error": "Can not find any emails of DIRAC Administrators"
         }
     allUsers = gConfig.getSections("/Registry/Users")
     if not allUsers["OK"]:
         return {
             "success": "false",
             "error": "No users found at this DIRAC installation"
         }
     allUsers = allUsers["Value"]
     mail2name = dict()
     for i in allUsers:
         tmpmail = gConfig.getValue("/Registry/Users/%s/Email" % i, "")
         if tmpmail in mails:
             mail2name[tmpmail] = gConfig.getValue(
                 "/Registry/Users/%s/FullName" % i, i)
     sentFailed = list()
     sentSuccess = list()
     errorMessage = list()
     ntc = NotificationClient(getRPCClient)
     for i in mails:
         i = i.strip()
         result = ntc.sendMail(i, "New user has registered", body, userMail,
                               False)
         if not result["OK"]:
             sentFailed.append(mail2name[i])
             errorMessage.append(result["Message"])
         else:
             sentSuccess.append(mail2name[i])
     gLogger.info("Sent success: ", sentSuccess)
     gLogger.info("Sent failure: ", sentFailed)
     errorMessage = uniqueElements(errorMessage)
     if len(sentSuccess) == 0:
         if not len(errorMessage) > 0:
             return {
                 "success":
                 "false",
                 "error":
                 "No messages were sent to administrators due techincal reasons"
             }
         errorMessage = ", ".join(errorMessage)
         return {"success": "false", "error": errorMessage}
     sName = ", ".join(sentSuccess)
     fName = ", ".join(sentFailed)
     if len(sentFailed) > 0:
         return {
             "success":
             "true",
             "result":
             "Your registration request were sent successfuly to %s. Failed to sent request to %s."
             % (sName, fName)
         }
     return {
         "success":
         "true",
         "result":
         "Your registration request were sent successfuly to %s." % sName
     }
Ejemplo n.º 17
0
 def registerUser(self,paramcopy):
   gLogger.info("Start processing a registration request")
   """
   Unfortunately there is no way to get rid of empty text values in JS,
   so i have to hardcode it on server side. Hate it!
   """
   default_values = ["John Smith","jsmith","*****@*****.**","+33 9 10 00 10 00"]
   default_values.append("Select preferred virtual organization(s)")
   default_values.append("Select your country")
   default_values.append("Any additional information you want to provide to administrators")
   # Check for having a DN but no username
   dn = getUserDN()
   username = getUsername()
   gLogger.debug("User's DN: %s and DIRAC username: %s" % (dn, username))
   if not username == "anonymous":
     error = "You are already registered in DIRAC with username: %s" % username
     gLogger.debug("Service response: %s" % error)
     return {"success":"false","error":error}
   else:
     if not dn:
       error = "Certificate is not loaded to a browser or DN is absent"
       gLogger.debug("Service response: %s" % error)
       return {"success":"false","error":error}
   body = ""
   userMail = False
   vo = []
   # Check for user's email, creating mail body
   gLogger.debug("Request's body:")
   for i in paramcopy:
     gLogger.debug("%s - %s" % (i,paramcopy[i]))
     if not paramcopy[i] in default_values:
       if i == "email":
         userMail = paramcopy[i]
       if i == "vo":
         vo = paramcopy[i].split(",")
       body = body + str(i) + ' - "' + str(paramcopy[i]) + '"\n'
   if not userMail:
     error = "Can not get your email address from the request"
     gLogger.debug("Service response: %s" % error)
     return {"success":"false","error":error}
   gLogger.info("User want to be register in VO(s): %s" % vo)
   # TODO Check for previous requests
   # Get admin mail based on requested VO i.e. mail of VO admin
   mails = list()
   gLogger.debug("Trying to get admin username to take care about request")
   for i in vo:
     gLogger.debug("VOAdmin for VO: %s" % i)
     i = i.strip()
     voadm = gConfig.getValue("/Registry/VO/%s/VOAdmin" % i,[])
     gLogger.debug("/Registry/VO/%s/VOAdmin - %s" % (i,voadm))
     for user in voadm:
       mails.append(user)
   # If no VOAdmin - try to get admin mails based on group properties
   if not len(mails) > 0:
     gLogger.debug("No VO admins found. Trying to get something based on group property")
     groupList = list()
     groups = gConfig.getSections("/Registry/Groups")
     gLogger.debug("Group response: %s" % groups)
     if groups["OK"]:
       allGroups = groups["Value"]
       gLogger.debug("Looking for UserAdministrator property")
       for j in allGroups:
         props = getProperties(j)
         gLogger.debug("%s properties: %s" % (j,props)) #1
         if "UserAdministrator" in props: # property which is used for user administration
           groupList.append(j)
     groupList = uniqueElements(groupList)
     gLogger.debug("Chosen group(s): %s" % groupList)
     if len(groupList) > 0:
       for i in groupList:
         users = gConfig.getValue("/Registry/Groups/%s/Users" % i,[])
         gLogger.debug("%s users: %s" % (i,users))
         for user in users:
           mails.append(user)
   # Last stand - Failsafe option
   if not len(mails) > 0:
     gLogger.debug("No suitable groups found. Trying failsafe")
     regAdmin = gConfig.getValue("/Website/UserRegistrationAdmin",[])
     gLogger.debug("/Website/UserRegistrationAdmin - %s" % regAdmin)
     for user in regAdmin:
       mails.append(user)
   mails = uniqueElements(mails)
   gLogger.info("Chosen admin(s): %s" % mails)
   # Final check of usernames
   if not len(mails) > 0:
     error = "Can't get in contact with administrators about your request\n"
     error = error + "Most likely this DIRAC instance is not configured yet"
     gLogger.debug("Service response: %s" % error)
     return {"success":"false","error":error}
   # Convert usernames to { e-mail : full name }
   gLogger.debug("Trying to get admin's mail and associated name")
   sendDict = dict()
   for user in mails:
     email = gConfig.getValue("/Registry/Users/%s/Email" % user,"")
     gLogger.debug("/Registry/Users/%s/Email - '%s'" % (user,email))
     emil = email.strip()
     if not email:
       gLogger.error("Can't find value for option /Registry/Users/%s/Email" % user)
       continue
     fname = gConfig.getValue("/Registry/Users/%s/FullName" % user,"")
     gLogger.debug("/Registry/Users/%s/FullName - '%s'" % (user,fname))
     fname = fname.strip()
     if not fname:
       fname = user
       gLogger.debug("FullName is absent, name to be used: %s" % fname)
     sendDict[email] = fname
   # Final check of mails
   gLogger.debug("Final dictionary with mails to be used %s" % sendDict)
   if not len(sendDict) > 0:
     error = "Can't get in contact with administrators about your request\n"
     error = error + "Most likely this DIRAC instance is not configured yet"
     gLogger.debug("Service response: %s" % error)
     return {"success":"false","error":error}
   # Sending a mail
   sentSuccess = list()
   sentFailed = list()
   gLogger.debug("Initializing Notification client")
   ntc = NotificationClient(lambda x, timeout: getRPCClient(x, timeout=timeout, static = True) )
   gLogger.debug("Sending messages")
   for email,name in sendDict.iteritems():
     gLogger.debug("ntc.sendMail(%s,New user has registered,%s,%s,False" % (email,body,userMail))
     result = ntc.sendMail(email,"New user has registered",body,userMail,False)
     if not result["OK"]:
       error = name + ": " + result["Message"]
       sentFailed.append(error)
       gLogger.error("Sent failure: ", error)
     else:
       gLogger.info("Successfully sent to %s" % name)
       sentSuccess.append(name)
   # Returning results
   sName = ", ".join(sentSuccess)
   gLogger.info("End of processing of a registration request")
   gLogger.debug("Service response sent to a user:"******"Your registration request were sent successfully to: "
     result = result + sName + "\n\nFailed to sent it to:\n"
     result = result + "\n".join(sentFailed)
     gLogger.debug(result)
     return {"success":"true","result":result}
   elif len(sentSuccess) > 0 and (not len(sentFailed)) > 0:
     result = "Your registration request were sent successfully to: %s" % sName
     gLogger.debug(result)
     return {"success":"true","result":result}
   elif (not len(sentSuccess)) > 0 and len(sentFailed) > 0:
     result = "Failed to sent your request to:\n"
     result = result + "\n".join(sentFailed)
     gLogger.debug(result)
     return {"success":"false","error":result}
   else:
     result = "No messages were sent to administrator due technical failure"
     gLogger.debug(result)
     return {"success":"false","error":result}
Ejemplo n.º 18
0
 def display( self ):
   if "SiteManager" in getProperties():
     c.allowActions = True
   else:
     c.allowActions = False
   return render( "web/siteMap.mako" )
Ejemplo n.º 19
0
 def display(self):
     if "SiteManager" in getProperties():
         c.allowActions = True
     else:
         c.allowActions = False
     return render("web/siteMap.mako")