Esempio n. 1
0
def __prepareArgs(kwargs):
    if credentials.getUserDN():
        kwargs["delegatedGroup"] = str(credentials.getSelectedGroup())
        kwargs["delegatedDN"] = str(credentials.getUserDN())
    kwargs["useCertificates"] = True
    kwargs["setup"] = credentials.getSelectedSetup()
    return kwargs
Esempio n. 2
0
def __prepareArgs(kwargs):
    if credentials.getUserDN():
        kwargs['delegatedGroup'] = str(credentials.getSelectedGroup())
        kwargs['delegatedDN'] = str(credentials.getUserDN())
    kwargs['useCertificates'] = True
    kwargs['setup'] = credentials.getSelectedSetup()
    return kwargs
Esempio n. 3
0
def __prepareArgs( kwargs ):
  if ( 'static' not in kwargs or not kwargs[ 'static' ] ) and credentials.getUserDN():
    kwargs[ 'delegatedGroup' ] =  str( credentials.getSelectedGroup() )
    kwargs[ 'delegatedDN' ] = str( credentials.getUserDN() )
  kwargs[ 'useCertificates' ] = True
  kwargs[ 'setup' ] = credentials.getSelectedSetup()
  return kwargs
Esempio n. 4
0
  def authorizeRequest( self ):
    #Check the setup is allright
    if 'setup' in request.params:
      requestedSetup = request.params[ 'setup' ]
      result = gConfig.getSections( "/DIRAC/Setups" )
      if not result[ 'OK' ]:
        c.error( "Oops: %s" % result[ 'Value' ] )
        return render( "/error.mako" )
      knownSetups = result[ 'Value' ]
      if requestedSetup not in knownSetups:
        c.error = "Unknown %s setup" % requestedSetup
        return render( "/error.mako" )
      if getSelectedSetup() != requestedSetup:
        return self.__changeSetupAndRedirect( requestedSetup )

    params = {}
    for key in request.params:
      params[ key ] = request.params[ key ]
    gOAManager.parse( method = request.method,
                      url = request.url,
                      headers = request.headers,
                      parameters = params,
                      query_string = request.query_string )
    if not gOAData.token:
      c.error = "Dude! You shouldn't be here without a request token :P"
      return render( "/error.mako" )
    if not getUserDN() or getSelectedGroup() == "visitor":
      c.error = "Please log in with your certificate"
      return render( "/error.mako" )
    result = gOAManager.credentials.getRequestData( gOAData.token )
    if not result[ 'OK' ]:
      c.error = result[ 'Message' ]
      return render( "/error.mako" )
    reqData = result[ 'Value' ]
    consData = reqData[ 'consumer' ]
    result = gOAManager.credentials.generateVerifier( consData[ 'key' ],
                                                         reqData[ 'request' ],
                                                         c.userDN, c.userGroup )
    if not result[ 'OK' ]:
      c.error = result[ 'Message' ]
      return render( "/error.mako" )
    verifier = result[ 'Value' ]

    c.consName = consData[ 'name' ]
    c.consImg = consData[ 'icon' ]
    c.userDN = getUserDN()
    c.userGroup = getSelectedGroup()
    c.request = gOAData.token
    c.verifier = verifier
    c.consumerKey = consData[ 'key' ]

    c.callback = gOAData.callback or reqData[ 'callback' ]
    c.callback = urllib.quote_plus( c.callback )

    return render( "/WebAPI/authorizeRequest.mako" )
Esempio n. 5
0
  def authorizeCode( self ):
    #Check the setup is allright
    if 'setup' in request.params:
      requestedSetup = request.params[ 'setup' ]
      result = gConfig.getSections( "/DIRAC/Setups" )
      if not result[ 'OK' ]:
        c.error( "Oops: %s" % result[ 'Value' ] )
        return render( "/error.mako" )
      knownSetups = result[ 'Value' ]
      if requestedSetup not in knownSetups:
        c.error = "Unknown %s setup" % requestedSetup
        return render( "/error.mako" )
      if getSelectedSetup() != requestedSetup:
        return self.__changeSetupAndRedirect( requestedSetup )

    try:
      cid = str( request.params[ 'client_id' ] )
    except KeyError:
      c.error = "Dude! You shouldn't be here without a client_id :P"
      return render( "/error.mako" )
    if not getUserDN() or getSelectedGroup() == "visitor":
      c.error = "Please log in with your certificate"
      return render( "/error.mako" )
    result = self.__oaToken.getClientDataByID( cid )
    if not result[ 'OK' ]:
      c.error = "Unknown originating client"
      return render( "/error.mako" )
    cData = result[ 'Value' ]

    try:
      redirect = str( request.params[ 'redirect_uri' ] )
    except KeyError:
      redirect = ""

    c.cName = cData[ 'Name' ]
    c.cImg = cData[ 'Icon' ]
    c.cID = cid
    if redirect:
      c.redirect = base64.urlsafe_b64encode( redirect )
    c.userDN = getUserDN()
    c.userGroup = getSelectedGroup()

    for k in ( 'scope', 'state' ):
      if k in request.params:
        setattr( c, k, str( request.params[k] ) )
      else:
        setattr( c, k, False )

    return render( "/OAuth2/authorizeCode.mako" )
