Beispiel #1
0
    def _process(self):

        if self._params.get("Cancel", None) is not None:
            p = adminPages.WPUserDetails(self, self._avatar)
            return p.display()

        msg = ""
        ok = False
        if self._ok:
            ok = True
            ih = AuthenticatorMgr()
            #first, check if login is free
            if not ih.isLoginFree(self._login):
                msg += "Sorry, the login you requested is already in use. Please choose another one.<br>"
                ok = False
            if not self._pwd:
                msg += "you must enter a password<br>"
                ok = False
            #then, check if password is OK
            if self._pwd != self._pwdBis:
                msg += "You must enter the same password twice<br>"
                ok = False
            if ok:
                #create the indentity
                li = user.LoginInfo(self._login, self._pwd)
                id = ih.createIdentity(li, self._avatar, self._system)
                ih.add(id)
                self._redirect(urlHandlers.UHUserDetails.getURL(self._avatar))
                return

        self._params["msg"] = msg
        p = adminPages.WPIdentityCreation(self, self._avatar, self._params)
        return p.display()
Beispiel #2
0
    def _process( self ):

        if self._params.get("Cancel",None) is not None :
            p = adminPages.WPUserDetails( self, self._avatar )
            return p.display()

        msg = ""
        ok = False
        if self._ok:
            ok = True
            ih = AuthenticatorMgr()
            #first, check if login is free
            if not ih.isLoginFree(self._login):
                msg += "Sorry, the login you requested is already in use. Please choose another one.<br>"
                ok = False
            if not self._pwd:
                msg += "you must enter a password<br>"
                ok = False
            #then, check if password is OK
            if self._pwd != self._pwdBis:
                msg += "You must enter the same password twice<br>"
                ok = False
            if ok:
                #create the indentity
                li = user.LoginInfo( self._login, self._pwd )
                id = ih.createIdentity( li, self._avatar, self._system )
                ih.add( id )
                self._redirect( urlHandlers.UHUserDetails.getURL( self._avatar ) )
                return

        self._params["msg"] = msg
        p = adminPages.WPIdentityCreation( self, self._avatar, self._params )
        return p.display()
Beispiel #3
0
def create_dummy_user():
    """
    Creates a dummy user for testing purposes
    """
    avatar = Avatar()

    avatar.setName("fake")
    avatar.setSurName("fake")
    avatar.setOrganisation("fake")
    avatar.setLang("en_GB")
    avatar.setEmail("*****@*****.**")

    # registering user
    ah = AvatarHolder()
    ah.add(avatar)

    # setting up the login info
    li = LoginInfo("dummyuser", "dummyuser")
    ih = AuthenticatorMgr()
    userid = ih.createIdentity(li, avatar, "Local")
    ih.add(userid)

    # activate the account
    avatar.activateAccount()

    # since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()

    al = minfo.getAdminList()
    al.grant(avatar)

    dc = DefaultConference()
    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(dc)
    return avatar
Beispiel #4
0
def create_dummy_user():
    """
    Creates a dummy user for testing purposes
    """
    avatar = Avatar()

    avatar.setName("fake")
    avatar.setSurName("fake")
    avatar.setOrganisation("fake")
    avatar.setLang("en_GB")
    avatar.setEmail("*****@*****.**")

    # registering user
    ah = AvatarHolder()
    ah.add(avatar)

    # setting up the login info
    li = LoginInfo("dummyuser", "dummyuser")
    ih = AuthenticatorMgr()
    userid = ih.createIdentity(li, avatar, "Local")
    ih.add(userid)

    # activate the account
    avatar.activateAccount()

    # since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()

    al = minfo.getAdminList()
    al.grant(avatar)

    dc = DefaultConference()
    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(dc)
    return avatar
Beispiel #5
0
    def _run(self, args):
        avatar = Avatar()

        name = raw_input("New administrator name: ").strip()
        surname = raw_input("New administrator surname: ").strip()
        organization = raw_input("New administrator organization: ").strip()
        email = raw_input("New administrator email: ").strip()
        login = raw_input("New administrator login: "******"New administrator password: "******"Retype administrator password: "******"Sorry, passwords do not match")

        avatar.setName(name)
        avatar.setSurName(surname)
        avatar.setOrganisation(organization)
        avatar.setLang("en_GB")
        avatar.setEmail(email)

        self.printUserInfo(avatar)

        if console.yesno("Are you sure to create and grant administrator privileges to this user?"):
            avatar.activateAccount()
            loginInfo = LoginInfo(login, password)
            authMgr = AuthenticatorMgr()
            userid = authMgr.createIdentity(loginInfo, avatar, "Local")
            authMgr.add(userid)
            adminList = info.HelperMaKaCInfo.getMaKaCInfoInstance().getAdminList()
            AvatarHolder().add(avatar)
            adminList.grant(avatar)
            print "New administrator created successfully with id: %s" % avatar.getId()
