def process_request(self, req): if req.path_info.startswith('/login') and req.authname == 'anonymous': try: referer = self._referer(req) except AttributeError: # Fallback for Trac 0.11 compatibility. referer = req.get_header('Referer') # Steer clear of requests going nowhere or loop to self. if referer is None or \ referer.startswith(str(req.abs_href()) + '/login'): referer = req.abs_href() data = { '_dgettext': dgettext, 'login_opt_list': self.login_opt_list, 'persistent_sessions': AccountManager(self.env).persistent_sessions, 'referer': referer, 'registration_enabled': RegistrationModule(self.env).enabled, 'reset_password_enabled': AccountModule(self.env).reset_password_enabled } if req.method == 'POST': self.log.debug( "LoginModule.process_request: 'user_locked' = %s" % req.args.get('user_locked')) if not req.args.get('user_locked'): # TRANSLATOR: Intentionally obfuscated login error data['login_error'] = _("Invalid username or password") else: f_user = req.args.get('username') release_time = AccountGuard(self.env).pretty_release_time( req, f_user) if not release_time is None: data['login_error'] = _( """Account locked, please try again after %(release_time)s """, release_time=release_time) else: data['login_error'] = _("Account locked") return 'login.html', data, None else: n_plural = req.args.get('failed_logins') if n_plural > 0: add_warning( req, Markup( tag.span( tag( ngettext( "Login after %(attempts)s failed attempt", "Login after %(attempts)s failed attempts", n_plural, attempts=n_plural))))) return auth.LoginModule.process_request(self, req)
def pretty_precise_timedelta(time1, time2=None, resolution=None, diff=0): """Calculate time delta between two `datetime` objects and format for pretty-printing. If either `time1` or `time2` is None, the current time will be used instead. Extending the signature of trac.util.datefmt.pretty_timedelta pre-calculated timedeltas may be specified by the alternative `diff` keyword argument that takes precedence if used. """ if diff: age_s = diff else: time1 = to_datetime(time1) time2 = to_datetime(time2) if time1 > time2: time2, time1 = time1, time2 diff = time2 - time1 age_s = int(diff.days * 86400 + diff.seconds) age_d = age_s // 86400 # DEVEL: Always reduce resolution as required by `resolution` argument. if resolution: if age_s < resolution: return _("less than %s" % pretty_precise_timedelta(None, diff=resolution)) # Get a compact string by stripping non-significant parts. if age_s == 0: return '' # Show seconds for small time values, even in timedeltas > 1 day. t = age_s - age_d * 86400 if t > 0 and t < 120: t = ngettext('%(num)i second', '%(num)i seconds', t) if age_d == 0: return t elif age_d != age_s / 86400.0: t = format_datetime(age_s - age_d * 86400, format='%X', tzinfo=utc) if age_d == 0: return t # TRANSLATOR: Pretty datetime representation, time part provided by string substitution. return (ngettext("%(num)i day %%s", "%(num)i days %%s", age_d) % (str(t) != '0' and t or '')).rstrip()
def process_request(self, req): if req.path_info.startswith('/login') and req.authname == 'anonymous': try: referer = self._referer(req) except AttributeError: # Fallback for Trac 0.11 compatibility. referer = req.get_header('Referer') # Steer clear of requests going nowhere or loop to self. if referer is None or \ referer.startswith(str(req.abs_href()) + '/login'): referer = req.abs_href() data = { '_dgettext': dgettext, 'login_opt_list': self.login_opt_list, 'persistent_sessions': AccountManager(self.env ).persistent_sessions, 'referer': referer, 'registration_enabled': RegistrationModule(self.env).enabled, 'reset_password_enabled': AccountModule(self.env ).reset_password_enabled } if req.method == 'POST': self.log.debug( "LoginModule.process_request: 'user_locked' = %s" % req.args.get('user_locked')) if not req.args.get('user_locked'): # TRANSLATOR: Intentionally obfuscated login error data['login_error'] = _("Invalid username or password") else: f_user = req.args.get('user') release_time = AccountGuard(self.env ).pretty_release_time(req, f_user) if not release_time is None: data['login_error'] = _( """Account locked, please try again after %(release_time)s """, release_time=release_time) else: data['login_error'] = _("Account locked") return 'login.html', data, None else: n_plural=req.args.get('failed_logins') if n_plural > 0: chrome.add_warning(req, Markup(tag.span(tag(ngettext( "Login after %(attempts)s failed attempt", "Login after %(attempts)s failed attempts", n_plural, attempts=n_plural ))))) return auth.LoginModule.process_request(self, req)
def _do_db_cleanup(self, req): if req.perm.has_permission('ACCTMGR_ADMIN'): env = self.env changed = False # Get all data from 'session_attributes' db table. attr = get_user_attribute(self.env, username=None, authenticated=None) attrs = {} sel = req.args.get('sel') if req.args.get('purge') and sel is not None: sel = isinstance(sel, list) and sel or [sel] sel_len = len(sel) matched = [] for acct, states in attr.iteritems(): for state in states['id'].keys(): for elem, id in states[state]['id'].iteritems(): if id in sel: if acct in attrs.keys(): if state in attrs[acct].keys(): attrs[acct][state] \ .append(elem) else: attrs[acct][state] = [elem] else: attrs[acct] = {state: [elem]} matched.append(id) if len(matched) == sel_len: break if len(matched) == sel_len: break if len(matched) == sel_len: break for id in (frozenset(sel) - frozenset(matched)): for acct, states in attr.iteritems(): for state, id_ in states['id'].iteritems(): if id == id_: # Full account is marked, forget attributes. if acct in attrs.keys(): attrs[acct].update({state: []}) else: attrs[acct] = {state: []} matched.append(id) if len(matched) == sel_len: break if len(matched) == sel_len: break # DEVEL: for Python>2.4 better use defaultdict for counters del_count = {'acct': 0, 'attr': 0} for account, states in attrs.iteritems(): for state, elem in states.iteritems(): if len(elem) == 0: del_user_attribute(env, account, state) del_count['acct'] += 1 else: for attribute in elem: del_user_attribute(env, account, state, attribute) del_count['attr'] += 1 changed = True elif req.args.get('list'): req.redirect(req.href.admin('accounts', 'users')) if changed == True: # Update the dict after changes. attr = get_user_attribute(env, username=None, authenticated=None) data = {'_dgettext': dgettext} data.update(self._prepare_attrs(req, attr)) if req.args.get('purge') and sel is not None: accounts = attributes = '' n_plural=del_count['acct'] if n_plural > 0: accounts = tag.li(tag.span(tag(ngettext( "%(count)s account", "%(count)s accounts", n_plural, count=n_plural )))) n_plural=del_count['attr'] if n_plural > 0: attributes = tag.li(tag.span(tag(ngettext( "%(count)s account attribute", "%(count)s account attributes", n_plural, count=n_plural )))) data['result'] = tag(_("Successfully deleted:"), tag.ul(accounts, attributes)) add_stylesheet(req, 'acct_mgr/acct_mgr.css') return 'db_cleanup.html', data
def _do_db_cleanup(self, req): if req.perm.has_permission('ACCTMGR_ADMIN'): env = self.env changed = False # Get all data from 'session_attributes' db table. attr = get_user_attribute(self.env, username=None, authenticated=None) attrs = {} sel = req.args.get('sel') if req.args.get('purge') and sel is not None: sel = isinstance(sel, list) and sel or [sel] sel_len = len(sel) matched = [] for acct, states in attr.iteritems(): for state in states['id'].keys(): for elem, id in states[state]['id'].iteritems(): if id in sel: if acct in attrs.keys(): if state in attrs[acct].keys(): attrs[acct][state] \ .append(elem) else: attrs[acct][state] = [elem] else: attrs[acct] = {state: [elem]} matched.append(id) if len(matched) == sel_len: break if len(matched) == sel_len: break if len(matched) == sel_len: break for id in (frozenset(sel) - frozenset(matched)): for acct, states in attr.iteritems(): for state, id_ in states['id'].iteritems(): if id == id_: # Full account is marked, forget attributes. if acct in attrs.keys(): attrs[acct].update({state: []}) else: attrs[acct] = {state: []} matched.append(id) if len(matched) == sel_len: break if len(matched) == sel_len: break # DEVEL: for Python>2.4 better use defaultdict for counters del_count = {'acct': 0, 'attr': 0} for account, states in attrs.iteritems(): for state, elem in states.iteritems(): if len(elem) == 0: del_user_attribute(env, account, state) del_count['acct'] += 1 else: for attribute in elem: del_user_attribute(env, account, state, attribute) del_count['attr'] += 1 changed = True elif req.args.get('list'): req.redirect(req.href.admin('accounts', 'users')) if changed == True: # Update the dict after changes. attr = get_user_attribute(env, username=None, authenticated=None) data = {'_dgettext': dgettext} data.update(self._prepare_attrs(req, attr)) if req.args.get('purge') and sel is not None: accounts = attributes = '' n_plural = del_count['acct'] if n_plural > 0: accounts = tag.li( tag.span( tag( ngettext("%(count)s account", "%(count)s accounts", n_plural, count=n_plural)))) n_plural = del_count['attr'] if n_plural > 0: attributes = tag.li( tag.span( tag( ngettext("%(count)s account attribute", "%(count)s account attributes", n_plural, count=n_plural)))) data['result'] = tag(_("Successfully deleted:"), tag.ul(accounts, attributes)) add_stylesheet(req, 'acct_mgr/acct_mgr.css') return 'db_cleanup.html', data