Esempio n. 6
0
 def getSandbox( self ):
   """ Get job sandbox 
   """
   if 'jobID' not in request.params:
     c.error = "Maybe you forgot the jobID ?"
     return render( "/error.mako" )
   jobID = int(request.params['jobID']) 
   sbType = 'Output'
   if 'sandbox' in request.params:
     sbType = str(request.params['sandbox'])
       
   client = SandboxStoreClient(useCertificates=True,
                               delegatedDN=str( credentials.getUserDN() ),
                               delegatedGroup=str( credentials.getSelectedGroup() ),
                               setup = credentials.getSelectedSetup() )
   result = client.downloadSandboxForJob(jobID,sbType,inMemory=True)
   if not result['OK']:
     c.error = "Error: %s" % result['Message']
     return render( "/error.mako" ) 
   
   data = result['Value'] 
   fname = "%s_%sSandbox.tar" % (str(jobID),sbType)
   response.headers['Content-type'] = 'application/x-tar'
   response.headers['Content-Disposition'] = 'attachment; filename="%s"' % fname
   response.headers['Content-Length'] = len( data )
   return data
Esempio n. 7
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 )
Esempio n. 8
0
    def __sendMessage(self):
        """
    This function is used to send a mail to specific group of DIRAC user
    Expected parameters from request are group, title, body
    """

        gLogger.info("Start message broadcasting")

        checkUserCredentials()
        dn = getUserDN()
        if not dn:
            error = "Certificate is not loaded in the browser or DN is absent"
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}
        username = getUsername()
        if username == "anonymous":
            error = "Sending an anonymous message is forbidden"
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}
        gLogger.info("DN: %s" % dn)

        email = gConfig.getValue("/Registry/Users/%s/Email" % username, "")
        gLogger.debug("/Registry/Users/%s/Email - '%s'" % (username, email))
        emil = email.strip()

        if not email:
            error = "Can't find value for option /Registry/Users/%s/Email" % user
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}

        test = ["group", "title", "body"]
        for i in test:
            if not i in request.params:
                error = "The required parameter %s is absent in request" % i
                gLogger.error("Service response: %s" % error)
                return {"success": "false", "error": error}

        group = request.params["group"]
        users = gConfig.getValue("/Registry/Groups/%s/Users" % group, [])
        if not len(users) > 0:
            error = "No users for %s group found" % group
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}

        sendDict = self.getMailDict(users)
        if not len(sendDict) > 0:
            error = "Can't get a mail address for users in %s group" % group
            gLogger.debug("Service response: %s" % error)
            return {"success": "false", "error": error}
        gLogger.debug("Final dictionary with mails to be used %s" % sendDict)

        title = self.checkUnicode(request.params["title"])
        gLogger.debug("email title: %s" % title)

        body = self.checkUnicode(request.params["body"])
        gLogger.debug("email body: %s" % body)

        self.__messageLog(user, group, title, body)

        return self.sendMail(sendDict, title, body, email)
Esempio n. 9
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)
Esempio n. 10
0
 def __getProxyStatus(self,secondsOverride = None):
     
   from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
   
   proxyManager = ProxyManagerClient()
   group = str(credentials.getSelectedGroup())
   if group == "visitor":
     return {"success":"false","error":"User is anonymous or is not registered in the system"}
   userDN = str(credentials.getUserDN())
   if secondsOverride and str(secondsOverride).isdigit():
     validSeconds = int(secondsOverride)
   else:
     defaultSeconds = 24 * 3600 + 60 # 24H + 1min
     validSeconds = gConfig.getValue("/Registry/DefaultProxyLifeTime",defaultSeconds)
   gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" % (userDN,group,validSeconds))
   result = proxyManager.userHasProxy(userDN,group,validSeconds)
   if result["OK"]:
     if result["Value"]:
       c.result = {"success":"true","result":"true"}
     else:
       c.result = {"success":"true","result":"false"}
   else:
     c.result = {"success":"false","error":"false"}
   gLogger.info("\033[0;31m PROXY: \033[0m",result)
   return c.result