Beispiel #6
0
    def _run(self, args):
        avatar = Avatar()

        name = raw_input("New administrator name: ").strip()
        surname = raw_input("New administrator surname: ").strip()
        organization = raw_input("New administrator organization: ").strip()
        email = raw_input("New administrator email: ").strip()
        login = raw_input("New administrator login: "******"New administrator password: "******"Retype administrator password: "******"Sorry, passwords do not match")

        avatar.setName(name)
        avatar.setSurName(surname)
        avatar.setOrganisation(organization)
        avatar.setLang("en_GB")
        avatar.setEmail(email)

        self.printUserInfo(avatar)

        if console.yesno(
                "Are you sure to create and grant administrator privileges to this user?"
        ):
            avatar.activateAccount()
            loginInfo = LoginInfo(login, password)
            authMgr = AuthenticatorMgr()
            userid = authMgr.createIdentity(loginInfo, avatar, "Local")
            authMgr.add(userid)
            adminList = info.HelperMaKaCInfo.getMaKaCInfoInstance(
            ).getAdminList()
            AvatarHolder().add(avatar)
            adminList.grant(avatar)
            print "New administrator created successfully with id: %s" % avatar.getId(
            )
Beispiel #7
0
class TestAuthentication(IndicoTestCase):
    _requires = ['db.Database']

    def setUp(self):
        super(TestAuthentication, self).setUp()

        with self._context("database"):
            # Create few users and groups
            gh = GroupHolder()
            ah = AvatarHolder()
            self._authMgr = AuthenticatorMgr()

            for i in xrange(1, 3):
                group = Group()
                group.setName("fake-group-%d" % i)
                group.setDescription("fake")
                group.setEmail("*****@*****.**" % i)
                group.setId("fake-group-%d" % i)
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("fake-%d" % i)
                avatar.activateAccount()
                group.addMember(avatar)
                ah.add(avatar)
                gh.add(group)
                identity = self._authMgr.createIdentity(LoginInfo("fake-%d" % i, "fake-%d" % i), avatar, "Local")
                self._authMgr.add(identity)

    @with_context('database')
    def testAvatarHolder(self):
        """
        Test Avatar Holder
        """
        ah = AvatarHolder()
        self.assertEqual(ah.getById("fake-1").getName(), "fake-1")
        self.assertEqual(ah.match({"name": "fake-1"}, searchInAuthenticators=False)[0].getEmail(), "*****@*****.**")
        self.assertEqual(len(ah.matchFirstLetter("name", "f", searchInAuthenticators=False)), 2)

    @with_context('database')
    def testGroupHolder(self):
        gh = GroupHolder()
        ah = AvatarHolder()
        self.assert_(gh.getById("fake-group-1").containsUser(ah.getById("fake-1")))
        self.assertEqual(gh.match({"groupname": "fake-group-1"}, searchInAuthenticators=False)[0].getEmail(),
                         "*****@*****.**")
        self.assertEqual(len(gh.matchFirstLetter("f", searchInAuthenticators=False)), 2)

    @with_context('database')
    def testIdentities(self):
        ah = AvatarHolder()
        for i in xrange(1, 3):
            self.assertEqual(self._authMgr.getAvatar(LoginInfo("fake-%d" % i, "fake-%d" % i)),
                             ah.getById("fake-%d" % i))
Beispiel #8
0
 def _process(self):
     authManager = AuthenticatorMgr()
     #first, check if login is free
     if not authManager.isLoginAvailable(self._login):
         self._redirect(self._fromURL + "&msg=Login not avaible")
         return
     #then, check if password is OK
     if self._pwd != self._pwdBis:
         self._redirect(self._fromURL + "&msg=You must enter the same password twice")
         return
     #create the indentity
     li = user.LoginInfo( self._login, self._pwd )
     id = authManager.createIdentity( li, self._avatar, self._system )
     authManager.add( id )
     #commit and if OK, send activation mail
     DBMgr.getInstance().commit()
     scr = mail.sendConfirmationRequest(self._avatar)
     scr.send()
     self._redirect(urlHandlers.UHUserDetails.getURL(self._avatar))  # to set to the returnURL
Beispiel #9
0
 def _process( self ):
     ih = AuthenticatorMgr()
     #first, check if login is free
     if not ih.isLoginFree(self._login):
         self._redirect(self._fromURL + "&msg=Login not avaible")
         return
     #then, check if password is OK
     if self._pwd != self._pwdBis:
         self._redirect(self._fromURL + "&msg=You must enter the same password twice")
         return
     #create the indentity
     li = user.LoginInfo( self._login, self._pwd )
     id = ih.createIdentity( li, self._avatar, self._system )
     ih.add( id )
     #commit and if OK, send activation mail
     DBMgr.getInstance().commit()
     scr = mail.sendConfirmationRequest(self._avatar)
     scr.send()
     self._redirect( urlHandlers.UHUserDetails.getURL( self._avatar ) ) #to set to the returnURL
