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( )
def _process( self ): am = AuthenticatorMgr() for id in self._identityList: identity = am.getIdentityById(id) am.removeIdentity(identity) self._avatar.removeIdentity(identity) self._redirect( urlHandlers.UHUserDetails.getURL( self._avatar ) )
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()
def _process(self): am = AuthenticatorMgr() for id in self._identityList: identity = am.getIdentityById(id) am.removeIdentity(identity) self._avatar.removeIdentity(identity) self._redirect(urlHandlers.UHUserDetails.getURL(self._avatar))
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
def _makeLoginProcess(self): # Check for automatic login authManager = AuthenticatorMgr() if ( authManager.isSSOLoginActive() and len(authManager.getList()) == 1 and not Config.getInstance().getDisplayLoginPage() ): self._redirect(urlHandlers.UHSignInSSO.getURL(authId=authManager.getDefaultAuthenticator().getId())) return if request.method != "POST": return self._signInPage.display(returnURL=self._returnURL) else: li = LoginInfo(self._login, self._password) av = authManager.getAvatar(li) if not av: return self._signInPageFailed.display(returnURL=self._returnURL) elif not av.isActivated(): if av.isDisabled(): self._redirect(self._disabledAccountURL(av)) else: self._redirect(self._unactivatedAccountURL(av)) return _("Your account is not active\nPlease activate it and try again") else: self._setSessionVars(av) self._addExtraParamsToURL() self._redirect(self._url)
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()
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)
def _process( self ): authManager = AuthenticatorMgr() for i in self._identityList: identity = authManager.getIdentityById(i) if len(identity.getUser().getIdentityList()) > 1: authManager.removeIdentity(identity) self._avatar.removeIdentity(identity) self._redirect( urlHandlers.UHUserDetails.getURL( self._avatar ) )
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))
def _processIfActive( self ): self._tohttps = True #Check for automatic login auth = AuthenticatorMgr() av = auth.autoLogin(self) if av: url = self._returnURL self._getSession().setUser( av ) self._redirect( url ) p = registrationForm.WPRegistrationFormSignIn(self, self._conf) return p.display()
def _processIfActive( self ): #Check for automatic login auth = AuthenticatorMgr() av = auth.autoLogin(self) if av: url = self._returnURL self._getSession().setUser( av ) if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect( url ) p = registrationForm.WPRegistrationFormSignIn(self, self._conf) return p.display()
def _processIfActive(self): #Check for automatic login auth = AuthenticatorMgr() av = auth.autoLogin(self) if av: url = self._returnURL self._getSession().setUser(av) if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect(url) p = registrationForm.WPRegistrationFormSignIn(self, self._conf) return p.display()
def _process( self ): autoLogoutRedirect = None if self._getUser(): auth = AuthenticatorMgr() autoLogoutRedirect = auth.autoLogout(self) self._getSession().removeVar("ActiveTimezone") self._getSession().setUser( None ) self._setUser( None ) if autoLogoutRedirect: self._redirect(autoLogoutRedirect) else: self._redirect(self._returnURL)
def _process(self): autoLogoutRedirect = None if self._getUser(): auth = AuthenticatorMgr() autoLogoutRedirect = auth.autoLogout(self) self._getSession().removeVar("ActiveTimezone") self._getSession().setUser(None) self._setUser(None) if autoLogoutRedirect: self._redirect(autoLogoutRedirect) else: self._redirect(self._returnURL)
def _getAnswer(self): li = LoginInfo( self._username, self._password ) auth = AuthenticatorMgr() av = auth.getAvatar(li) if not av: from MaKaC.services.interface.rpc.common import ServiceError raise ServiceError(message="Wrong login or password") elif not av.isActivated(): from MaKaC.services.interface.rpc.common import ServiceError raise ServiceError(message="Your account is not active. Please activate it and retry.") else: self._getSession().setUser( av ) return '%s OK %s' % (self._username, datetime.datetime.now())
def _process(self): authManager = AuthenticatorMgr() if (authManager.isSSOLoginActive() and len(authManager.getList()) == 1 and not Config.getInstance().getDisplayLoginPage()): self._redirect(urlHandlers.UHSignInSSO.getURL(authId=authManager.getDefaultAuthenticator().getId())) return av = authManager.getAvatarByLogin(self._login).values()[0] self._responseUtil.content_type='application/json' if not av: return '{"success":false,"message":"User not found"}' elif not av.isActivated(): return '{"success":false,"message":"User not activated"}' else: return '{"success":true}'
def _getAnswer(self): li = LoginInfo(self._username, self._password) auth = AuthenticatorMgr() av = auth.getAvatar(li) if not av: from MaKaC.services.interface.rpc.common import ServiceError raise ServiceError("Wrong login or password") elif not av.isActivated(): from MaKaC.services.interface.rpc.common import ServiceError raise ServiceError( "Your account is not active. Please activate it and retry.") else: self._getSession().setUser(av) return '%s OK %s' % (self._username, datetime.datetime.now())
def _process(self): self._disableCaching() #Check for automatic login auth = AuthenticatorMgr() av = auth.autoLogin(self) if av: url = self._returnURL tzUtil = timezoneUtils.SessionTZ(av) tz = tzUtil.getSessionTZ() self._getSession().setVar("ActiveTimezone", tz) self._getSession().setUser(av) if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect(url, noCache=True) if not self._signIn: p = signIn.WPSignIn(self) return p.display(returnURL=self._returnURL) else: li = LoginInfo(self._login, self._password) av = auth.getAvatar(li) if not av: p = signIn.WPSignIn(self, login=self._login, msg=_("Wrong login or password")) return p.display(returnURL=self._returnURL) elif not av.isActivated(): if av.isDisabled(): self._redirect(urlHandlers.UHDisabledAccount.getURL(av)) else: self._redirect(urlHandlers.UHUnactivatedAccount.getURL(av)) return _( "your account is not activate\nPlease active it and retry") else: url = self._returnURL #raise(str(dir(av))) self._getSession().setUser(av) tzUtil = timezoneUtils.SessionTZ(av) tz = tzUtil.getSessionTZ() self._getSession().setVar("ActiveTimezone", tz) if self._userId != "": if "?" in url: url += "&userId=%s" % self._userId else: url += "?userId=%s" % self._userId if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect(url, noCache=True)
def create_dummy_users(dummyuser_has_password=False): """ Creates a dummy user for testing purposes. If dummyuser_has_password is set, "dummyuser" and "fake-1" can be used for logging in. """ minfo = HelperMaKaCInfo.getMaKaCInfoInstance() ah = AvatarHolder() authManager = AuthenticatorMgr() avatars = [] al = minfo.getAdminList() avatar = create_user("fake", "dummyuser", authManager, dummyuser_has_password) ah.add(avatar) avatars.append(avatar) al.grant(avatar) for i in xrange(1, 5): avatar = create_user("fake-%d" % i, "fake-%d" % i, authManager, dummyuser_has_password and i == 1) avatar.setId("fake-%d" % i) ah.add(avatar) avatars.append(avatar) HelperMaKaCInfo.getMaKaCInfoInstance().setDefaultConference( DefaultConference()) return avatars
class RHResetPasswordBase: _isMobile = False _token_storage = GenericCache('resetpass') def _checkParams(self, params): self._token = request.view_args['token'] self._data = self._token_storage.get(self._token) if not self._data: raise NoReportError(_('Invalid token. It might have expired.')) self._avatar = AuthenticatorMgr().getById(self._data['tag']).getAvatarByLogin(self._data['login']) self._identity = self._avatar.getIdentityById(self._data['login'], self._data['tag']) if not self._identity: raise NoReportError(_('Invalid token (no login found)')) def _checkParams_POST(self): self._password = request.form['password'].strip() if not self._password: raise FormValuesError(_('Your password must not be empty.')) if self._password != request.form['password_confirm'].strip(): raise FormValuesError(_('Your password confirmation is not correct.')) def _process_GET(self): return self._getWP().display() def _process_POST(self): self._identity.setPassword(self._password.encode('utf-8')) self._token_storage.delete(self._token) url = self._getRedirectURL() url.addParam('passwordChanged', True) self._redirect(url)
def _getParams(self): super(BookRoomHook, self)._getParams() username = get_query_parameter(self._queryParams, ['username']) booked_for = AuthenticatorMgr().getAvatarByLogin(username).values() if not booked_for: raise HTTPAPIError('Username does not exist.') self._params = { 'roomid': get_query_parameter(self._queryParams, ['roomid']), 'location': get_query_parameter(self._queryParams, ['location']), 'username': username, 'reason': get_query_parameter(self._queryParams, ['reason']), 'userBookedFor': booked_for[0], 'from': self._fromDT, 'to': self._toDT } # calculate missing arguments missing = list(name for (name, value) in (self._params.iteritems()) if not value) if missing: raise HTTPAPIError('Argument(s) missing: {0}'.format(', '.join(missing)), apache.HTTP_BAD_REQUEST) self._room = CrossLocationQueries.getRooms(location=self._params['location'], roomID=int(self._params['roomid']))
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)
def authenticate(self, id): """ id is MaKaC.user.LoginInfo instance, self.user is Avatar """ log = Logger.get('auth.ldap') log.info("authenticate(%s)" % id.getLogin()) data = AuthenticatorMgr.getInstance().getById(self.getAuthenticatorTag()).checkLoginPassword(id.getLogin(), id.getPassword()) if not data or self.getLogin() != id.getLogin(): return None # modify Avatar with the up-to-date info from LDAP av = self.user av.clearAuthenticatorPersonalData() udata = LDAPTools.extractUserDataFromLdapData(data) mail = udata.get('email', '').strip() if mail != '' and mail != av.getEmail(): av.setEmail(mail, reindex=True) av.setAuthenticatorPersonalData('firstName', udata.get('name')) av.setAuthenticatorPersonalData('surName', udata.get('surName')) av.setAuthenticatorPersonalData('affiliation', udata.get('organisation')) av.setAuthenticatorPersonalData('address', udata.get('address')) av.setAuthenticatorPersonalData('phone', udata.get('phone')) av.setAuthenticatorPersonalData('fax', udata.get('fax')) return self.user
def _process(self): """Script triggered by the display of the centralized SSO logout dialog. It logouts the user from CDS Invenio and stream back the expected picture.""" if self._getUser(): auth = AuthenticatorMgr() autoLogoutRedirect = auth.autoLogout(self) self._getSession().removeVar("ActiveTimezone") self._getSession().setUser( None ) self._setUser( None ) self._req.content_type = 'image/gif' self._req.encoding = None self._req.filename = 'wsignout.gif' self._req.headers_out["Content-Disposition"] = "inline; filename=wsignout.gif" self._req.set_content_length(os.path.getsize("%s/wsignout.gif"%Configuration.Config.getInstance().getImagesDir())) self._req.send_http_header() self._req.sendfile("%s/wsignout.gif"%Configuration.Config.getInstance().getImagesDir())
def _process(self): #Check for automatic login authManager = AuthenticatorMgr() if (authManager.isSSOLoginActive() and len(authManager.getList()) == 1 and not Config.getInstance().getDisplayLoginPage()): self._redirect(urlHandlers.UHSignInSSO.getURL(authId=authManager.getDefaultAuthenticator().getId())) return li = LoginInfo( self._login, self._password ) av = authManager.getAvatar(li) self._responseUtil.content_type='application/json' if not av: return '{"success":false,"message":"User not authenticated or found"}' elif not av.isActivated(): return '{"success":false,"message":"User not activated"}' else: return '{"success":true}'
def _process( self ): self._disableCaching() #Check for automatic login auth = AuthenticatorMgr() av = auth.autoLogin(self) if av: url = self._returnURL tzUtil = timezoneUtils.SessionTZ(av) tz = tzUtil.getSessionTZ() self._getSession().setVar("ActiveTimezone",tz) self._getSession().setUser( av ) if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect( url, noCache = True ) if not self._signIn: p = signIn.WPSignIn( self ) return p.display( returnURL = self._returnURL ) else: li = LoginInfo( self._login, self._password ) av = auth.getAvatar(li) if not av: p = signIn.WPSignIn( self, login = self._login, msg = _("Wrong login or password") ) return p.display( returnURL = self._returnURL ) elif not av.isActivated(): if av.isDisabled(): self._redirect(urlHandlers.UHDisabledAccount.getURL(av)) else: self._redirect(urlHandlers.UHUnactivatedAccount.getURL(av)) return _("your account is not activate\nPlease active it and retry") else: url = self._returnURL #raise(str(dir(av))) self._getSession().setUser( av ) tzUtil = timezoneUtils.SessionTZ(av) tz = tzUtil.getSessionTZ() self._getSession().setVar("ActiveTimezone",tz) if self._userId != "": if "?" in url: url += "&userId=%s"%self._userId else: url += "?userId=%s"%self._userId if Config.getInstance().getBaseSecureURL().startswith('https://'): url = str(url).replace('http://', 'https://') self._redirect( url, noCache = True )
def _checkParams(self, params): self._token = request.view_args['token'] self._data = self._token_storage.get(self._token) if not self._data: raise NoReportError(_('Invalid token. It might have expired.')) self._avatar = AuthenticatorMgr().getById(self._data['tag']).getAvatarByLogin(self._data['login']) self._identity = self._avatar.getIdentityById(self._data['login'], self._data['tag']) if not self._identity: raise NoReportError(_('Invalid token (no login found)'))
def _process(self): authenticator = session.pop('Authenticator', None) if authenticator is not None: authManager = AuthenticatorMgr() if not authManager.isSSOLoginActive(): raise MaKaCError(_("SSO Login is not active.")) av = authManager.SSOLogin(self, authenticator) if not av: raise MaKaCError(_("You could not login through SSO.")) self._setSessionVars(av) self._redirect(self._url) elif self._authId: session['Authenticator'] = self._authId if self._returnURL: session['loginReturnURL'] = self._returnURL self._redirect(str(urlHandlers.UHSignInSSO.getURL(authId=self._authId))) else: raise MaKaCError(_("You did not pass the authenticator"))
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
def getMemberList(self): uidList = AuthenticatorMgr.getInstance().getById('LDAP').getGroupMemberList(self.getName()) avatarLists = [] for uid in uidList: # First, try locally (fast) lst = PrincipalHolder().match(uid , exact=1, searchInAuthenticators=False) print "Result", lst if not lst: # If not found, try external lst = PrincipalHolder().match(uid, exact=1) avatarLists.append(lst) return [avList[0] for avList in avatarLists if avList]
def containsUser(self, avatar): # used when checking acces to private events restricted for certain groups if not avatar: return False login = None for aid in avatar.getIdentityList(): if aid.getAuthenticatorTag() == 'LDAP': login = aid.getLogin() if not login: return False return AuthenticatorMgr.getInstance().getById('LDAP').isUserInGroup((login, self.getName()))
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)))
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()
def _process(self): li = LoginInfo(self._login, self._password) av = AuthenticatorMgr().getAvatar(li) value = "OK" message = "" if not av: value = "ERROR" message = "Login failed" elif not av.isActivated(): if av.isDisabled(): value = "ERROR" message = "Acount is disabled" else: value = "ERROR" message = "Acount is not activated" else: value = "OK" message = "Login succesful" session.user = av return self._createResponse(value, message)
def _process( self ): li = LoginInfo( self._login, self._password ) av = AuthenticatorMgr().getAvatar(li) value = "OK" message = "" if not av: value = "ERROR" message = "Login failed" elif not av.isActivated(): if av.isDisabled(): value = "ERROR" message = "Acount is disabled" else: value = "ERROR" message = "Acount is not activated" else: value = "OK" message = "Login succesful" session.user = av return self._createResponse(value, message)
def createUser(name, email, org, password): #has problem that if no email exists and 2 users with same name will clash #perhaps change getUser() to check for same name if no email exist. #problem being that more than one person can have same name. Email unique. dummy = user.Avatar() #sets the user properties if name == '':#if there is no username makes the email address appear in it's place dummy.setName(email) else: dummy.setName(name) dummy.setEmail(email) dummy.setOrganisation(org) ah.add(dummy) avatar = ah.getById(dummy.id) if email != '':#creates the identity and sets the password for chairs etc. id = user.LocalIdentity(name, password, avatar) else:#user with no email address - identity not created return avatar try: AuthenticatorMgr.getInstance().add(id) except (UserError): pass avatar.activateAccount() return avatar
def _process(self): authManager = AuthenticatorMgr() if (authManager.isSSOLoginActive() and len(authManager.getList()) == 1 and not Config.getInstance().getDisplayLoginPage()): self._redirect( urlHandlers.UHSignInSSO.getURL( authId=authManager.getDefaultAuthenticator().getId())) return av = authManager.getAvatarByLogin(self._login).values()[0] self._responseUtil.content_type = 'application/json' if not av: return '{"success":false,"message":"User not found"}' elif not av.isActivated(): return '{"success":false,"message":"User not activated"}' else: return '{"success":true}'
def createUser(name, email, org, password): #has problem that if no email exists and 2 users with same name will clash #perhaps change getUser() to check for same name if no email exist. #problem being that more than one person can have same name. Email unique. dummy = user.Avatar() #sets the user properties if name == '':#if there is no username makes the email address appear in it's place dummy.setName(email) else: dummy.setName(name) dummy.setEmail(email) dummy.setOrganisation(org) ah.add(dummy) avatar = ah.getById(dummy.id) if email != '':#creates the identity and sets the password for chairs etc. id = user.LocalIdentity(name, password, avatar) else:#user with no email address - identity not created return avatar try: AuthenticatorMgr().add(id) except (UserError): pass avatar.activateAccount() return avatar
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
def _process(self): #Check for automatic login authManager = AuthenticatorMgr() if (authManager.isSSOLoginActive() and len(authManager.getList()) == 1 and not Config.getInstance().getDisplayLoginPage()): self._redirect( urlHandlers.UHSignInSSO.getURL( authId=authManager.getDefaultAuthenticator().getId())) return li = LoginInfo(self._login, self._password) av = authManager.getAvatar(li) self._responseUtil.content_type = 'application/json' if not av: return '{"success":false,"message":"User not authenticated or found"}' elif not av.isActivated(): return '{"success":false,"message":"User not activated"}' else: return '{"success":true}'
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 _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()
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 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)
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()
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()
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))
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]
from MaKaC.authentication import AuthenticatorMgr from MaKaC.authentication.LocalAuthentication import LocalIdentity print('This script will remove all local identities from users.') print('This will remove passwords from the database and prevent them from') print('logging in locally (so you need e.g. NICE or LDAP authentication)') print if raw_input('Do you want to continue? [yes|NO]: ').lower() != 'yes': print 'Cancelled.' sys.exit(0) i = 0 dbi = DBMgr.getInstance() dbi.startRequest() ah = AvatarHolder() am = AuthenticatorMgr() for aid, avatar in ah._getIdx().iteritems(): for identity in avatar.getIdentityList(): if isinstance(identity, LocalIdentity): print('Removing LocalIdentity(%s, %s) from %s' % (identity.getLogin(), len(identity.password) * '*', avatar.getFullName())) am.removeIdentity(identity) avatar.removeIdentity(identity) if i % 100 == 99: dbi.commit() i += 1 DBMgr.getInstance().endRequest()