Esempio n. 11
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 )
Esempio n. 12
0
def htmlUserInfo():
    username = credentials.getUsername()
    if not username or username == "anonymous":
        htmlData = "Anonymous"
    else:
        selectedGroup = credentials.getSelectedGroup()
        availableGroups = [(groupName,
                            diracURL(controller='web/userdata',
                                     action='changeGroup',
                                     id=groupName))
                           for groupName in credentials.getAvailableGroups()]
        htmlData = "%s@%s" % (username,
                              yuiWidgets.dropDownMenu("UserGroupPos",
                                                      selectedGroup,
                                                      availableGroups))
    dn = credentials.getUserDN()
    if dn:
        htmlData += " (%s)" % dn
    else:
        if 'REQUEST_URI' in request.environ:
            uri = str(request.environ['REQUEST_URI'])
        else:
            uri = ""
        htmlData += " (<a href='https://%s%s'>certificate login</a>)" % (str(
            request.environ['HTTP_HOST']), uri)
    return htmlData
Esempio n. 13
0
  def sysinfo( self ):

    DN = getUserDN()
    group = getSelectedGroup()

    #TODO: remove hosts code after v6r7 since it will be built-in
    result = gConfig.getSections( "/Registry/Hosts" )
    if not result[ "Value" ]:
      return { "success" : "false" , "error" : result[ "Message" ] }
    hosts = result[ "Value" ]

    client = SystemAdministratorIntegrator( hosts = hosts , delegatedDN=DN ,
                                          delegatedGroup=group )
    result = client.getHostInfo()
    gLogger.debug( result )
    if not result[ "OK" ]:
      return { "success" : "false" , "error" : result[ "Message" ] }
    result = result[ "Value" ]

    callback = list()
    for i in result:
      if result[ i ][ "OK" ]:
        tmp = result[ i ][ "Value" ]
      else:
        tmp = dict()
      tmp[ "Host" ] = i
      callback.append( tmp )

    total = len( callback )
    if not total > 0:
      return { "success" : "false" , "error" : "No system information found" }
    return { "success" : "true" , "result" : callback , "total" : total }
    def getSandbox(self):
        """ Get job sandbox 
    """
        if 'jobID' not in request.params:
            c.error = "Maybe you forgot the jobID ?"
            return render("/error.mako")
        jobID = int(request.params['jobID'])
        sbType = 'Output'
        if 'sandbox' in request.params:
            sbType = str(request.params['sandbox'])

        client = SandboxStoreClient(useCertificates=True,
                                    delegatedDN=str(credentials.getUserDN()),
                                    delegatedGroup=str(
                                        credentials.getSelectedGroup()),
                                    setup=credentials.getSelectedSetup())
        result = client.downloadSandboxForJob(jobID, sbType, inMemory=True)
        if not result['OK']:
            c.error = "Error: %s" % result['Message']
            return render("/error.mako")

        data = result['Value']
        fname = "%s_%sSandbox.tar" % (str(jobID), sbType)
        response.headers['Content-type'] = 'application/x-tar'
        response.headers[
            'Content-Disposition'] = 'attachment; filename="%s"' % fname
        response.headers['Content-Length'] = len(data)
        return data
Esempio n. 15
0
  def showHostErrors( self ):

    DN = getUserDN()
    group = getSelectedGroup()
    
    if not "host" in request.params:
      return { "success" : "false" , "error" : "Name of the host is missing or not defined" }
    host = str( request.params[ "host" ] )

    client = SystemAdministratorClient( host , None , delegatedDN=DN , delegatedGroup=group )

    result = client.checkComponentLog( "*" )
    gLogger.debug( result )
    if not result[ "OK" ]:
      return { "success" : "false" , "error" : result[ "Message" ] }
    result = result[ "Value" ]
    
    callback = list()
    for key, value in result.items():
      system, component = key.split( "/" )
      value[ "System" ] = system
      value[ "Name" ] = component
      value[ "Host" ] = host
      callback.append( value )
    total = len( callback )

    return { "success" : "true" , "result" : callback , "total" : total }