Beispiel #10
0
def user_create(grant_admin):
    """Creates new user"""
    avatar = Avatar()
    user_type = 'user' if not grant_admin else 'admin'

    print()
    name = prompt("First name")
    surname = prompt("Last name")
    organization = prompt("Affiliation")
    print()
    login = prompt("Enter username")
    email = prompt_email().encode('utf-8')
    if email is None:
        return
    password = prompt_pass().encode('utf-8')
    if password is None:
        return

    avatar.setName(name)
    avatar.setSurName(surname)
    avatar.setOrganisation(organization)
    avatar.setLang("en_GB")
    avatar.setEmail(email)
    print_user_info(avatar)

    if prompt_bool(cformat("%{yellow}Create the new {}?").format(user_type), default=True):
        from MaKaC.authentication import AuthenticatorMgr
        avatar.activateAccount()
        login_info = LoginInfo(login, password)
        auth_mgr = AuthenticatorMgr()
        try:
            user_id = auth_mgr.createIdentity(login_info, avatar, "Local")
            auth_mgr.add(user_id)
            AvatarHolder().add(avatar)
            if grant_admin:
                admin_list = HelperMaKaCInfo.getMaKaCInfoInstance().getAdminList()
                admin_list.grant(avatar)
            success("New {} created successfully with ID: {}".format(user_type, avatar.getId()))
        except UserError as e:
            error("Error: {}".format(str(e)))
Beispiel #11
0
    def start(self, obj):
        super(RoomBooking_Feature, self).start(obj)

        with obj._context('database'):
            # Tell indico to use the current database for roombooking stuff
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            cfg = Configuration.Config.getInstance()
            minfo.setRoomBookingDBConnectionParams(cfg.getDBConnectionParams())

            obj._ph.getById('RoomBooking').setActive(True)

            DALManagerCERN.connect()
            initializeRoomBookingDB("Universe", force=False)
            DALManagerCERN.disconnect()
            # do not use the method for it as it tries to re-create jsvars and fails
            minfo._roomBookingModuleActive = True
            DALManagerCERN.connect()

            # Create dummy avatars in obj._avatarN
            ah = AvatarHolder()
            obj._avatars = []
            for i in xrange(1, 5):
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("rb-fake-%d" % i)

                # setting up the login info
                li = LoginInfo("fake-%d" % i, "fake-%d" % i)
                ih = AuthenticatorMgr()
                userid = ih.createIdentity(li, avatar, "Local")
                ih.add(userid)

                # activate the account
                avatar.activateAccount()

                ah.add(avatar)
                obj._avatars.append(avatar)
                setattr(obj, '_avatar%d' % i, avatar)

            # Create dummy rooms in obj._roomN - owners are fake1 and fake2 (r1 has f1, r2 has f2, r3 has f1, ...)
            location = Location.getDefaultLocation()
            obj._rooms = []
            for i in xrange(1, 8):
                room = location.newRoom()
                room.locationName = location.friendlyName
                room.name = 'DummyRoom%d' % i
                room.site = 'a'
                room.building = 1
                room.floor = 'b'
                room.roomNr = 'c'
                room.latitude = ''
                room.longitude = ''
                room.isActive = True
                room.isReservable = True
                room.resvsNeedConfirmation = False
                room.responsibleId = 'rb-fake-%d' % (((i - 1) % 2) + 1)
                room.whereIsKey = 'Nowhere'
                room.telephone = '123456789'
                room.capacity = 10
                room.division = ''
                room.surfaceArea = 50
                room.comments = ''
                room.setEquipment([])
                room.setAvailableVC([])
                room.insert()
                obj._rooms.append(room)
                setattr(obj, '_room%d' % i, room)
Beispiel #12
0
    def start(self, obj):
        super(RoomBooking_Feature, self).start(obj)

        with obj._context('database'):
            # Tell indico to use the current database for roombooking stuff
            minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
            cfg = Configuration.Config.getInstance()
            minfo.setRoomBookingDBConnectionParams(cfg.getDBConnectionParams())

            obj._ph.getById('RoomBooking').setActive(True)

            DALManagerCERN.connect()
            initializeRoomBookingDB("Universe", force=False)
            DALManagerCERN.disconnect()
            # do not use the method for it as it tries to re-create jsvars and fails
            minfo._roomBookingModuleActive = True
            DALManagerCERN.connect()

            # Create dummy avatars in obj._avatarN
            ah = AvatarHolder()
            obj._avatars = []
            for i in xrange(1, 5):
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("rb-fake-%d" % i)

                # setting up the login info
                li = LoginInfo("fake-%d" % i, "fake-%d" % i)
                ih = AuthenticatorMgr()
                userid = ih.createIdentity(li, avatar, "Local")
                ih.add(userid)

                # activate the account
                avatar.activateAccount()

                ah.add(avatar)
                obj._avatars.append(avatar)
                setattr(obj, '_avatar%d' % i, avatar)

            # Create dummy rooms in obj._roomN - owners are fake1 and fake2 (r1 has f1, r2 has f2, r3 has f1, ...)
            location = Location.getDefaultLocation()
            obj._rooms = []
            for i in xrange(1, 8):
                room = location.newRoom()
                room.locationName = location.friendlyName
                room.name = 'DummyRoom%d' % i
                room.site = 'a'
                room.building = 1
                room.floor = 'b'
                room.roomNr = 'c'
                room.latitude = ''
                room.longitude = ''
                room.isActive = True
                room.isReservable = True
                room.resvsNeedConfirmation = False
                room.responsibleId = 'rb-fake-%d' % (((i - 1) % 2) + 1)
                room.whereIsKey = 'Nowhere'
                room.telephone = '123456789'
                room.capacity = 10
                room.division = ''
                room.surfaceArea = 50
                room.comments = ''
                room.setEquipment([])
                room.setAvailableVC([])
                room.insert()
                obj._rooms.append(room)
                setattr(obj, '_room%d' % i, room)
