def _indexingRequest(self, request): """ Return a new request that can be used for index building. This request uses a security policy that lets the current user read any page. Without this policy some pages will not render, which will create broken pagelinks index. @param request: current request """ from MoinMoin.security import Permissions from MoinMoin.user import User class SecurityPolicy(Permissions): def read(self, *args, **kw): return True user = User(request) user.may = SecurityPolicy(user) class FakeRequest(object): """ minimal request object for indexing code """ def __init__(self, request, user): NAMES = """action cfg clock current_lang dicts form getPragma getText href html_formatter isSpiderAgent mode_getpagelinks page parsePageLinks_running redirect redirectedOutput rev rootpage script_root session setContentLanguage setPragma theme uid_generator values write""".split() for name in NAMES: value = getattr(request, name, None) setattr(self, name, value) self.user = user return FakeRequest(request, user)
def test_filter_subscriber_list(request): user = User(request) event = events.Event(request) print "User is subscribed to this event on jabber." print "This means, that he should stay on the list." user.jid = "*****@*****.**" user.jabber_subscribed_events = [events.Event.__name__] subscribers = {"en": [user]} notification.filter_subscriber_list(event, subscribers, True) assert subscribers["en"] print "User is not subscribed to this event on jabber." print "The list should be empty." user.jid = "*****@*****.**" user.jabber_subscribed_events = [] subscribers = {"en": [user]} notification.filter_subscriber_list(event, subscribers, True) assert not subscribers["en"] print "User is subscribed to this event on email." print "This means, that he should stay on the list." user.email = "*****@*****.**" user.email_subscribed_events = [events.Event.__name__] subscribers = {"en": [user]} notification.filter_subscriber_list(event, subscribers, False) assert subscribers["en"] print "User is not subscribed to this event on email." print "The list should be empty." user.email = "*****@*****.**" user.email_subscribed_events = [] subscribers = {"en": [user]} notification.filter_subscriber_list(event, subscribers, False) assert not subscribers["en"]
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.mainitem_name, u'AnyUser', ['read']), # by after acl (self.mainitem_name, u'JaneDoe', ['read', 'write']), # by item acl (self.mainitem_name, u'JoeDoe', []), # by item acl (self.subitem1_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem1_name, u'AnyUser', ['read']), # by after acl (self.subitem1_name, u'JoeDoe', []), # by inherited acl from main item (self.subitem1_name, u'JaneDoe', ['read', 'write']), # by inherited acl from main item (self.subitem2_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem2_name, u'AnyUser', ['read']), # by after acl (self.subitem2_name, u'JoeDoe', ['read']), # by after acl (self.subitem2_name, u'JaneDoe', ['read']), # by after acl (self.subitem_4boss, u'AnyUser', ['read']), # by after acl (self.subitem_4boss, u'JoeDoe', ['read', 'write']), # by item acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True # User should have these rights... for right in may: can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (hierarchic)".format(u.name, right, itemname)
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.mainitem_name, u"AnyUser", ["read"]), # by after acl (self.mainitem_name, u"JaneDoe", ["read", "write"]), # by item acl (self.mainitem_name, u"JoeDoe", []), # by item acl (self.subitem1_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.subitem1_name, u"AnyUser", ["read"]), # by after acl (self.subitem1_name, u"JoeDoe", []), # by inherited acl from main item (self.subitem1_name, u"JaneDoe", ["read", "write"]), # by inherited acl from main item (self.subitem2_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.subitem2_name, u"AnyUser", ["read"]), # by after acl (self.subitem2_name, u"JoeDoe", ["read"]), # by after acl (self.subitem2_name, u"JaneDoe", ["read"]), # by after acl (self.subitem_4boss, u"AnyUser", ["read"]), # by after acl (self.subitem_4boss, u"JoeDoe", ["read", "write"]), # by item acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True # User should have these rights... for right in may: can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (hierarchic)".format(u.name, right, itemname)
def testPageACLs(self): """ security: test page acls """ tests = [ # hierarchic, pagename, username, expected_rights (False, self.mainpage_name, u'WikiAdmin', ['read', 'write', 'admin', 'revert', 'delete']), (True, self.mainpage_name, u'WikiAdmin', ['read', 'write', 'admin', 'revert', 'delete']), (False, self.mainpage_name, u'AnyUser', ['read']), # by after acl (True, self.mainpage_name, u'AnyUser', ['read']), # by after acl (False, self.mainpage_name, u'JaneDoe', ['read', 'write']), # by page acl (True, self.mainpage_name, u'JaneDoe', ['read', 'write']), # by page acl (False, self.mainpage_name, u'JoeDoe', []), # by page acl (True, self.mainpage_name, u'JoeDoe', []), # by page acl (False, self.subpage_name, u'WikiAdmin', ['read', 'write', 'admin', 'revert', 'delete']), (True, self.subpage_name, u'WikiAdmin', ['read', 'write', 'admin', 'revert', 'delete']), (False, self.subpage_name, u'AnyUser', ['read', 'write']), # by default acl (True, self.subpage_name, u'AnyUser', ['read']), # by after acl (False, self.subpage_name, u'JoeDoe', ['read', 'write']), # by default acl (True, self.subpage_name, u'JoeDoe', []), # by inherited acl from main page (False, self.subpage_name, u'JaneDoe', ['read', 'write']), # by default acl (True, self.subpage_name, u'JaneDoe', ['read', 'write']), # by inherited acl from main page (True, self.subitem_4boss, u'AnyUser', ['read']), # by after acl (True, self.subitem_4boss, u'JoeDoe', ['read', 'write']), # by item acl ] for hierarchic, pagename, username, may in tests: u = User(self.request, auth_username=username) u.valid = True def _have_right(u, right, pagename, hierarchic): self.request.cfg.acl_hierarchic = hierarchic can_access = u.may.__getattr__(right)(pagename) if can_access: print "page %s: %s test if %s may %s (success)" % ( pagename, ['normal', 'hierarchic'][hierarchic], username, right) else: print "page %s: %s test if %s may %s (failure)" % ( pagename, ['normal', 'hierarchic'][hierarchic], username, right) assert can_access # User should have these rights... for right in may: yield _have_right, u, right, pagename, hierarchic def _not_have_right(u, right, pagename, hierarchic): self.request.cfg.acl_hierarchic = hierarchic can_access = u.may.__getattr__(right)(pagename) if can_access: print "page %s: %s test if %s may not %s (failure)" % ( pagename, ['normal', 'hierarchic'][hierarchic], username, right) else: print "page %s: %s test if %s may not %s (success)" % ( pagename, ['normal', 'hierarchic'][hierarchic], username, right) assert not can_access # User should NOT have these rights: mayNot = [right for right in self.request.cfg.acl_rights_valid if right not in may] for right in mayNot: yield _not_have_right, u, right, pagename, hierarchic
def request(self, request, user_obj, **kw): """ authenticate via external cookie """ import Cookie user = None try_next = True # if True, moin tries the next auth method cookiename = "whatever" # +++ external cookie name you want to use try: cookie = Cookie.SimpleCookie(request.saved_cookie) except Cookie.CookieError: # ignore invalid cookies cookie = None if cookie and cookiename in cookie: import urllib cookievalue = cookie[cookiename].value # +++ now we decode and parse the cookie value - edit this to fit your needs. # the minimum we need to get is auth_username. aliasname and email is optional. cookievalue = urllib.unquote(cookievalue) # cookie value is urlencoded, decode it cookievalue = cookievalue.decode("iso-8859-1") # decode cookie charset to unicode cookievalue = cookievalue.split("#") # cookie has format loginname#firstname#lastname#email auth_username = cookievalue[0] # having this cookie means user auth has already been done! aliasname = email = "" try: aliasname = "%s %s" % (cookievalue[1], cookievalue[2]) # aliasname is for cosmetical stuff only email = cookievalue[3] except IndexError: # +++ this is for debugging it, in case it does not work if 0: f = open("cookie.log", "w") f.write(repr(cookie)) f.write(repr(cookievalue)) f.close() pass from MoinMoin.user import User # giving auth_username to User constructor means that authentication has already been done. user = User(request, name=auth_username, auth_username=auth_username, auth_method=self.name) changed = False if aliasname != user.aliasname: # was the aliasname externally updated? user.aliasname = aliasname changed = True # yes -> update user profile if email != user.email: # was the email addr externally updated? user.email = email changed = True # yes -> update user profile if user: user.create_or_update(changed) if user and user.valid: # did we succeed making up a valid user? try_next = False # stop processing auth method list return user, try_next
def request(self, request, user_obj, **kw): user = request.env.get('repoze.who.identity', {}).get('user', None) if user: user = User( request, auth_username=user.uid, auth_method=self.name, auth_attribs=('name', 'aliasname', 'email', 'password')) #user.may = PlonePermissions(user) user.language = 'es' user.valid = 1 return user, True return user_obj, True
def __call__(self, request, **kw): def handle_egroupware(session): """ Extracts name, fullname and email from the session. """ username = session['egw_session']['session_lid'].split("@", 1)[0] known_accounts = session['egw_info_cache']['accounts']['cache']['account_data'] # if the next line breaks, then the cache was not filled with the current # user information user_info = [value for key, value in known_accounts.items() if value['account_lid'] == username][0] name = user_info.get('fullname', '') email = user_info.get('email', '') dec = lambda x: x and x.decode("iso-8859-1") return dec(username), dec(email), dec(name) import Cookie, urllib from MoinMoin.user import User from MoinMoin.util import sessionParser user_obj = kw.get('user_obj') try: cookie = Cookie.SimpleCookie(request.saved_cookie) except Cookie.CookieError: # ignore invalid cookies cookie = None if cookie: for cookiename in cookie.keys(): cookievalue = urllib.unquote(cookie[cookiename].value).decode('iso-8859-1') session = sessionParser.loadSession(cookievalue, path=self.s_path, prefix=self.s_prefix) if session: if "egw" in self.apps and session.get('egw_session', None): username, email, name = handle_egroupware(session) break else: return user_obj, True user = User(request, name=username, auth_username=username) changed = False if name != user.aliasname: user.aliasname = name changed = True if email != user.email: user.email = email changed = True if user: user.create_or_update(changed) if user and user.valid: return user, True # True to get other methods called, too return user_obj, True # continue with next method in auth list
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.mainitem_name, u'AnyUser', ['read']), # by after acl (self.mainitem_name, u'JaneDoe', ['read', 'write']), # by item acl (self.mainitem_name, u'JoeDoe', []), # by item acl (self.subitem1_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem1_name, u'AnyUser', ['read', 'write']), # by default acl (self.subitem1_name, u'JoeDoe', ['read', 'write']), # by default acl (self.subitem1_name, u'JaneDoe', ['read', 'write']), # by default acl (self.subitem2_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem2_name, u'AnyUser', ['read']), # by after acl (self.subitem2_name, u'JoeDoe', ['read']), # by after acl (self.subitem2_name, u'JaneDoe', ['read']), # by after acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True def _have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (normal)".format(u.name, right, itemname) # User should have these rights... for right in may: yield _have_right, u, right, itemname def _not_have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (normal)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: yield _not_have_right, u, right, itemname # check function rights u = User(auth_username='******') assert u.may.superuser() u = User(auth_username='******') assert u.may.notextcha() u = User(auth_username='******') assert not u.may.superuser() assert not u.may.notextcha()
def view(self, offset, length, sessionId): page_info = self.ngowikiutil.select_page_by_id(self.pageid) comment_list = self.ngowikiutil.select_comments_by_page(self.page, offset, length) if comment_list == None: comment_list = [] for comment in comment_list: user = User(self.request, id=comment["user_id"]) comment["user_name"] = user.name comment["comment"] = comment["comment"].replace("\n", "<br>") if self.user == None or not self.user.valid or (not self.user.isSuperUser() and self.user.id != comment["user_id"]): continue comment["_delete_"] = True isSuperUser = False if self.user != None and self.user.valid and self.user.isSuperUser(): isSuperUser = True has_user_liked_page = False if self.user != None and self.user.valid: has_user_liked_page = self.ngowikiutil.has_user_liked_page(self.user.id, self.page) else: has_user_liked_page = self.ngowikiutil.has_user_liked_page('anonymous-' + sessionId, self.page) has_user_favorite_page = False if self.user != None and self.user.valid: has_user_favorite_page = self.ngowikiutil.has_user_favorite_page(self.user.id, self.page) else: has_user_favorite_page = False return {"commentcount": page_info["commentcount"], "likecount": page_info["likecount"], "hasUserLikedPage": has_user_liked_page, "hasUserFavoritedPage": has_user_favorite_page, "comments": {"offset": offset, "length": length, "items": comment_list}, "isSuperUser": isSuperUser, "superrecommend": page_info["superrecommend"]}
def parse(story): """ The main workhorse that does nothing but call MoinMoin to do its dirty laundry @param story: A text for conversion @type story: string @returns: formatted string @rtype: string """ s = StringIO() oldstdout = sys.stdout form = None page = Page(None) page.hilite_re = None request = Request() request.user = User() formatter = Formatter(request) formatter.setPage(page) sys.stdout = s Parser(story, request).format(formatter, form) sys.stdout = oldstdout result = s.getvalue() s.close() return result
def setup_class(self): # Backup user self.savedUser = self.request.user.name self.request.user = User(self.request, auth_username=u'WikiAdmin') self.request.user.valid = True for page_name, page_content in self.pages: create_page(self.request, page_name, page_content)
def check_users(request, accounts): _ = request.getText if not accounts: raise GroupException(_('No accounts specified.')) for uname in accounts: if not User(request, name=uname).exists(): raise GroupException(_('User not valid: ') + uname)
def handle_user_created(event): """Handles an event sent when a new user is being created""" request = event.request sitename = request.cfg.sitename event_name = event.name email = event.user.email or u"NOT SET" username = event.user.name user_ids = getUserList(request) for id in user_ids: usr = User(request, id=id) # Currently send this only to super users if usr.isSuperUser() and usr.jid and event_name in usr.jabber_subscribed_events: _ = lambda text: request.getText(text, lang=usr.language or "en") msg = notification.user_created_message(request, _, sitename, username, email) data = {"action": "user_created", "subject": msg["subject"], "text": msg["text"], "url_list": []} send_notification(request, [usr.jid], data)
def setup_class(self): request = self.request user_name = 'TestUser' self.user_name = user_name become_superuser(request) User(request, name=user_name, password=user_name).save()
def mainloop(self): argc = len(self.args) self.init_request() request = self.request if self.options.py_append_file: def logs(request): """ generator for log objects """ # global edit-log yield editlog.EditLog(request) # local edit-log of every page for pn in request.rootpage.getPageList(exists=False): yield editlog.EditLog(request, rootpagename=pn) def uids(log): """ generator for userids found in a log """ for line in log: uid = line.userid if uid: yield uid fn = self.options.py_append_file editlog_uids = set() for log in logs(request): editlog_uids |= set(uids(log)) with open(fn, "a") as f: for uid in editlog_uids: u = User(request, uid) code = u'editlog_uids.add(%r) # %r %r %r\n' % ( uid, u.name, u.email, u.jid) f.write(code.encode('utf-8')) elif self.options.py_exec_file: def check_interactive(u): if self.options.interactive: prompt = "%s %r %r %r disabled=%r (y/N)? " % (u.id, u.name, u.email, u.jid, u.disabled) return raw_input(prompt).strip() in ['y', 'Y', ] else: return True fn = self.options.py_exec_file locs = dict(editlog_uids=set()) execfile(fn, {}, locs) editlog_uids = locs.get('editlog_uids') profile_uids = set(getUserList(request)) inactive_uids = profile_uids - editlog_uids for uid in inactive_uids: u = User(request, uid) if self.options.show: print "%s\t%r\t%r\t%r" % (uid, u.name, u.email, u.disabled) if self.options.disable: if check_interactive(u): u.disabled = 1 u.save() elif self.options.remove: if check_interactive(u): u.remove()
def handle_user_created(event): """Sends an email to super users that have subscribed to this event type""" request = event.request sitename = request.cfg.sitename from_address = request.cfg.mail_from event_name = event.name email = event.user.email or u"NOT SET" username = event.user.name user_ids = getUserList(request) for usr_id in user_ids: usr = User(request, id=usr_id) # Currently send this only to super users if usr.isSuperUser() and event_name in usr.email_subscribed_events: _ = lambda text: request.getText(text, lang=usr.language or 'en') data = notification.user_created_message(request, _, sitename, username, email) send_notification(request, from_address, [usr.email], data)
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.p1, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.p2, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c1, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c2, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c12, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.p1, u'Editor', []), # by p1 acl (self.c1, u'Editor', []), # by p1 acl (self.p1, u'SomeOne', ['read']), # by after acl (self.c1, u'SomeOne', ['read']), # by after acl (self.p2, u'Editor', ['read', 'write']), # by default acl (self.c2, u'Editor', ['read', 'write']), # by default acl (self.p2, u'SomeOne', ['read']), # by after acl (self.c2, u'SomeOne', ['read']), # by after acl (self.c12, u'SomeOne', ['read']), # by after acl # now check the rather special stuff: (self.c12, u'Editor', ['read', 'write']), # disallowed via p1, but allowed via p2 via default acl ] for itemnames, username, may in tests: u = User(auth_username=username) u.valid = True itemname = itemnames[0] def _have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should have these rights... for right in may: yield _have_right, u, right, itemname def _not_have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: yield _not_have_right, u, right, itemname
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.mainitem_name, u'AnyUser', ['read']), # by after acl (self.mainitem_name, u'JaneDoe', ['read', 'write']), # by item acl (self.mainitem_name, u'JoeDoe', []), # by item acl (self.subitem1_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem1_name, u'AnyUser', ['read']), # by after acl (self.subitem1_name, u'JoeDoe', []), # by inherited acl from main item (self.subitem1_name, u'JaneDoe', ['read', 'write']), # by inherited acl from main item (self.subitem2_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem2_name, u'AnyUser', ['read']), # by after acl (self.subitem2_name, u'JoeDoe', ['read']), # by after acl (self.subitem2_name, u'JaneDoe', ['read']), # by after acl (self.subitem_4boss, u'AnyUser', ['read']), # by after acl (self.subitem_4boss, u'JoeDoe', ['read', 'write']), # by item acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True def _have_right(u, right, itemname): flaskg.user = u can_access = getattr(u.may, right)(itemname) assert can_access, "%r may %s %r (hierarchic)" % (u.name, right, itemname) # User should have these rights... for right in may: yield _have_right, u, right, itemname def _not_have_right(u, right, itemname): flaskg.user = u can_access = getattr(u.may, right)(itemname) assert not can_access, "%r may not %s %r (hierarchic)" % (u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_valid if right not in may] for right in mayNot: yield _not_have_right, u, right, itemname
def run(): usage = "usage: %prog [options] <path to wiki> <pagename>" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Report success") parser.add_option("-a", "--auth", action="store_true", dest="auth", help="Use local user-based wiki authentication") parser.add_option("-c", "--comment", dest="comment", help="Optional change comment for the edit") (options, args) = parser.parse_args() if len(args) != 2: print parser.get_usage() sys.exit(2) # Configdir to path, so wikiconfig can be imported by Request cp = args[0] cp2 = os.path.join(cp, 'config') if os.path.isdir(cp2): cp = cp2 sys.path.insert(0, cp) pagename = unicode(args[1], sys.getfilesystemencoding()) # Make a new request for the page req = MinimalMoinScript(pagename, parse=False) req.page = Page(req, pagename) # Auth if options.auth: import posix, pwd # We need to import contexts before importing users, because otherwise # the relative imports in MoinMoin will fail. import MoinMoin.web.contexts from MoinMoin.user import User req.user = User(req, auth_username=pwd.getpwuid(posix.getuid())[0]) mytext = unicode(sys.stdin.read(), sys.getfilesystemencoding()) if options.comment: savetext(req, pagename, mytext, comment=unicode(options.comment)) else: savetext(req, pagename, mytext) # Must finish the request to ensure that metadata is saved graphdata_close(req)
def test_ItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.mainitem_name, u"AnyUser", ["read"]), # by after acl (self.mainitem_name, u"JaneDoe", ["read", "write"]), # by item acl (self.mainitem_name, u"JoeDoe", []), # by item acl (self.subitem1_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.subitem1_name, u"AnyUser", ["read", "write"]), # by default acl (self.subitem1_name, u"JoeDoe", ["read", "write"]), # by default acl (self.subitem1_name, u"JaneDoe", ["read", "write"]), # by default acl (self.subitem2_name, u"WikiAdmin", ["read", "write", "admin", "create", "destroy"]), (self.subitem2_name, u"AnyUser", ["read"]), # by after acl (self.subitem2_name, u"JoeDoe", ["read"]), # by after acl (self.subitem2_name, u"JaneDoe", ["read"]), # by after acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True # User should have these rights... for right in may: can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (normal)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (normal)".format(u.name, right, itemname) # check function rights u = User(auth_username="******") assert u.may.superuser() u = User(auth_username="******") assert u.may.notextcha() u = User(auth_username="******") assert not u.may.superuser() assert not u.may.notextcha()
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.mainitem_name, u'AnyUser', ['read']), # by after acl (self.mainitem_name, u'JaneDoe', ['read', 'write']), # by item acl (self.mainitem_name, u'JoeDoe', []), # by item acl (self.subitem1_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem1_name, u'AnyUser', ['read']), # by after acl (self.subitem1_name, u'JoeDoe', []), # by inherited acl from main item (self.subitem1_name, u'JaneDoe', ['read', 'write']), # by inherited acl from main item (self.subitem2_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem2_name, u'AnyUser', ['read']), # by after acl (self.subitem2_name, u'JoeDoe', ['read']), # by after acl (self.subitem2_name, u'JaneDoe', ['read']), # by after acl (self.subitem_4boss, u'AnyUser', ['read']), # by after acl (self.subitem_4boss, u'JoeDoe', ['read', 'write']), # by item acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True def _have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should have these rights... for right in may: yield _have_right, u, right, itemname def _not_have_right(u, right, itemname): can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: yield _not_have_right, u, right, itemname
def request(self, request, user_obj, **kw): """ authenticate via external cookie """ import Cookie user = None try_next = True # if True, moin tries the next auth method cookiename = "whatever" # +++ external cookie name you want to use try: cookie = Cookie.SimpleCookie(request.saved_cookie) except Cookie.CookieError: # ignore invalid cookies cookie = None if cookie and cookiename in cookie: import urllib cookievalue = cookie[cookiename].value # +++ now we decode and parse the cookie value - edit this to fit your needs. # the minimum we need to get is auth_username. aliasname and email is optional. cookievalue = urllib.unquote( cookievalue) # cookie value is urlencoded, decode it cookievalue = cookievalue.decode( 'iso-8859-1') # decode cookie charset to unicode cookievalue = cookievalue.split( '#') # cookie has format loginname#firstname#lastname#email auth_username = cookievalue[ 0] # having this cookie means user auth has already been done! aliasname = email = '' try: aliasname = "%s %s" % ( cookievalue[1], cookievalue[2] ) # aliasname is for cosmetical stuff only email = cookievalue[3] except IndexError: # +++ this is for debugging it, in case it does not work if 0: f = open("cookie.log", "w") f.write(repr(cookie)) f.write(repr(cookievalue)) f.close() pass from MoinMoin.user import User # giving auth_username to User constructor means that authentication has already been done. user = User(request, name=auth_username, auth_username=auth_username, auth_method=self.name) changed = False if aliasname != user.aliasname: # was the aliasname externally updated? user.aliasname = aliasname changed = True # yes -> update user profile if email != user.email: # was the email addr externally updated? user.email = email changed = True # yes -> update user profile if user: user.create_or_update(changed) if user and user.valid: # did we succeed making up a valid user? try_next = False # stop processing auth method list return user, try_next
def test_user_addition_to_group_page(self): """ Test addition of a username to a large list of group members. """ request = self.request become_trusted(request) # long list of users page_content = [u" * %s" % member for member in create_random_string_list()] create_page(request, u'UserGroup', "\n".join(page_content)) new_user = create_random_string_list(length=15, count=1)[0] append_page(request, u'UserGroup', u' * %s' % new_user) user = User(request, name=new_user) if not user.exists(): User(request, name=new_user, password=new_user).save() result = new_user in request.groups[u'UserGroup'] nuke_page(request, u'UserGroup') nuke_user(request, new_user) assert result
def testUserAppendingGroupPage(self): """ tests appending a username to a large list of group members and user creation """ # long list of users page_content = [u" * %s" % member for member in create_random_string_list()] request = self.request become_trusted(request) test_user = create_random_string_list(length=15, count=1)[0] page = create_page(request, u'UserGroup', "\n".join(page_content)) page = append_page(request, u'UserGroup', u' * %s' % test_user) # now shortly later we create a user object user = User(request, name=test_user) if not user.exists(): User(request, name=test_user, password=test_user).save() result = request.dicts.has_member('UserGroup', test_user) nuke_page(request, u'UserGroup') nuke_user(request, test_user) assert result is True
def testItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.p1, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.p2, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c1, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c2, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.c12, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), # by before acl (self.p1, u'Editor', []), # by p1 acl (self.c1, u'Editor', []), # by p1 acl (self.p1, u'SomeOne', ['read']), # by after acl (self.c1, u'SomeOne', ['read']), # by after acl (self.p2, u'Editor', ['read', 'write']), # by default acl (self.c2, u'Editor', ['read', 'write']), # by default acl (self.p2, u'SomeOne', ['read']), # by after acl (self.c2, u'SomeOne', ['read']), # by after acl (self.c12, u'SomeOne', ['read']), # by after acl # now check the rather special stuff: (self.c12, u'Editor', ['read', 'write']), # disallowed via p1, but allowed via p2 via default acl ] for itemnames, username, may in tests: u = User(auth_username=username) u.valid = True itemname = itemnames[0] # User should have these rights... for right in may: can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (hierarchic)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (hierarchic)".format(u.name, right, itemname)
def test_user_addition_to_group_page(self): """ Test addition of a username to a large list of group members. """ request = self.request become_trusted(request) # long list of users page_content = [ u" * %s" % member for member in create_random_string_list() ] create_page(request, u'UserGroup', "\n".join(page_content)) new_user = create_random_string_list(length=15, count=1)[0] append_page(request, u'UserGroup', u' * %s' % new_user) user = User(request, name=new_user) if not user.exists(): User(request, name=new_user, password=new_user).save() result = new_user in request.groups[u'UserGroup'] nuke_page(request, u'UserGroup') nuke_user(request, new_user) assert result
def handle_user_created(event): """Handles an event sent when a new user is being created""" request = event.request sitename = request.cfg.sitename event_name = event.name email = event.user.email or u"NOT SET" username = event.user.name user_ids = getUserList(request) for id in user_ids: usr = User(request, id=id) # Currently send this only to super users if usr.isSuperUser( ) and usr.jid and event_name in usr.jabber_subscribed_events: _ = lambda text: request.getText(text, lang=usr.language or 'en') msg = notification.user_created_message(request, _, sitename, username, email) data = { 'action': "user_created", 'subject': msg['subject'], 'text': msg['text'], 'url_list': [] } send_notification(request, [usr.jid], data)
def test_ItemACLs(self): """ security: test item acls """ tests = [ # itemname, username, expected_rights (self.mainitem_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.mainitem_name, u'AnyUser', ['read']), # by after acl (self.mainitem_name, u'JaneDoe', ['read', 'write']), # by item acl (self.mainitem_name, u'JoeDoe', []), # by item acl (self.subitem1_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem1_name, u'AnyUser', ['read', 'write']), # by default acl (self.subitem1_name, u'JoeDoe', ['read', 'write']), # by default acl (self.subitem1_name, u'JaneDoe', ['read', 'write']), # by default acl (self.subitem2_name, u'WikiAdmin', ['read', 'write', 'admin', 'create', 'destroy']), (self.subitem2_name, u'AnyUser', ['read']), # by after acl (self.subitem2_name, u'JoeDoe', ['read']), # by after acl (self.subitem2_name, u'JaneDoe', ['read']), # by after acl ] for itemname, username, may in tests: u = User(auth_username=username) u.valid = True # User should have these rights... for right in may: can_access = getattr(u.may, right)(itemname) assert can_access, "{0!r} may {1} {2!r} (normal)".format(u.name, right, itemname) # User should NOT have these rights: mayNot = [right for right in app.cfg.acl_rights_contents if right not in may] for right in mayNot: can_access = getattr(u.may, right)(itemname) assert not can_access, "{0!r} may not {1} {2!r} (normal)".format(u.name, right, itemname) # check function rights u = User(auth_username='******') assert u.may.superuser() u = User(auth_username='******') assert u.may.notextcha() u = User(auth_username='******') assert not u.may.superuser() assert not u.may.notextcha()
def groups_by_user(request, account, recursive=False): _ = request.getText if not account: raise GroupException(_('No account specified.')) if not User(request, name=account).exists(): raise GroupException(_('User not valid: ') + account) wiki_groups = set(group for group in request.groups.groups_with_member(account) if isinstance(request.groups[group], WikiGroup)) if recursive: return wiki_groups else: return set(gn for gn in wiki_groups if account in request.groups[gn].members)
def get_subscribers(**meta): """ Get all users that are subscribed to the item :param meta: key/value pairs from item metadata - itemid, name, namespace, tags keys :return: a set of Subscriber objects """ itemid = meta.get(ITEMID) name = meta.get(NAME) namespace = meta.get(NAMESPACE) fqname = CompositeName(namespace, ITEMID, itemid) tags = meta.get(TAGS) terms = [] if itemid is not None: terms.extend( [Term(SUBSCRIPTION_IDS, u"{0}:{1}".format(ITEMID, itemid))]) if namespace is not None: if name is not None: terms.extend( Term(SUBSCRIPTION_IDS, u"{0}:{1}:{2}".format( NAME, namespace, name_)) for name_ in name) if tags is not None: terms.extend( Term(SUBSCRIPTION_IDS, u"{0}:{1}:{2}".format( TAGS, namespace, tag)) for tag in tags) query = Or(terms) with flaskg.storage.indexer.ix[LATEST_REVS].searcher() as searcher: result_iterators = [ searcher.search(query, limit=None), ] subscription_patterns = searcher.lexicon(SUBSCRIPTION_PATTERNS) patterns = get_matched_subscription_patterns(subscription_patterns, **meta) result_iterators.extend( searcher.documents(subscription_patterns=pattern) for pattern in patterns) subscribers = set() for user in chain.from_iterable(result_iterators): email = user.get(EMAIL) if email: from MoinMoin.user import User u = User(uid=user.get(ITEMID)) if u.may.read(fqname): locale = user.get(LOCALE, DEFAULT_LOCALE) subscribers.add( Subscriber(user[ITEMID], user[NAME][0], email, locale)) return subscribers
def test_user_created_event(request): py.test.skip( "Test is wrong, because it assumes send_notification will be called - but if there is no superuser subscribed to UserCreatedEvent, then no notification needs to be sent." ) class server_dummy: def __init__(self): self.sent = False def send_notification(self, *args): self.sent = True event = events.UserCreatedEvent(request, User(request)) request.cfg.notification_server = server_dummy() request.cfg.secrets = "thisisnotsecret" jabbernotify.handle_user_created(event) assert request.cfg.notification_server.sent is True
def mail_admins_about(self, request, page_name, score): """Send email to the AdminGroup about a suspect page.""" # This does not yet work. I've yet to figure out how to extract the # email addresses of the members of the AdminGroup. return admin_text = Page(request, "AdminGroup").get_raw_body() group = Group(request, admin_text) emails = [] for name in group.members(): uid = getUserId(request, name) if uid is None: continue u = User(request, uid) emails.append(u.email) if score < self.spam_cutoff: subject = "Possible wiki spam" text = """\ This page as submitted to the wiki might be spam: %(page_name)s If that is not the case, add the page's URL (including action=raw and the revision number) to HamPages then revert the page to that revision. If it is spam, add it instead to SpamPages. """ % locals() else: subject = "Probable wiki spam" text = """\ This page as submitted to the wiki is likely to be spam: %(page_name)s If that is not the case, add the page's URL (including action=raw and the revision number) to HamPages then revert the page to that revision. If it is spam, do nothing. """ % locals() sendmail(request, emails, subject, text)
def newday (Wiki, ParentPage, TemplatePage, NewPage, Editor, UidName, GidName): from os import seteuid,setegid from pwd import getpwnam from grp import getgrnam uid = getpwnam(UidName).pw_uid gid = getgrnam(GidName).gr_gid setegid(gid) seteuid(uid) from MoinMoin.PageEditor import PageEditor from MoinMoin.Page import Page from MoinMoin.user import getUserId, User from MoinMoin.web.contexts import ScriptContext PageName = "%s/%s" % (ParentPage,NewPage) RequestPage = ScriptContext(Wiki, PageName) UserId = getUserId(RequestPage, Editor) RequestPage.user = User(RequestPage, UserId) Editor = PageEditor(RequestPage, PageName) Dummy, Revision, Exists = Editor.get_rev() if not Exists: RequestTemplate = ScriptContext(Wiki, TemplatePage) Viewer = Page(RequestTemplate, TemplatePage) Text = Viewer.getPageText().replace("@PAGE@", NewPage) Header = Viewer.getPageHeader() Text=Header+Text return Editor.saveText(Text, Revision)
def testMoinAuthSession(self): """ run some requests with MoinAuth, check whether session works """ from MoinMoin.user import User username = u'MoinAuthTestUser' password = u'ßecretß' User(self.request, name=username, password=password).save() # create user trail_expected = [] first = True for pagename in self.PAGES: if first: formdata = { 'name': username, 'password': password, 'login': '******', } request = self.run_request(path='/%s' % pagename, query_string='login=login', method='POST', form_data=formdata) else: # not first page, use session cookie environ_overrides = {'HTTP_COOKIE': cookie} request = self.run_request(path='/%s' % pagename, environ_overrides=environ_overrides) # Login worked? assert request.user.valid assert request.user.name == username # Do we have a session? assert request.session is not None appiter, status, headers = evaluate_request(request.request) # check if the request resulted in normal status, result headers and content assert status[:3] == '200' has_ct = has_v = has_cc = False for k, v in request.headers: if k == 'Content-Type': assert v.startswith('text/html') has_ct = True elif k == 'Vary': assert 'Cookie' in v assert 'Accept-Language' in v has_v = True elif k == 'Cache-Control': assert 'private' in v assert 'must-revalidate' in v has_cc = True elif k == 'Set-Cookie': cookie = v assert has_ct assert has_v assert has_cc # do not cache logged-in user's content assert '</html>' in ''.join(appiter) # The trail is only ever saved on the second page display # because otherwise anonymous sessions would be created # for every request, even if it never sent a cookie! # Hence, skip over the first request and only verify # the trail for the second and following. if first: first = False continue trail_expected.append(unicode(pagename)) # Requested pagenames get into trail? assert 'trail' in request.session trail = request.session['trail'] assert trail == trail_expected
def mainloop(self): argc = len(self.args) self.init_request() request = self.request if self.options.py_append_file: def logs(request): """ generator for log objects """ # global edit-log yield editlog.EditLog(request) # local edit-log of every page for pn in request.rootpage.getPageList(exists=False): yield editlog.EditLog(request, rootpagename=pn) def uids(log): """ generator for userids found in a log """ for line in log: uid = line.userid if uid: yield uid fn = self.options.py_append_file editlog_uids = set() for log in logs(request): editlog_uids |= set(uids(log)) with open(fn, "a") as f: for uid in editlog_uids: u = User(request, uid) code = u'editlog_uids.add(%r) # %r %r %r\n' % ( uid, u.name, u.email, u.jid) f.write(code.encode('utf-8')) elif self.options.py_exec_file: def check_interactive(u): if self.options.interactive: prompt = "%s %r %r %r disabled=%r (y/N)? " % ( u.id, u.name, u.email, u.jid, u.disabled) return raw_input(prompt).strip() in [ 'y', 'Y', ] else: return True fn = self.options.py_exec_file locs = dict(editlog_uids=set()) execfile(fn, {}, locs) editlog_uids = locs.get('editlog_uids') profile_uids = set(getUserList(request)) inactive_uids = profile_uids - editlog_uids for uid in inactive_uids: u = User(request, uid) if self.options.show: print "%s\t%r\t%r\t%r" % (uid, u.name, u.email, u.disabled) if self.options.disable: if check_interactive(u): u.disabled = 1 u.save() elif self.options.remove: if check_interactive(u): u.remove()