Esempio n. 16
0
  def showLog( self ):

    DN = getUserDN()
    group = getSelectedGroup()
    
    if not "host" in request.params:
      return "Name of the host is missing or not defined"
    host = str( request.params[ "host" ] )

    if not "system" in request.params:
      return "Name of the system is missing or not defined"
    system = str( request.params[ "system" ] )

    if not "component" in request.params:
      return "Name of component is missing or not defined"
    name = str( request.params[ "component" ] )

    client = SystemAdministratorClient( host , None , delegatedDN=DN , delegatedGroup=group )

    result = client.getLogTail( system , name )
    gLogger.debug( result )
    if not result[ "OK" ]:
      return result[ "Message" ]
    result = result[ "Value" ]

    key = system + "_" + name
    if not key in result:
      return "%s key is absent in service response" % key
    log = result[ key ]

    return log.replace( "\n" , "<br>" )
Esempio n. 17
0
  def submit( self ):

    """
    Returns flatten list of components (services, agents) installed on hosts
    returned by getHosts function
    """

    checkUserCredentials()
    DN = getUserDN()
    group = getSelectedGroup()

    callback = list()
    
    request = self.request()
    if not 'Hostname' in request:
      return { "success" : "false" , "error" : "Name of the host is absent" }
    
    host = request[ 'Hostname' ]
    client = SystemAdministratorClient( host , None , delegatedDN=DN ,
                                          delegatedGroup=group )
    result = client.getOverallStatus()
    gLogger.debug( "Result of getOverallStatus(): %s" % result )

    if not result[ "OK" ]:
      return { "success" : "false" , "error" : result[ "Message" ] }
    overall = result[ "Value" ]

    for record in self.flatten( overall ):
      record[ "Host" ] = host
      callback.append( record )

    return { "success" : "true" , "result" : callback }
Esempio n. 18
0
 def commitConfiguration(self):
     if not authorizeAction():
         return S_ERROR("You are not authorized to commit configurations!! Bad boy!")
     gLogger.always("User %s is commiting a new configuration version" % credentials.getUserDN())
     modifier = self.__getModificator()
     modifier.loadFromBuffer(session["cfgData"])
     retDict = modifier.commit()
     if not retDict["OK"]:
         return S_ERROR(retDict["Message"])
     return S_OK()
 def commitConfiguration(self):
     if not authorizeAction():
         return S_ERROR(
             "You are not authorized to commit configurations!! Bad boy!")
     gLogger.always("User %s is commiting a new configuration version" %
                    credentials.getUserDN())
     modifier = self.__getModificator()
     modifier.loadFromBuffer(session['cfgData'])
     retDict = modifier.commit()
     if not retDict['OK']:
         return S_ERROR(retDict['Message'])
     return S_OK()
Esempio n. 20
0
    def display(self):
        checkUserCredentials()
        dn = getUserDN()
        user = getUsername()
        group = getSelectedGroup()
        gLogger.always("User: %s, Group: %s, DN: %s" % (user, group, dn))
        templates = ["reg_%s.mako" % i for i in ["done", "form", "info"]]
        html = [
            "reg_%s.html" % i
            for i in ["footer", "header", "conditions", "form", "done"]
        ]
        files = templates + html
        basedir = os.path.join(rootPath, "Web", "dirac", "templates")
        for i in files:
            f = os.path.join(basedir, i)
            if not os.path.exists(f):
                gLogger.error("File does not exists: %s" % f)
                return render("web/External.mako")
        if dn and user == "anonymous":
            upc = UserProfileClient("Registration", getRPCClient)
            result = upc.retrieveVar(dn)
            if result["OK"]:
                c.sent = result["Value"]
                return render("/reg_done.mako")
            else:
                return render("/reg_form.mako")
        if not dn or dn == "":
            return render("/reg_info.mako")

        if "site" not in request.params:
            c.select = gConfig.getValue("/Website/DefaultExternalURL",
                                        "http://diracgrid.org")
            return render("web/External.mako")

        # No idea what this code should do...
        if request.params.has_key("site") and len(request.params["site"]) > 0:
            if str(request.params["site"]) != "All":
                c.select = str(request.params["site"])
                gLogger.debug("Request's body:")
                for key in request.params.keys():
                    if not key == "site" and len(request.params[key]) > 0:
                        c.select = c.select + "&" + key + "=" + request.params[
                            key]
                        try:
                            gLogger.debug("%s - %s" %
                                          (key, request.params[key]))
                        except Exception, x:
                            gLogger.error("Exception: %s" % str(x))
                            pass