Beispiel #13
0
def runTests(host='localhost', port=FAKE_SERVICE_PORT,
             scenarios=[(2, 10)]):

    execTimes = []

    agent = InvenioBatchUploaderAgent('test1', 'test1', 'test',
                                      0, 'http://%s:%s' \
                                      % (host, port))

    ph = PluginsHolder()
    ph.reloadAllPlugins()
    ph.getPluginType('livesync').toggleActive()
    do = DummyObservable()

    do._notify('updateDBStructures', 'indico.ext.livesync',
                              None, None, None)

    sm = SyncManager.getDBInstance()

    sm.registerNewAgent(agent)

    cm = CategoryManager()

    avatar = user.Avatar()
    avatar.setName( "fake" )
    avatar.setSurName( "fake" )
    avatar.setOrganisation( "fake" )
    avatar.setLang( "en_GB" )
    avatar.setEmail( "*****@*****.**" )

    #registering user
    ah = user.AvatarHolder()
    ah.add(avatar)

    #setting up the login info
    li = user.LoginInfo("dummyuser", None)
    am = AuthenticatorMgr()
    userid = am.createIdentity( li, avatar, "Local" )
    am.add( userid )

    #activate the account
    avatar.activateAccount()

    #since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    al = minfo.getAdminList()
    al.grant( avatar )

    dummy = avatar

    ContextManager.destroy()

    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(DefaultConference())

    cm.getRoot()

    do._notify('requestStarted')

    home = cm.getById('0')

    # execute code
    for nconf in range(0, 1000):
        conf = home.newConference(dummy)
        conf.setTitle('Test Conference %s' % nconf)

    do._notify('requestFinished')

    time.sleep(1)

    # params won't be used
    task = LiveSyncUpdateTask(dateutil.rrule.MINUTELY)

    for scen in scenarios:

        print "Scenario %s workers, size = %s " % scen,

        # configure scenario
        InvenioBatchUploaderAgent.NUM_WORKERS = scen[0]
        InvenioBatchUploaderAgent.BATCH_SIZE = scen[1]

        ts = time.time()
        # just run it
        task.run()

        te = time.time()
        execTimes.append(te - ts)

        print "%s" % (te - ts)

        sm._track._pointers['test1'] = None

    for i in range(0, len(execTimes)):
        results[scenarios[i]] = execTimes[i]
def runTests(host='localhost', port=FAKE_SERVICE_PORT,
             scenarios=[(2, 10)]):

    execTimes = []

    agent = InvenioBatchUploaderAgent('test1', 'test1', 'test',
                                      0, 'http://%s:%s' \
                                      % (host, port))

    ph = PluginsHolder()
    ph.reloadAllPlugins()
    ph.getPluginType('livesync').toggleActive()
    do = DummyObservable()

    do._notify('updateDBStructures', 'indico.ext.livesync',
                              None, None, None)

    sm = SyncManager.getDBInstance()

    sm.registerNewAgent(agent)

    cm = CategoryManager()

    avatar = user.Avatar()
    avatar.setName( "fake" )
    avatar.setSurName( "fake" )
    avatar.setOrganisation( "fake" )
    avatar.setLang( "en_GB" )
    avatar.setEmail( "*****@*****.**" )

    #registering user
    ah = user.AvatarHolder()
    ah.add(avatar)

    #setting up the login info
    li = user.LoginInfo( "dummyuser", "dummyuser" )
    ih = AuthenticatorMgr()
    userid = ih.createIdentity( li, avatar, "Local" )
    ih.add( userid )

    #activate the account
    avatar.activateAccount()

    #since the DB is empty, we have to add dummy user as admin
    minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
    al = minfo.getAdminList()
    al.grant( avatar )

    dummy = avatar

    ContextManager.destroy()

    HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference(DefaultConference())

    cm.getRoot()

    do._notify('requestStarted')

    home = cm.getById('0')

    # execute code
    for nconf in range(0, 1000):
        conf = home.newConference(dummy)
        conf.setTitle('Test Conference %s' % nconf)

    do._notify('requestFinished')

    time.sleep(1)

    # params won't be used
    task = LiveSyncUpdateTask(dateutil.rrule.MINUTELY)

    for scen in scenarios:

        print "Scenario %s workers, size = %s " % scen,

        # configure scenario
        InvenioBatchUploaderAgent.NUM_WORKERS = scen[0]
        InvenioBatchUploaderAgent.BATCH_SIZE = scen[1]

        ts = time.time()
        # just run it
        task.run()

        te = time.time()
        execTimes.append(te - ts)

        print "%s" % (te - ts)

        sm._track._pointers['test1'] = None

    for i in range(0, len(execTimes)):
        results[scenarios[i]] = execTimes[i]
