def run(self, name, display_name, email, openid, password): before_wiki() msg = user.create_user(username=name, password=password, email=email, openid=openid) if msg: print msg else: u = user.User(auth_username=name) print " %-20s %-25s %-35s - created." % (u.itemid, u.name, u.email),
def request(self, request, user_obj, **kw): cookies = kw.get('cookie') if cookies is None or cookies == {}: return None, False self.fflink.db_reconnect_if_needed() conn = self.fflink._conn for cookiename in cookies: if cookiename not in self.cookies: continue cookievalue = \ urllib.unquote(cookies[cookiename]).decode('iso-8859-1') m = re.search('^([A-Za-z0-9+/=]+)!([A-Za-z0-9+/=]+)$', cookievalue) if m is None: continue (sserial, shash) = m.group(1, 2) sdata = base64.b64decode(sserial) shash = base64.b64decode(shash) H = hmac.new(self.session_key, sdata, hashlib.sha256) if H.digest() != shash: continue m = re.search('(.*)<(.*)<(.*)<(.*)<(.*)', sdata) if m is None: continue (time, user_id, ip, nonce, user_agent) = m.group(1, 2, 3, 4, 5) cur = conn.cursor() cur.execute( """SELECT user_name, realname FROM users WHERE user_id=%s""", [user_id]) (loginname, realname) = cur.fetchone() cur.close() # MoinMoin doesn't enforce unicity of realnames u = user.User(request, name=loginname, auth_username=loginname, auth_method=self.name) if u and self.autocreate: u.create_or_update(True) if u and u.valid: self.auth_user = u return u, False self.auth_user = None return None, False
def test_auth_with_ssha_stored_password(self): """ Create user with {SSHA} password and check that user can login. """ # Create test user name = u'Test User' # pass = 12345 # salt = salt password = '******' self.createUser(name, password, True) # Try to "login" theuser = user.User(name=name, password='******') assert theuser.valid
def test_upgrade_password_from_des_to_ssha256(self): """ Create user with {DES} password and check that logging in upgrades to {SSHA}. """ # Create test user name = u'Test User' # generated with "htpasswd -nbd blaze 12345" password = '******' # 12345 self.createUser(name, password, True) # User is not required to be valid theuser = user.User(name=name, password='******') assert theuser.enc_password[:9] == '{SSHA256}'
def test_upgrade_password_from_apr1_to_ssha256(self): """ Create user with {APR1} password and check that logging in upgrades to {SSHA256}. """ # Create test user name = u'Test User' # generated with "htpasswd -nbm blaze 12345" password = '******' # 12345 self.createUser(name, password, True) # User is not required to be valid theuser = user.User(name=name, password='******') assert theuser.enc_password[:9] == '{SSHA256}'
def test_upgrade_password_from_ssha_to_ssha256(self): """ Create user with {SSHA} password and check that logging in upgrades to {SSHA256}. """ name = u'/no such user/' #pass = MoinMoin #salr = 12345 password = '******' self.createUser(name, password, True) # User is not required to be valid theuser = user.User(name=name, password='******') assert theuser.enc_password[:9] == '{SSHA256}'
def setup_from_session(): userobj = None if 'user.id' in session: auth_userid = session['user.id'] auth_method = session['user.auth_method'] auth_attrs = session['user.auth_attribs'] logging.debug("got from session: %r %r" % (auth_userid, auth_method)) logging.debug("current auth methods: %r" % app.cfg.auth_methods) if auth_method and auth_method in app.cfg.auth_methods: userobj = user.User(auth_userid, auth_method=auth_method, auth_attribs=auth_attrs) logging.debug("session started for user %r", userobj) return userobj
def set_password(uid, password, notify=False, skip_invalid=False, subject=None, text=None): u = user.User(uid) if u and u.exists(): if skip_invalid and u.has_invalidated_password(): return u.set_password(password) u.save() if notify and not u.disabled: if not u.email: raise UserHasNoEMail('Notification was requested, but User profile does not have a validated E-Mail address (name: %r id: %r)!' % (u.name, u.itemid)) mailok, msg = u.mail_password_recovery(subject=subject, text=text) if not mailok: raise MailFailed(msg) else: raise NoSuchUser('User does not exist (name: %r id: %r)!' % (u.name, u.id))
def _remove_user_from_team(u, team, cfg): acl_request = u._request acl_request.user = user.User(acl_request, None, cfg.openidrp_acl_admin) pe = PageEditor(acl_request, team + cfg.openidrp_acl_page_postfix) acl_text = pe.get_raw_body() logging.log(logging.INFO, "ACL Page content: " + acl_text) # does ACL want uid, name, username, auth_username? p = re.compile(ur"^ \* %s" % u.name, re.MULTILINE) if p.search(acl_text): logging.log(logging.INFO, "found user %s in acl, removing..." % u.name) acl_text = acl_text.replace(" * %s\n" % u.name, "") try: pe.saveText(acl_text, 0) except PageEditor.EmptyPage: pe.deletePage()
def login(self, request, user_obj, **kw): username = kw.get('username') password = kw.get('password') if not username or not password: return ContinueLogin(user_obj) logging.debug("trying to authenticate %r" % username) wikiname, username = username.split(' ', 1) # XXX Hack because ':' is not allowed in name field wikitag, wikiurl, name, err = wikiutil.resolve_interwiki(request, wikiname, username) logging.debug("resolve wiki returned: %r %r %r %r" % (wikitag, wikiurl, name, err)) if err or wikitag not in self.trusted_wikis: return ContinueLogin(user_obj) homewiki = xmlrpclib.ServerProxy(wikiurl + "?action=xmlrpc2") auth_token = homewiki.getAuthToken(name, password) if not auth_token: logging.debug("%r wiki did not return an auth token." % wikitag) return ContinueLogin(user_obj) logging.debug("successfully got an auth token for %r. trying to get user profile data..." % name) mc = xmlrpclib.MultiCall(homewiki) mc.applyAuthToken(auth_token) mc.getUserProfile() result, account_data = mc() if result != "SUCCESS": logging.debug("%r wiki did not accept auth token." % wikitag) return ContinueLogin(None) if not account_data: logging.debug("%r wiki did not return a user profile." % wikitag) return ContinueLogin(None) logging.debug("%r wiki returned a user profile." % wikitag) # TODO: check remote auth_attribs u = user.User(request, name=name, auth_method=self.name, auth_attribs=('name', 'aliasname', 'password', 'email', )) for key, value in account_data.iteritems(): if key not in request.cfg.user_transient_fields: setattr(u, key, value) u.valid = True if self.autocreate: u.create_or_update(True) logging.debug("successful interwiki auth for %r" % name) return ContinueLogin(u)
def get_editor_info(meta, external=False): addr = meta.get(ADDRESS) hostname = meta.get(HOSTNAME) text = _('anonymous') # link text title = '' # link title css = 'editor' # link/span css class name = None # author name uri = None # author homepage uri email = None # pure email address of author if app.cfg.show_hosts and addr: # only tell ip / hostname if show_hosts is True if hostname: text = hostname[:15] # 15 = len(ipaddr) name = title = u'{0}[{1}]'.format(hostname, addr) css = 'editor host' else: name = text = addr title = u'[{0}]'.format(addr) css = 'editor ip' userid = meta.get(USERID) if userid: u = user.User(userid) name = u.name0 text = name display_name = u.display_name or name if title: # we already have some address info title = u"{0} @ {1}".format(display_name, title) else: title = display_name if u.mailto_author and u.email: email = u.email css = 'editor mail' else: homewiki = app.cfg.user_homewiki if is_local_wiki(homewiki): css = 'editor homepage local' else: css = 'editor homepage interwiki' uri = url_for_item(name, wiki_name=homewiki, _external=external) result = dict(name=name, text=text, css=css, title=title) if uri: result['uri'] = uri if email: result['email'] = email return result
def test_recovery_token(self): name = u'Test_User_other' password = name self.createUser(name, password) theUser = user.User(name=name, password=password) # use recovery token to generate new password test_token = theUser.generate_recovery_token() result_success = theUser.apply_recovery_token(test_token, u'test_newpass') assert result_success # wrong token result_failure = theUser.apply_recovery_token('test_wrong_token', u'test_newpass') assert not result_failure
def mainloop(self): """ moin-package's main code. """ # Initalize request self.init_request() request = self.request _ = self.request.getText # Check our command line args if self.options.pages and self.options.search: script.fatal(_("Options --pages and --search are mutually exclusive!")) elif not self.options.output: script.fatal(_("You must specify an output file!")) elif not self.options.pages and not self.options.search: script.log(_("No pages specified using --pages or --search, assuming full package.")) include_attachments = self.options.attachment or False if include_attachments: script.log(_("All attachments included into the package.")) # Sanity checks if os.path.exists(self.options.output): script.fatal(_("Output file already exists! Cowardly refusing to continue!")) # Check for user if self.options.package_user: request.user = user.User(request, name=self.options.package_user) # Import PackagePages here, as we now have an initalized request. from MoinMoin.action.PackagePages import PackagePages # Perform actual packaging. package = PackagePages(request.rootpage.page_name, request) packageoutput = open(self.options.output, "wb") if self.options.search: packagedata = package.collectpackage(package.searchpackage(request, self.options.search), packageoutput, include_attachments=include_attachments) elif self.options.pages: packagedata = package.collectpackage(self.options.pages.split(","), packageoutput, include_attachments=include_attachments) else: packagedata = package.collectpackage(request.rootpage.getPageList( include_underlay=False, filter=lambda name: not wikiutil.isSystemPage(request, name)), packageoutput, include_attachments=include_attachments) if packagedata: script.fatal(packagedata)
def login(self, request, user_obj, **kw): if kw.get('multistage'): uid = request.session.get('botbouncer.uid', None) if not uid: return CancelLogin(None) openid = request.session['botbouncer.id'] del request.session['botbouncer.id'] del request.session['botbouncer.uid'] user_obj = user.User(request, uid, auth_method='openid', auth_username=openid) if not user_obj or not user_obj.valid: return ContinueLogin(user_obj) if user_obj.auth_method != 'openid': return ContinueLogin(user_obj) openid_id = user_obj.auth_username _ = request.getText try: url = "http://botbouncer.com/api/info?openid=%s&api_key=%s" % ( quote_plus(openid_id), self.apikey) data = urlopen(url).read().strip() except IOError: return CancelLogin(_('Could not contact botbouncer.com.')) data = data.split(':') if len(data) != 2 or data[0] != 'verified': return CancelLogin( 'botbouncer.com verification failed, probably invalid API key.' ) if data[1].lower() == 'true': # they proved they are human already return ContinueLogin(user_obj) # tell them to verify at bot bouncer first request.session['botbouncer.id'] = openid_id request.session['botbouncer.uid'] = user_obj.id goto = "http://botbouncer.com/captcha/queryuser?return_to=%%return_form&openid=%s" % ( quote_plus(request.session['botbouncer.id'])) return MultistageRedirectLogin(goto)
def subscribe_users(request, subscribe, unsubscribe, pagename, formatter): _ = request.getText if not Page(request, pagename).exists(): return u"Page does not exist." result = [] did_match = {} # get user object - only with IDs! for userid in user.getUserList(request): userobj = user.User(request, userid) name = userobj.name matched = subscribed = False for name_re in unsubscribe: if re.match(name_re, name, re.U): matched = did_match[name_re] = True if (not userobj.isSubscribedTo([pagename]) or userobj.unsubscribe(pagename)): subscribed = False break for name_re in subscribe: if re.match(name_re, name, re.U): matched = did_match[name_re] = True if (userobj.isSubscribedTo([pagename]) or (userobj.email or userobj.jid) and userobj.subscribe(pagename)): subscribed = True break if matched: result.extend([formatter.smiley(subscribed and '{*}' or '{o}'), formatter.text(" "), formatter.url(1, Page(request, name).url(request)), formatter.text(name), formatter.url(0), formatter.linebreak(preformatted=0), ]) result.extend([''.join([formatter.smiley('{X}'), formatter.text(" " + _("Not a user:"******" " + name_re), formatter.linebreak(preformatted=0)]) for name_re in subscribe + unsubscribe if name_re not in did_match]) return ''.join(result)
def setup_setuid(request, userobj): """ Check for setuid conditions in the session and setup an user object accordingly. Returns a tuple of the new user objects. @param request: a moin request object @param userobj: a moin user object @rtype: boolean @return: (new_user, user) or (user, None) """ old_user = None if 'setuid' in request.session and userobj and userobj.isSuperUser(): old_user = userobj uid = request.session['setuid'] userobj = user.User(request, uid, auth_method='setuid') userobj.valid = True logging.debug("setup_suid returns %r, %r" % (userobj, old_user)) return (userobj, old_user)
def test_perf_get_subscribers(self): pytest.skip("usually we do no performance tests") password = u"password" subscriptions = [ "{0}:{1}".format(ITEMID, self.item.meta[ITEMID]), "{0}:{1}:{2}".format(NAME, self.namespace, self.item_name), "{0}:{1}:{2}".format(TAGS, self.namespace, self.tagname), "{0}:{1}:{2}".format(NAMEPREFIX, self.namespace, u"fo"), "{0}:{1}:{2}".format(NAMERE, self.namespace, r"\wo") ] users = set() expected_names = set() for i in xrange(10000): i = unicode(i) user.create_user(username=i, password=password, email="{0}@example.org".format(i), validate=False, locale=u'en') user_ = user.User(name=i, password=password) users.add(user_) expected_names.add(user_.name0) users_sliced = list(users)[:100] expected_names_sliced = {user_.name0 for user_ in users_sliced} tests = [(users_sliced, expected_names_sliced), (users, expected_names)] import time for users_, expected_names_ in tests: print "\nTesting {0} subscribers from a total of {1} users".format( len(users_), len(users)) for subscription in subscriptions: for user_ in users_: user_.profile._meta[SUBSCRIPTIONS] = [subscription] user_.save(force=True) t = time.time() subscribers = get_subscribers(**self.item.meta) elapsed_time = time.time() - t print "{0}: {1} s".format( subscription.split(':', 1)[0], elapsed_time) subscribers_names = { subscriber.name for subscriber in subscribers } assert subscribers_names == expected_names_
def test_auth_with_des_stored_password(self): """ Create user with {DES} password and check that user can login. """ # Create test user name = u'Test User' # generated with "htpasswd -nbd blaze 12345" password = '******' # 12345 self.createUser(name, password, True) try: import crypt # Try to "login" theuser = user.User(name=name, password='******') assert theuser.valid except ImportError: py.test.skip("Platform does not provide crypt module!")
def test_auth_with_ssha256_stored_password(self): """ Create user with {SSHA256} password and check that user can login. """ # Create test user name = u'Test User' # generated with online sha256 tool # pass: 12345 # salt: salt # base64 encoded password = '******' self.createUser(name, password, True) # Try to "login" theuser = user.User(name=name, password='******') assert theuser.valid
def request(self, request, user_obj, **kw): u = None _ = request.getText # always revalidate auth if user_obj and user_obj.auth_method == self.name: user_obj = None # something else authenticated before us if user_obj: self.log.debug("already authenticated, doing nothing") return user_obj, True if self.user_name is not None: auth_username = self.user_name elif self.env_var is None: auth_username = request.remote_user else: auth_username = request.environ.get(self.env_var) self.log.debug("auth_username = %r" % auth_username) if auth_username: auth_username = self.decode_username(auth_username) auth_username = self.transform_username(auth_username) self.log.debug("auth_username (after decode/transform) = %r" % auth_username) uid = user._getUserIdByKey(request, 'aliasname', auth_username) if uid is not None: u = user.User(request, uid, auth_method=self.name, auth_attribs=('name', 'password')) self.log.debug("u: %r" % u) if u and self.autocreate: self.log.debug("autocreating user") u.create_or_update() if u and u.valid: self.log.debug("returning valid user %r" % u) return u, True # True to get other methods called, too else: self.log.debug("returning %r" % user_obj) return user_obj, True
def _handle_verify_continuation(self, request): _ = request.getText oidconsumer = consumer.Consumer(request.session, MoinOpenIDStore(request)) query = {} for key in request.values.keys(): query[key] = request.values.get(key) current_url = get_multistage_continuation_url(request, self.name, {'oidstage': '1'}) info = oidconsumer.complete(query, current_url) if info.status == consumer.FAILURE: logging.debug(_("OpenID error: %s.") % info.message) return CancelLogin(_('OpenID error: %s.') % info.message) elif info.status == consumer.CANCEL: logging.debug(_("OpenID verification canceled.")) return CancelLogin(_('Verification canceled.')) elif info.status == consumer.SUCCESS: logging.debug(_("OpenID success. id: %s") % info.identity_url) request.session['openid.id'] = info.identity_url request.session['openid.info'] = info # try to find user object uid = user.getUserIdByOpenId(request, info.identity_url) if uid: u = user.User(request, id=uid, auth_method=self.name, auth_username=info.identity_url, auth_attribs=self.auth_attribs) else: u = None # create or update the user according to the registration data u = self._handle_user_data(request, u) if u: return ContinueLogin(u) # if no user found, then we need to ask for a username, # possibly associating an existing account. logging.debug("OpenID: No user found, prompting for username") #request.session['openid.id'] = info.identity_url return MultistageFormLogin(self._get_account_name) else: logging.debug(_("OpenID failure")) return CancelLogin(_('OpenID failure.'))
def mail_recovery_token(): """ Send user an email so he can reset his password. """ username = request.form.get('username', '') if username: u = user.User(auth_username=username) if u.valid: is_ok, msg = u.mail_password_recovery() if not is_ok: flash(msg, "error") else: flash(_("{0} has been sent a password recovery email.".format(username)), "info") else: flash(_("{0} is an invalid user, no email has been sent.".format(username)), "error") else: flash(_("No user name provided, no email sent."), "error") return redirect(url_for('.userbrowser'))
def mainloop(self): self.init_request() request = self.request checks = [] if not self.options.all_sessions: now = time.time() def session_expired(session): try: return session['expires'] < now except KeyError: # this is likely a pre-1.9.1 session file without expiry return True # consider it expired checks.append(session_expired) if self.options.username: u = user.User(request, None, self.options.username) if not u.exists(): print 'User "%s" does not exist!' % self.options.username return else: def user_matches(session): try: return session['user.id'] == u.id except KeyError: return False checks.append(user_matches) session_service = request.cfg.session_service for sid in session_service.get_all_session_ids(request): session = session_service.get_session(request, sid) # if ALL conditions are met, the session will be destroyed killit = True for check in checks: killit = killit and check(session) if killit: session_service.destroy_session(request, session)
def test_sessions(self): name = u'Test_User_sessions' password = name self.createUser(name, password) theUser = user.User(name=name, password=password) # generate test token and validate it test_token = theUser.generate_session_token() result_success = theUser.validate_session(test_token) assert result_success # check if the token is saved test_new_token = theUser.get_session_token() assert test_token == test_new_token # check if password change invalidates the token theUser.set_password(password, False) result_failure = theUser.validate_session(test_token) assert not result_failure
def user_acl_report(uid): all_items = flaskg.storage.documents(wikiname=app.cfg.interwikiname) groups = flaskg.groups theuser = user.User(uid=uid) itemwise_acl = [] for item in all_items: fqname = CompositeName(item.meta.get(NAMESPACE), u'itemid', item.meta.get(ITEMID)) itemwise_acl.append({'name': item.meta.get(NAME), 'itemid': item.meta.get(ITEMID), 'fqname': fqname, 'read': theuser.may.read(fqname), 'write': theuser.may.write(fqname), 'create': theuser.may.create(fqname), 'admin': theuser.may.admin(fqname), 'destroy': theuser.may.destroy(fqname)}) return render_template('admin/user_acl_report.html', title_name=_(u'User ACL Report'), user_names=theuser.name, itemwise_acl=itemwise_acl)
def userprofile(user_name): """ Set values in user profile """ # XXX add superuser check uid = user.getUserId(user_name) u = user.User(uid) if request.method == 'GET': return _(u"User profile of %(username)s: %(email)r", username=user_name, email=(u.email, u.disabled)) if request.method == 'POST': key = request.form.get('key', '') val = request.form.get('val', '') ok = False if hasattr(u, key): ok = True oldval = getattr(u, key) if isinstance(oldval, bool): val = bool(val) elif isinstance(oldval, int): val = int(val) elif isinstance(oldval, unicode): val = unicode(val) else: ok = False if ok: setattr(u, key, val) theuser.save() flash( '%s.%s: %s -> %s' % ( user_name, key, unicode(oldval), unicode(val), ), "info") else: flash('modifying %s.%s failed' % ( user_name, key, ), "error") return redirect(url_for('admin.userbrowser'))
def userprofile(user_name): """ Set values in user profile """ u = user.User(auth_username=user_name) if request.method == 'GET': return _(u"User profile of %(username)s: %(email)s %(disabled)s", username=user_name, email=u.email, disabled=u.disabled) if request.method == 'POST': key = request.form.get('key', '') val = request.form.get('val', '') ok = False if hasattr(u, key): ok = True oldval = u.profile[key] if isinstance(oldval, bool): val = bool(int(val)) elif isinstance(oldval, int): val = int(val) elif isinstance(oldval, unicode): val = unicode(val) else: ok = False if ok: u.profile[key] = val u.save() flash( u'{0}.{1}: {2} -> {3}'.format( user_name, key, unicode(oldval), unicode(val), ), "info") else: flash(u'modifying {0}.{1} failed'.format( user_name, key, ), "error") return redirect(url_for('.userbrowser'))
def _add_user_to_team(u, team, cfg): # use admin account to create or edit ACL page # http://moinmo.in/MoinDev/CommonTasks acl_request = u._request acl_request.user = user.User(acl_request, None, cfg.openidrp_acl_admin) pe = PageEditor(acl_request, team + cfg.openidrp_acl_page_postfix) acl_text = pe.get_raw_body() logging.log(logging.INFO, "ACL Page content: " + acl_text) # make sure acl command is first line of document # only the admin user specified in wikiconfig should # be allowed to change these acl files if not acl_text or acl_text == "" or acl_text[0] != "#": acl_text = "#acl Known:read All:\n" + acl_text # does ACL want uid, name, username, auth_username? p = re.compile(ur"^ \* %s" % u.name, re.MULTILINE) if not p.search(acl_text): logging.log(logging.INFO, "did not find user %s in acl, adding..." % u.name) acl_text += u" * %s\n" % u.name pe.saveText(acl_text, 0)
def login(self, request, user_obj, **kw): username = kw.get('username') password = kw.get('password') # simply continue if something else already logged in successfully if user_obj and user_obj.valid: return ContinueLogin(user_obj) if not username and not password: return ContinueLogin(user_obj) _ = request.getText logging.debug("%s: performing login action" % self.name) if username and not password: return ContinueLogin( user_obj, _('Missing password. Please enter user name and password.')) if not username and password: return ContinueLogin( user_obj, _('Missing user name. Please enter user name and password.')) check_surge_protect(request, action='auth-ip') check_surge_protect(request, action='auth-name', username=username) u = user.User(request, name=username, password=password, auth_method=self.name) if u.valid: logging.debug("%s: successfully authenticated user %r (valid)" % (self.name, u.name)) log_attempt("auth/login (moin)", True, request, username) return ContinueLogin(u) else: logging.debug("%s: could not authenticate user %r (not valid)" % (self.name, username)) log_attempt("auth/login (moin)", False, request, username) return ContinueLogin(user_obj, _("Invalid username or password."))
def _user_select(self): options = [] users = user.getUserList(self.request) current_uid = self.request.user.id for uid in users: if uid != current_uid: name = user.User(self.request, id=uid).name options.append((uid, name)) options.sort(lambda x, y: cmp(x[1].lower(), y[1].lower())) if not options: _ = self._ self._only = True return _("You are the only user.") self._only = False size = min(10, len(options)) return util.web.makeSelection('selected_user', options, current_uid, size=size)