Esempio n. 21
0
 def grantAccess( self ):
   uDN = getUserDN()
   uGroup = getSelectedGroup()
   if not uDN or uGroup == "visitor":
     c.error = "Please log in with your certificate"
     return render( "/error.mako" )
   try:
     cid = str( request.params[ 'cid' ] )
     lifeTime = int( request.params[ 'accessTime' ] ) * 3600
     qRedirect = str( request.params[ 'redirect' ] )
     if qRedirect:
       qRedirect = base64.urlsafe_b64decode( qRedirect )
   except Exception, excp:
     c.error = "Missing or invalid in query!"
     return render( "/error.mako" )
Esempio n. 22
0
  def __actionHost( self ):

    """
    Restart all DIRAC components on a given host
    """

    if not "hostname" in request.params:
      return { "success" : "false" , "error" : "No hostname given" }
    hosts = request.params[ "hostname" ].split( "," )

    DN = getUserDN()
    group = getSelectedGroup()

    self.actionSuccess = list()
    self.actionFailed = list()

    for i in hosts:
      client = SystemAdministratorClient( str( i ) , None , delegatedDN=DN ,
                                          delegatedGroup=group )
      if self.action is "restart":
        result = client.restartComponent( str( "*" ) , str( "*" ) )
      elif self.action is "revert":
        result = client.revertSoftware()
      else:
        error = i + ": Action %s is not defined" % self.action
        self.actionFailed.append( error )
        continue

      gLogger.always( result )

      if not result[ "OK" ]:
        if result[ "Message" ].find( "Unexpected EOF" ) > 0:
          msg = "Signal 'Unexpected EOF' received. Most likely DIRAC components"
          msg = i + ": " + msg + " were successfully restarted."
          self.actionSuccess.append( msg )
          continue
        error = i + ": " + result[ "Message" ]
        self.actionFailed.append( error )
        gLogger.error( error )
      else:
        gLogger.info( result[ "Value" ] )
        self.actionSuccess.append( i )
      
    self.prefix = "Host"
    return self.__aftermath()
Esempio n. 23
0
def htmlUserInfo():
  username = credentials.getUsername()
  if not username or username == "anonymous":
    htmlData = "Anonymous"
  else:
    selectedGroup = credentials.getSelectedGroup()
    availableGroups = [ ( groupName, diracURL( controller = 'web/userdata', action = 'changeGroup', id = groupName ) ) for groupName in credentials.getAvailableGroups() ]
    htmlData = "%s@%s" % ( username, yuiWidgets.dropDownMenu( "UserGroupPos", selectedGroup, availableGroups ) )
  dn = credentials.getUserDN()
  if dn:
    htmlData += " (%s)" % dn
  else:
    if 'REQUEST_URI' in request.environ:
      uri = str( request.environ[ 'REQUEST_URI' ] )
    else:
      uri = ""
    htmlData += " (<a href='https://%s%s'>certificate login</a>)" % ( str( request.environ[ 'HTTP_HOST' ] ), uri )
  return htmlData
Esempio n. 24
0
 def __getProxyStatus( self, validSeconds = 0 ):
   from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
   proxyManager = ProxyManagerClient()
   group = str(credentials.getSelectedGroup())
   if group == "visitor":
     return {"success":"false","error":"User not registered"}
   userDN = str(credentials.getUserDN())
   gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" % (userDN,group,validSeconds))
   result = proxyManager.userHasProxy(userDN,group,validSeconds)
   if result["OK"]:
     if result["Value"]:
       c.result = {"success":"true","result":"true"}
     else:
       c.result = {"success":"true","result":"false"}
   else:
     c.result = {"success":"false","error":"false"}
   gLogger.info("\033[0;31m PROXY: \033[0m",result)
   return c.result