class TestAuthentication(IndicoTestCase):
    _requires = ['db.Database']

    def setUp(self):
        super(TestAuthentication, self).setUp()

        with self._context("database"):
            # Create few users and groups
            gh = GroupHolder()
            ah = AvatarHolder()
            self._authMgr = AuthenticatorMgr()

            for i in xrange(1, 3):
                group = Group()
                group.setName("fake-group-%d" % i)
                group.setDescription("fake")
                group.setEmail("*****@*****.**" % i)
                group.setId("fake-group-%d" % i)
                avatar = Avatar()
                avatar.setName("fake-%d" % i)
                avatar.setSurName("fake")
                avatar.setOrganisation("fake")
                avatar.setLang("en_GB")
                avatar.setEmail("*****@*****.**" % i)
                avatar.setId("fake-%d" % i)
                avatar.activateAccount()
                group.addMember(avatar)
                ah.add(avatar)
                gh.add(group)
                identity = self._authMgr.createIdentity(
                    LoginInfo("fake-%d" % i, "fake-%d" % i), avatar, "Local")
                self._authMgr.add(identity)

    @with_context('database')
    def testAvatarHolder(self):
        """
        Test Avatar Holder
        """
        ah = AvatarHolder()
        self.assertEqual(ah.getById("fake-1").getName(), "fake-1")
        self.assertEqual(
            ah.match({"name": "fake-1"},
                     searchInAuthenticators=False)[0].getEmail(),
            "*****@*****.**")
        self.assertEqual(
            len(ah.matchFirstLetter("name", "f",
                                    searchInAuthenticators=False)), 2)

    @with_context('database')
    def testGroupHolder(self):
        gh = GroupHolder()
        ah = AvatarHolder()
        self.assert_(
            gh.getById("fake-group-1").containsUser(ah.getById("fake-1")))
        self.assertEqual(
            gh.match({"groupname": "fake-group-1"},
                     searchInAuthenticators=False)[0].getEmail(),
            "*****@*****.**")
        self.assertEqual(
            len(gh.matchFirstLetter("f", searchInAuthenticators=False)), 2)

    @with_context('database')
    def testIdentities(self):
        ah = AvatarHolder()
        for i in xrange(1, 3):
            self.assertEqual(
                self._authMgr.getAvatar(LoginInfo("fake-%d" % i,
                                                  "fake-%d" % i)),
                ah.getById("fake-%d" % i))
Beispiel #16
0
 def _process(self):
     save = False
     authManager = AuthenticatorMgr()
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     self._params["msg"] = ""
     if self._save:
         save = True
         #check submited data
         if not self._params.get("name",""):
             self._params["msg"] += _("You must enter a name.")+"<br>"
             save = False
         if not self._params.get("surName",""):
             self._params["msg"] += _("You must enter a surname.")+"<br>"
             save = False
         if not self._params.get("organisation",""):
             self._params["msg"] += _("You must enter the name of your organisation.")+"<br>"
             save = False
         if not self._params.get("email",""):
             self._params["msg"] += _("You must enter an email address.")+"<br>"
             save = False
         if not self._params.get("login",""):
             self._params["msg"] += _("You must enter a login.")+"<br>"
             save = False
         if not self._params.get("password",""):
             self._params["msg"] += _("You must define a password.")+"<br>"
             save = False
         if self._params.get("password","") != self._params.get("passwordBis",""):
             self._params["msg"] += _("You must enter the same password twice.")+"<br>"
             save = False
         if not authManager.isLoginAvailable(self._params.get("login", "")):
             self._params["msg"] += _("Sorry, the login you requested is already in use. Please choose another one.")+"<br>"
             save = False
         if not self._validMail(self._params.get("email","")):
             self._params["msg"] += _("You must enter a valid email address")
             save = False
     if save:
         #Data are OK, Now check if there is an existing user or create a new one
         ah = user.AvatarHolder()
         res =  ah.match({"email": self._params["email"]}, exact=1, searchInAuthenticators=False)
         if res:
             #we find a user with the same email
             a = res[0]
             #check if the user have an identity:
             if a.getIdentityList():
                 self._redirect(urlHandlers.UHConfUserExistWithIdentity.getURL(self._conf, a))
                 return
             else:
                 #create the identity to the user and send the comfirmation email
                 li = user.LoginInfo(self._params["login"], self._params["password"])
                 id = authManager.createIdentity(li, a, "Local")
                 authManager.add(id)
                 DBMgr.getInstance().commit()
                 if minfo.getModerateAccountCreation():
                     mail.sendAccountCreationModeration(a).send()
                 else:
                     mail.sendConfirmationRequest(a, self._conf).send()
                     if minfo.getNotifyAccountCreation():
                         mail.sendAccountCreationNotification(a).send()
         else:
             a = user.Avatar()
             _UserUtils.setUserData( a, self._params )
             ah.add(a)
             li = user.LoginInfo( self._params["login"], self._params["password"] )
             id = authManager.createIdentity( li, a, "Local" )
             authManager.add( id )
             DBMgr.getInstance().commit()
             if minfo.getModerateAccountCreation():
                 mail.sendAccountCreationModeration(a).send()
             else:
                 mail.sendConfirmationRequest(a).send()
                 if minfo.getNotifyAccountCreation():
                     mail.sendAccountCreationNotification(a).send()
         self._redirect( urlHandlers.UHConfUserCreated.getURL( self._conf, a ) )
     else:
         p = conferences.WPConfUserCreation( self, self._conf, self._params )
         return p.display()
Beispiel #17
0
def _import(self, file):
    # check Registration period
    import datetime
    import pytz
    utc = pytz.UTC
    startDate = self._conf.getRegistrationForm().getStartRegistrationDate()
    endDate = self._conf.getRegistrationForm().getEndRegistrationDate()
    current = datetime.datetime.now()
    current = utc.localize(current)

    if (current < startDate or current > endDate):
        raise NoReportError(
            "Import registrants not authorized, outside registration period.")

    reader = csv.DictReader(file)
    i = 1
    errors = []

    successfuls = []
    unsuccessfuls = []

    for row in reader:
        try:
            # row['Email'] = row['Email'].lower()
            self._processImportData(row)
            matchedUsers = AvatarHolder().match({"email": row['Email']},
                                                exact=1)
            if matchedUsers:
                user = matchedUsers[0]
            elif ('Account Creation' in row) and row['Account Creation'].lower(
            ) == 'yes':  # account creation
                avData = self._mapAvatar(row)
                user = Avatar(avData)
                user.activateAccount()
                login_info = LoginInfo(row['Login'], row['Password'])
                auth_mgr = AuthenticatorMgr()
                user_id = auth_mgr.createIdentity(login_info, user, "Local")
                auth_mgr.add(user_id)
                AvatarHolder().add(user)
            else:
                user = None

            if not (user):
                reg = Registrant()  # new registration
                self._conf.addRegistrant(reg, user)
            else:
                if user.isRegisteredInConf(self._conf):
                    reg = self._conf.getRegistrantsByEmail(user.getEmail())
                else:  # not registered, new registration
                    reg = Registrant()
                    reg.setAvatar(user)
                    self._conf.addRegistrant(reg, user)
                    user.addRegistrant(reg)

            regData = self._mapRegistrant(row)
            regData['import'] = 'import'
            reg.setValues(regData, user)
            self._setAffiliation(reg)
            successfuls.append(reg.getFullName())
        except Exception:
            errors.append(i)
            unsuccessfuls.append(
                row["Surname"] + ", " + row["First Name"]
            )  # exception : reg or user might not be defined yet
        finally:
            i += 1
    self.logimport(successfuls, unsuccessfuls)
    return errors
 def _process(self):
     save = False
     authManager = AuthenticatorMgr()
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     self._params["msg"] = ""
     if self._save:
         save = True
         #check submited data
         if not self._params.get("name", ""):
             self._params["msg"] += _("You must enter a name.") + "<br>"
             save = False
         if not self._params.get("surName", ""):
             self._params["msg"] += _("You must enter a surname.") + "<br>"
             save = False
         if not self._params.get("organisation", ""):
             self._params["msg"] += _(
                 "You must enter the name of your organisation.") + "<br>"
             save = False
         if not self._params.get("email", ""):
             self._params["msg"] += _(
                 "You must enter an email address.") + "<br>"
             save = False
         if not self._params.get("login", ""):
             self._params["msg"] += _("You must enter a login.") + "<br>"
             save = False
         if not self._params.get("password", ""):
             self._params["msg"] += _(
                 "You must define a password.") + "<br>"
             save = False
         if self._params.get("password", "") != self._params.get(
                 "passwordBis", ""):
             self._params["msg"] += _(
                 "You must enter the same password twice.") + "<br>"
             save = False
         if not authManager.isLoginAvailable(self._params.get("login", "")):
             self._params["msg"] += _(
                 "Sorry, the login you requested is already in use. Please choose another one."
             ) + "<br>"
             save = False
         if not self._validMail(self._params.get("email", "")):
             self._params["msg"] += _(
                 "You must enter a valid email address")
             save = False
     if save:
         #Data are OK, Now check if there is an existing user or create a new one
         ah = user.AvatarHolder()
         res = ah.match({"email": self._params["email"]},
                        exact=1,
                        searchInAuthenticators=False)
         if res:
             #we find a user with the same email
             a = res[0]
             #check if the user have an identity:
             if a.getIdentityList():
                 self._redirect(
                     urlHandlers.UHConfUserExistWithIdentity.getURL(
                         self._conf, a))
                 return
             else:
                 #create the identity to the user and send the comfirmation email
                 li = user.LoginInfo(self._params["login"],
                                     self._params["password"])
                 id = authManager.createIdentity(li, a, "Local")
                 authManager.add(id)
                 DBMgr.getInstance().commit()
                 if minfo.getModerateAccountCreation():
                     mail.sendAccountCreationModeration(a).send()
                 else:
                     mail.sendConfirmationRequest(a, self._conf).send()
                     if minfo.getNotifyAccountCreation():
                         mail.sendAccountCreationNotification(a).send()
         else:
             a = user.Avatar()
             _UserUtils.setUserData(a, self._params)
             ah.add(a)
             li = user.LoginInfo(self._params["login"],
                                 self._params["password"])
             id = authManager.createIdentity(li, a, "Local")
             authManager.add(id)
             DBMgr.getInstance().commit()
             if minfo.getModerateAccountCreation():
                 mail.sendAccountCreationModeration(a).send()
             else:
                 mail.sendConfirmationRequest(a).send()
                 if minfo.getNotifyAccountCreation():
                     mail.sendAccountCreationNotification(a).send()
         self._redirect(urlHandlers.UHConfUserCreated.getURL(self._conf, a))
     else:
         p = conferences.WPConfUserCreation(self, self._conf, self._params)
         return p.display()