Esempio n. 25
0
  def display(self):
    checkUserCredentials()
    dn = getUserDN()
    user = getUsername()
    group = getSelectedGroup()
    gLogger.always( "User: %s, Group: %s, DN: %s" % ( user , group , dn ) )
    templates = [ "reg_%s.mako" % i for i in [ "done" , "form" , "info" ] ]
    html = [ "reg_%s.html" % i for i in [ "footer" , "header" , "conditions" , "form" , "done" ] ]
    files = templates + html
    basedir = os.path.join( rootPath , "Web" , "dirac" , "templates" )
    for i in files:
      f = os.path.join( basedir , i )
      if not os.path.exists( f ):
        gLogger.error( "File does not exists: %s" % f )
        return render( "web/External.mako" )
    if dn and user == "anonymous":
      upc = UserProfileClient( "Registration" , getRPCClient )
      result =  upc.retrieveVar( dn )
      if result[ "OK" ]:
        c.sent = result[ "Value" ]
        return render( "/reg_done.mako" )
      else:
        return render("/reg_form.mako")
    if not dn or dn == "":
      return render("/reg_info.mako")

    if "site" not in request.params:
      c.select =  gConfig.getValue( "/Website/DefaultExternalURL", "http://diracgrid.org" )
      return render( "web/External.mako" )

    # No idea what this code should do...
    if request.params.has_key( "site" ) and len( request.params[ "site" ] ) > 0:
      if str( request.params[ "site" ] ) != "All":
        c.select = str( request.params[ "site" ] )
        gLogger.debug("Request's body:")
        for key in request.params.keys():
          if not key == "site" and len(request.params[key]) > 0:
            c.select = c.select + "&" + key + "=" + request.params[key]
            try:
              gLogger.debug("%s - %s" % (key,request.params[key]))
            except Exception,x:
              gLogger.error("Exception: %s" % str(x))
              pass
Esempio n. 26
0
 def __getProxyStatus(self, validSeconds=0):
     from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
     proxyManager = ProxyManagerClient()
     group = str(credentials.getSelectedGroup())
     if group == "visitor":
         return {"success": "false", "error": "User not registered"}
     userDN = str(credentials.getUserDN())
     gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" %
                  (userDN, group, validSeconds))
     result = proxyManager.userHasProxy(userDN, group, validSeconds)
     if result["OK"]:
         if result["Value"]:
             c.result = {"success": "true", "result": "true"}
         else:
             c.result = {"success": "true", "result": "false"}
     else:
         c.result = {"success": "false", "error": "false"}
     gLogger.info("\033[0;31m PROXY: \033[0m", result)
     return c.result
Esempio n. 27
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
     }
Esempio n. 28
0
  def registerUser( self ):

    """
    This function is used to notify DIRAC admins about user registration request
    The logic is simple:
    0) Check if request from this e-mail has already registered or not
    1) Send mail to VO admin of requested VO
    2) Send mail to users in group with UserAdministrator property
    3) Send mail to users indicated in /Website/UserRegistrationAdmin option
    """
    
    gLogger.info("Start processing a registration request")

    checkUserCredentials()
    # Check for having a DN but no username
    dn = getUserDN()
    if not dn:
      error = "Certificate is not loaded in the browser or DN is absent"
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    username = getUsername()
    if not username == "anonymous":
      error = "You are already registered in DIRAC with username: %s" % username
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.info( "DN: %s" % dn )

    if not request.params.has_key( "email" ):
      error = "Can not get your email address from the request"
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    userMail = request.params[ "email" ]

    if self.alreadyRequested( userMail ):
      error = "Request associated with %s already registered" % userMail
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }

    vo = fromChar( request.params[ "vo" ] )
    if not vo:
      error = "You should indicate a VirtualOrganization for membership"
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.info( "User want to be register in VO(s): %s" % vo )

    body = str()
    for i in request.params:
      if not i in [ "registration_request" , "email" , "vo" ]:
        info = self.__checkUnicode( i , request.params[ i ] )
        body = body + info + "\n"
    body = body + "DN - " + dn
    gLogger.debug( "email body: %s" % body )

    adminList = self.__getAdminList( vo )
    if not len( adminList ) > 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 }
    adminList = uniqueElements( adminList )
    gLogger.info( "Chosen admin(s): %s" % adminList )
    
    sendDict = self.__getMailDict( adminList )
    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 }
    gLogger.debug( "Final dictionary with mails to be used %s" % sendDict )

    return self.__sendAMail( sendDict , body , userMail )