Beispiel #19
0
 def _process(self):
     save = False
     ih = AuthenticatorMgr()
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     self._params["msg"] = ""
     if self._save:
         save = True
         #check submited data
         if not self._params.get("name", ""):
             self._params["msg"] += _("You must enter a name.") + "<br>"
             save = False
         if not self._params.get("surName", ""):
             self._params["msg"] += _("You must enter a surname.") + "<br>"
             save = False
         if not self._params.get("organisation", ""):
             self._params["msg"] += _(
                 "You must enter the name of your organisation.") + "<br>"
             save = False
         if not self._params.get("email", ""):
             self._params["msg"] += _(
                 "You must enter an email address.") + "<br>"
             save = False
         if not self._params.get("login", ""):
             self._params["msg"] += _("You must enter a login.") + "<br>"
             save = False
         if not self._params.get("password", ""):
             self._params["msg"] += _(
                 "You must define a password.") + "<br>"
             save = False
         if self._params.get("password", "") != self._params.get(
                 "passwordBis", ""):
             self._params["msg"] += _(
                 "You must enter the same password twice.") + "<br>"
             save = False
         if not ih.isLoginFree(self._params.get("login", "")):
             self._params["msg"] += _(
                 "Sorry, the login you requested is already in use. Please choose another one."
             ) + "<br>"
             save = False
         if not self._validMail(self._params.get("email", "")):
             self._params["msg"] += _(
                 "You must enter a valid email address")
             save = False
     if save:
         #Data are OK, Now check if there is an existing user or create a new one
         ah = user.AvatarHolder()
         res = ah.match({"email": self._params["email"]},
                        exact=1,
                        forceWithoutExtAuth=True)
         if res:
             #we find a user with the same email
             a = res[0]
             #check if the user have an identity:
             if a.getIdentityList():
                 self._redirect(
                     urlHandlers.UHUserExistWithIdentity.getURL(a))
                 return
             else:
                 #create the identity to the user and send the comfirmatio email
                 _UserUtils.setUserData(a, self._params)
                 li = user.LoginInfo(self._params["login"],
                                     self._params["password"])
                 id = ih.createIdentity(li, a, "Local")
                 ih.add(id)
                 DBMgr.getInstance().commit()
                 if minfo.getModerateAccountCreation():
                     mail.sendAccountCreationModeration(a).send()
                 else:
                     mail.sendConfirmationRequest(a).send()
                     if minfo.getNotifyAccountCreation():
                         mail.sendAccountCreationNotification(a).send()
         else:
             a = user.Avatar()
             _UserUtils.setUserData(a, self._params)
             ah.add(a)
             li = user.LoginInfo(self._params["login"],
                                 self._params["password"])
             id = ih.createIdentity(li, a, "Local")
             ih.add(id)
             DBMgr.getInstance().commit()
             if minfo.getModerateAccountCreation():
                 mail.sendAccountCreationModeration(a).send()
             else:
                 mail.sendConfirmationRequest(a).send()
                 if minfo.getNotifyAccountCreation():
                     mail.sendAccountCreationNotification(a).send()
         self._redirect(urlHandlers.UHUserCreated.getURL(a))
     else:
         cp = None
         if self._params.has_key("cpEmail"):
             ph = pendingQueues.PendingQueuesHolder()
             cp = ph.getFirstPending(self._params["cpEmail"])
         if self._aw.getUser() and self._aw.getUser() in minfo.getAdminList(
         ).getList():
             p = adminPages.WPUserCreation(self, self._params, cp)
         else:
             p = adminPages.WPUserCreationNonAdmin(self, self._params, cp)
         return p.display()
Beispiel #20
0
 def _process( self ):
     save = False
     ih = AuthenticatorMgr()
     minfo = info.HelperMaKaCInfo.getMaKaCInfoInstance()
     self._params["msg"] = ""
     if self._save:
         save = True
         #check submited data
         if not self._params.get("name",""):
             self._params["msg"] += _("You must enter a name.")+"<br>"
             save = False
         if not self._params.get("surName",""):
             self._params["msg"] += _("You must enter a surname.")+"<br>"
             save = False
         if not self._params.get("organisation",""):
             self._params["msg"] += _("You must enter the name of your organisation.")+"<br>"
             save = False
         if not self._params.get("email",""):
             self._params["msg"] += _("You must enter an email address.")+"<br>"
             save = False
         if not self._params.get("login",""):
             self._params["msg"] += _("You must enter a login.")+"<br>"
             save = False
         if not self._params.get("password",""):
             self._params["msg"] += _("You must define a password.")+"<br>"
             save = False
         if self._params.get("password","") != self._params.get("passwordBis",""):
             self._params["msg"] += _("You must enter the same password twice.")+"<br>"
             save = False
         if not ih.isLoginFree(self._params.get("login","")):
             self._params["msg"] += _("Sorry, the login you requested is already in use. Please choose another one.")+"<br>"
             save = False
         if not self._validMail(self._params.get("email","")):
             self._params["msg"]+= _("You must enter a valid email address")
             save = False
     if save:
         #Data are OK, Now check if there is an existing user or create a new one
         ah = user.AvatarHolder()
         res =  ah.match({"email": self._params["email"]}, exact=1, forceWithoutExtAuth=True)
         if res:
             #we find a user with the same email
             a = res[0]
             #check if the user have an identity:
             if a.getIdentityList():
                 self._redirect( urlHandlers.UHUserExistWithIdentity.getURL(a))
                 return
             else:
                 #create the identity to the user and send the comfirmatio email
                 _UserUtils.setUserData( a, self._params )
                 li = user.LoginInfo( self._params["login"], self._params["password"] )
                 id = ih.createIdentity( li, a, "Local" )
                 ih.add( id )
                 DBMgr.getInstance().commit()
                 if minfo.getModerateAccountCreation():
                     mail.sendAccountCreationModeration(a).send()
                 else:
                     mail.sendConfirmationRequest(a).send()
                     if minfo.getNotifyAccountCreation():
                         mail.sendAccountCreationNotification(a).send()
         else:
             a = user.Avatar()
             _UserUtils.setUserData( a, self._params )
             ah.add(a)
             li = user.LoginInfo( self._params["login"], self._params["password"] )
             id = ih.createIdentity( li, a, "Local" )
             ih.add( id )
             DBMgr.getInstance().commit()
             if minfo.getModerateAccountCreation():
                 mail.sendAccountCreationModeration(a).send()
             else:
                 mail.sendConfirmationRequest(a).send()
                 if minfo.getNotifyAccountCreation():
                     mail.sendAccountCreationNotification(a).send()
         self._redirect(urlHandlers.UHUserCreated.getURL( a ))
     else:
         cp=None
         if self._params.has_key("cpEmail"):
             ph=pendingQueues.PendingQueuesHolder()
             cp=ph.getFirstPending(self._params["cpEmail"])
         if self._aw.getUser() and self._aw.getUser() in minfo.getAdminList().getList():
             p = adminPages.WPUserCreation( self, self._params, cp )
         else:
             p = adminPages.WPUserCreationNonAdmin( self, self._params, cp )
         return p.display()
Beispiel #21
0
def _import(self, file):
    # check Registration period
    import datetime
    import pytz
    utc = pytz.UTC
    startDate = self._conf.getRegistrationForm().getStartRegistrationDate()
    endDate = self._conf.getRegistrationForm().getEndRegistrationDate()
    current = datetime.datetime.now()
    current = utc.localize(current)

    if (current < startDate or current > endDate):
        raise NoReportError("Import registrants not authorized, outside registration period.")

    reader = csv.DictReader(file)
    i = 1
    errors = []

    successfuls = []
    unsuccessfuls = []

    for row in reader:
        try:
            # row['Email'] = row['Email'].lower()
            self._processImportData(row)
            matchedUsers = AvatarHolder().match({"email": row['Email']}, exact=1)
            if matchedUsers:
                user = matchedUsers[0]
            elif ('Account Creation' in row) and row['Account Creation'].lower() == 'yes':  # account creation
                avData = self._mapAvatar(row)
                user = Avatar(avData)
                user.activateAccount()
                login_info = LoginInfo(row['Login'], row['Password'])
                auth_mgr = AuthenticatorMgr()
                user_id = auth_mgr.createIdentity(login_info, user, "Local")
                auth_mgr.add(user_id)
                AvatarHolder().add(user)
            else:
                user = None

            if not (user):
                reg = Registrant()  # new registration
                self._conf.addRegistrant(reg, user)
            else:
                if user.isRegisteredInConf(self._conf):
                    reg = self._conf.getRegistrantsByEmail(user.getEmail())
                else:  # not registered, new registration
                    reg = Registrant()
                    reg.setAvatar(user)
                    self._conf.addRegistrant(reg, user)
                    user.addRegistrant(reg)

            regData = self._mapRegistrant(row)
            regData['import'] = 'import'
            reg.setValues(regData, user)
            self._setAffiliation(reg)
            successfuls.append(reg.getFullName())
        except Exception:
            errors.append(i)
            unsuccessfuls.append(
                row["Surname"] + ", " + row["First Name"])  # exception : reg or user might not be defined yet
        finally:
            i += 1
    self.logimport(successfuls, unsuccessfuls)
    return errors