Esempio n. 29
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}
Esempio n. 30
0
  def __sendMessage( self ):
  
    """
    This function is used to send a mail to specific group of DIRAC user
    Expected parameters from request are group, title, body
    """
    
    gLogger.info("Start message broadcasting")

    checkUserCredentials()
    dn = getUserDN()
    if not dn:
      error = "Certificate is not loaded in the browser or DN is absent"
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    username = getUsername()
    if username == "anonymous":
      error = "Sending an anonymous message is forbidden"
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.info( "DN: %s" % dn )

    email = gConfig.getValue( "/Registry/Users/%s/Email" % username , "" )
    gLogger.debug( "/Registry/Users/%s/Email - '%s'" % ( username , email ) )
    emil = email.strip()
      
    if not email:
      error = "Can't find value for option /Registry/Users/%s/Email" % user
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }

    test = [ "group" , "title" , "body" ]
    for i in test:
      if not i in request.params:
        error = "The required parameter %s is absent in request" % i
        gLogger.error( "Service response: %s" % error )
        return { "success" : "false" , "error" : error }

    group = request.params[ "group" ]
    users = gConfig.getValue( "/Registry/Groups/%s/Users" % group , [] )
    if not len( users ) > 0:
      error = "No users for %s group found" % group
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }

    sendDict = self.getMailDict( users )
    if not len( sendDict ) > 0:
      error = "Can't get a mail address for users in %s group" % group
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.debug( "Final dictionary with mails to be used %s" % sendDict )
    
    title = self.checkUnicode( request.params[ "title" ] )
    gLogger.debug( "email title: %s" % title )

    body = self.checkUnicode( request.params[ "body" ] )
    gLogger.debug( "email body: %s" % body )

    self.__messageLog( user , group , title , body )

    return self.sendMail( sendDict , title , body , email )
Esempio n. 31
0
  def registerUser( self ):

    """
    This function is used to notify DIRAC admins about user registration request
    The logic is simple:
    0) Check if request from this e-mail has already registered or not
    1) Send mail to VO admin of requested VO
    2) Send mail to users in group with UserAdministrator property
    3) Send mail to users indicated in /Website/UserRegistrationAdmin option
    """
    
    gLogger.info("Start processing a registration request")

    checkUserCredentials()
    # Check for having a DN but no username
    dn = getUserDN()
    if not dn:
      error = "Certificate is not loaded in the browser or DN is absent"
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    username = getUsername()
    if not username == "anonymous":
      error = "You are already registered in DIRAC with username: %s" % username
      gLogger.error( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.info( "DN: %s" % dn )

    if not "email" in request.params:
      error = "Can not get your email address from the request"
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    userMail = request.params[ "email" ]

    result = self.isRequested( userMail )
    gLogger.debug( result )
    if result[ "OK" ]:
      return render( "/reg_done.mako" )

    result = self.registerRequest( dn , userMail )
    gLogger.debug( result )
    if not result[ "OK" ]:
      return { "success" : "false" , "error" : result[ "Message" ] }

    vo = fromChar( request.params[ "vo" ] )
    if not vo:
      error = "You should indicate a VirtualOrganization for membership"
      gLogger.debug( "Service response: %s" % error )
      return { "success" : "false" , "error" : error }
    gLogger.info( "User want to be register in VO(s): %s" % vo )

    body = str()
    for i in request.params:
      if not i in [ "registration_request" , "email" , "vo" ]:
        text = self.checkUnicode( request.params[ i ] )
        info = "%s - %s" % ( i , text )
        body = body + info + "\n"
    body = body + "DN - " + dn
    gLogger.debug( "email body: %s" % body )

    adminList = self.__getAdminList( vo )
    if not len( adminList ) > 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 }
    adminList = uniqueElements( adminList )
    gLogger.info( "Chosen admin(s): %s" % adminList )
    
    sendDict = self.getMailDict( adminList )
    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 }
    gLogger.debug( "Final dictionary with mails to be used %s" % sendDict )

    if socket.gethostname().find( '.' ) >= 0:
      hostname = socket.gethostname()
    else:
      hostname = socket.gethostbyaddr( socket.gethostname() )[ 0 ]
    title = "New user has sent registration request to %s" % hostname

    return self.sendMail( sendDict , title , body , userMail )
Esempio n. 32
0
    def registerUser(self):
        """
    This function is used to notify DIRAC admins about user registration request
    The logic is simple:
    0) Check if request from this e-mail has already registered or not
    1) Send mail to VO admin of requested VO
    2) Send mail to users in group with UserAdministrator property
    3) Send mail to users indicated in /Website/UserRegistrationAdmin option
    """

        gLogger.info("Start processing a registration request")

        checkUserCredentials()
        # Check for having a DN but no username
        dn = getUserDN()
        if not dn:
            error = "Certificate is not loaded in the browser or DN is absent"
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}
        username = getUsername()
        if not username == "anonymous":
            error = "You are already registered in DIRAC with username: %s" % username
            gLogger.error("Service response: %s" % error)
            return {"success": "false", "error": error}
        gLogger.info("DN: %s" % dn)

        if not "email" in request.params:
            error = "Can not get your email address from the request"
            gLogger.debug("Service response: %s" % error)
            return {"success": "false", "error": error}
        userMail = request.params["email"]

        result = self.isRequested(userMail)
        gLogger.debug(result)
        if result["OK"]:
            return render("/reg_done.mako")

        result = self.registerRequest(dn, userMail)
        gLogger.debug(result)
        if not result["OK"]:
            return {"success": "false", "error": result["Message"]}

        vo = fromChar(request.params["vo"])
        if not vo:
            error = "You should indicate a VirtualOrganization for membership"
            gLogger.debug("Service response: %s" % error)
            return {"success": "false", "error": error}
        gLogger.info("User want to be register in VO(s): %s" % vo)

        body = str()
        for i in request.params:
            if not i in ["registration_request", "email", "vo"]:
                text = self.checkUnicode(request.params[i])
                info = "%s - %s" % (i, text)
                body = body + info + "\n"
        body = body + "DN - " + dn
        gLogger.debug("email body: %s" % body)

        adminList = self.__getAdminList(vo)
        if not len(adminList) > 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}
        adminList = uniqueElements(adminList)
        gLogger.info("Chosen admin(s): %s" % adminList)

        sendDict = self.getMailDict(adminList)
        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}
        gLogger.debug("Final dictionary with mails to be used %s" % sendDict)

        if socket.gethostname().find('.') >= 0:
            hostname = socket.gethostname()
        else:
            hostname = socket.gethostbyaddr(socket.gethostname())[0]
        title = "New user has sent registration request to %s" % hostname

        return self.sendMail(sendDict, title, body, userMail)
Esempio n. 33
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}
Esempio n. 34
0
  def __componentAction( self , action = None ):

    """
    Actions which should be done on components. The only parameters is an action
    to perform.
    Returns standard JSON response structure with with service response
    or error messages
    """

    DN = getUserDN()
    group = getSelectedGroup()

    if ( not action ) or ( not len( action ) > 0 ):
      error = "Action is not defined or has zero length"
      gLogger.debug( error )
      return { "success" : "false" , "error" : error }

    if action not in [ "restart" , "start" , "stop" , "uninstall" ]:
      error = "The request parameters action '%s' is unknown" % action
      gLogger.debug( error )
      return { "success" : "false" , "error" : error }
    self.action = action

    result = dict()
    for i in request.params:
      if i == "action":
        continue

      target = i.split( " @ " , 1 )
      if not len( target ) == 2:
        continue

      system = request.params[ i ]
      gLogger.always( "System: %s" % system )
      host = target[ 1 ]
      gLogger.always( "Host: %s" % host )
      component = target[ 0 ]
      gLogger.always( "Component: %s" % component )
      if not host in result:
        result[ host ] = list()
      result[ host ].append( [ system , component ] )

    if not len( result ) > 0:
      error = "Failed to get component(s) for %s" % action
      gLogger.debug( error )
      return { "success" : "false" , "error" : error }
      
    gLogger.always( result )
    self.actionSuccess = list()
    self.actionFailed = list()

    for hostname in result.keys():

      if not len( result[ hostname ] ) > 0:
        continue

      client = SystemAdministratorClient( hostname , None , delegatedDN=DN ,
                                          delegatedGroup=group )

      for i in result[ hostname ]:

        system = i[ 0 ]
        component = i[ 1 ]

        try:
          if action == "restart":
            result = client.restartComponent( system , component )
          elif action == "start":
            result = client.startComponent( system , component )
          elif action == "stop":
            result = client.stopComponent( system , component )
          elif action == "uninstall":
            result = client.uninstallComponent( system , component )
          else:
            result = list()
            result[ "Message" ] = "Action %s is not valid" % action
        except Exception, x:
          result = list()
          result[ "Message" ] = "Exception: %s" % str( x )
        gLogger.debug( "Result: %s" % result )

        if not result[ "OK" ]:
          error = hostname + ": " + result[ "Message" ]
          self.actionFailed.append( error )
          gLogger.error( "Failure during component %s: %s" % ( action , error ) )
        else:
          gLogger.always( "Successfully %s component %s" % ( action , component ) )
          self.actionSuccess.append( component )