From f9b636676d4be64e3a5141df4c6787f2a21ff848 Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 1 Oct 2018 20:12:24 +0000 Subject: [PATCH 01/23] Extends normalize_username() function to strip excessive spaces. --- evennia/accounts/accounts.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 2c33e5c1f8..07fb8f318c 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -10,7 +10,7 @@ character object, so you should customize that instead for most things). """ - +import re import time from django.conf import settings from django.contrib.auth import password_validation @@ -359,6 +359,27 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): puppet = property(__get_single_puppet) # utility methods + @classmethod + def normalize_username(cls, username): + """ + Django: Applies NFKC Unicode normalization to usernames so that visually + identical characters with different Unicode code points are considered + identical. + + (This deals with the Turkish "i" problem and similar + annoyances. Only relevant if you go out of your way to allow Unicode + usernames though-- Evennia accepts ASCII by default.) + + In this case we're simply piggybacking on this feature to apply + additional normalization per Evennia's standards. + """ + username = super(DefaultAccount, cls).normalize_username(username) + + # strip excessive spaces in accountname + username = re.sub(r"\s+", " ", username).strip() + + return username + @classmethod def validate_password(cls, password, account=None): """ From c5b7577021200e8958c932a1f8a6e884f41bbd01 Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 1 Oct 2018 21:24:33 +0000 Subject: [PATCH 02/23] Adds username normalization/validation and authentication methods to Account class. --- evennia/accounts/accounts.py | 110 ++++++++++++++++++++++++++++++++++- evennia/accounts/tests.py | 29 +++++++++ evennia/server/validators.py | 35 +++++++++++ evennia/settings_default.py | 22 +++++++ 4 files changed, 194 insertions(+), 2 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 07fb8f318c..8da9a7ea9b 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -13,9 +13,10 @@ instead for most things). import re import time from django.conf import settings -from django.contrib.auth import password_validation -from django.core.exceptions import ValidationError +from django.contrib.auth import authenticate, password_validation +from django.core.exceptions import ImproperlyConfigured, ValidationError from django.utils import timezone +from django.utils.module_loading import import_string from evennia.typeclasses.models import TypeclassBase from evennia.accounts.manager import AccountManager from evennia.accounts.models import AccountDB @@ -359,6 +360,74 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): puppet = property(__get_single_puppet) # utility methods + @classmethod + def get_username_validators(cls, validator_config=getattr(settings, 'AUTH_USERNAME_VALIDATORS', [])): + """ + Retrieves and instantiates validators for usernames. + + Args: + validator_config (list): List of dicts comprising the battery of + validators to apply to a username. + + Returns: + validators (list): List of instantiated Validator objects. + """ + + objs = [] + for validator in validator_config: + try: + klass = import_string(validator['NAME']) + except ImportError: + msg = "The module in NAME could not be imported: %s. Check your AUTH_USERNAME_VALIDATORS setting." + raise ImproperlyConfigured(msg % validator['NAME']) + objs.append(klass(**validator.get('OPTIONS', {}))) + return objs + + @classmethod + def authenticate(cls, username, password, ip=None): + """ + Checks the given username/password against the database to see if the + credentials are valid. + + Note that this simply checks credentials and returns a valid reference + to the user-- it does not log them in! + + To finish the job: + After calling this from a Command, associate the account with a Session: + - session.sessionhandler.login(session, account) + + ...or after calling this from a View, associate it with an HttpRequest: + - django.contrib.auth.login(account, request) + + Args: + username (str): Username of account + password (str): Password of account + ip (str, optional): IP address of client + + Returns: + account (DefaultAccount, None): Account whose credentials were + provided if not banned. + errors (list): Error messages of any failures. + + """ + errors = [] + if ip: ip = str(ip) + + # Authenticate and get Account object + account = authenticate(username=username, password=password) + if not account: + # User-facing message + errors.append('Username and/or password is incorrect.') + + # System log message + logger.log_sec('Authentication Failure: %s (IP: %s).' % (username, ip)) + + return None, errors + + # Account successfully authenticated + logger.log_sec('Authentication Success: %s (IP: %s).' % (account, ip)) + return account, errors + @classmethod def normalize_username(cls, username): """ @@ -379,6 +448,43 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): username = re.sub(r"\s+", " ", username).strip() return username + + @classmethod + def validate_username(cls, username): + """ + Checks the given username against the username validator associated with + Account objects, and also checks the database to make sure it is unique. + + Args: + username (str): Username to validate + + Returns: + valid (bool): Whether or not the password passed validation + errors (list): Error messages of any failures + + """ + valid = [] + errors = [] + + # Make sure we're at least using the default validator + validators = cls.get_username_validators() + if not validators: + validators = [cls.username_validator] + + # Try username against all enabled validators + for validator in validators: + try: + valid.append(not validator(username)) + except ValidationError as e: + valid.append(False) + [errors.append(x) for x in e.messages] + + # Disqualify if any check failed + if False in valid: + valid = False + else: valid = True + + return valid, errors @classmethod def validate_password(cls, password, account=None): diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index 2855dd0ca2..f1a9f16c28 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from mock import Mock from random import randint from unittest import TestCase @@ -59,6 +61,33 @@ class TestDefaultAccount(TestCase): self.s1 = Session() self.s1.puppet = None self.s1.sessid = 0 + + self.password = "testpassword" + self.account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password=self.password, typeclass=DefaultAccount) + + def test_authentication(self): + "Confirm Account authentication method is authenticating/denying users." + # Valid credentials + obj, errors = DefaultAccount.authenticate(self.account.name, self.password) + self.assertTrue(obj, 'Account did not authenticate given valid credentials.') + + # Invalid credentials + obj, errors = DefaultAccount.authenticate(self.account.name, 'xyzzy') + self.assertFalse(obj, 'Account authenticated using invalid credentials.') + + def test_username_validation(self): + "Check username validators deny relevant usernames" + # Should not accept Unicode by default, lest users pick names like this + result, error = DefaultAccount.validate_username('¯\_(ツ)_/¯') + self.assertFalse(result, "Validator allowed kanji in username.") + + # Should not allow duplicate username + result, error = DefaultAccount.validate_username(self.account.name) + self.assertFalse(result, "Duplicate username should not have passed validation.") + + # Should not allow username too short + result, error = DefaultAccount.validate_username('xx') + self.assertFalse(result, "2-character username passed validation.") def test_password_validation(self): "Check password validators deny bad passwords" diff --git a/evennia/server/validators.py b/evennia/server/validators.py index b10f990a8a..bccbde6b51 100644 --- a/evennia/server/validators.py +++ b/evennia/server/validators.py @@ -1,7 +1,42 @@ +from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ +from evennia.accounts.models import AccountDB import re +class EvenniaUsernameAvailabilityValidator: + """ + Checks to make sure a given username is not taken or otherwise reserved. + """ + + def __call__(self, username): + """ + Validates a username to make sure it is not in use or reserved. + + Args: + username (str): Username to validate + + Returns: + None (None): None if password successfully validated, + raises ValidationError otherwise. + + """ + + # Check guest list + if settings.GUEST_LIST and username.lower() in (guest.lower() for guest in settings.GUEST_LIST): + raise ValidationError( + _('Sorry, that username is reserved.'), + code='evennia_username_reserved', + ) + + # Check database + exists = AccountDB.objects.filter(username__iexact=username).exists() + if exists: + raise ValidationError( + _('Sorry, that username is already taken.'), + code='evennia_username_taken', + ) + class EvenniaPasswordValidator: def __init__(self, regex=r"^[\w. @+\-',]+$", policy="Password should contain a mix of letters, spaces, digits and @/./+/-/_/'/, only."): diff --git a/evennia/settings_default.py b/evennia/settings_default.py index 9efbb6314b..04c928ac99 100644 --- a/evennia/settings_default.py +++ b/evennia/settings_default.py @@ -809,6 +809,28 @@ AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, {'NAME': 'evennia.server.validators.EvenniaPasswordValidator'}] + +# Username validation plugins +AUTH_USERNAME_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.validators.ASCIIUsernameValidator', + }, + { + 'NAME': 'django.core.validators.MinLengthValidator', + 'OPTIONS': { + 'limit_value': 3, + } + }, + { + 'NAME': 'django.core.validators.MaxLengthValidator', + 'OPTIONS': { + 'limit_value': 30, + } + }, + { + 'NAME': 'evennia.server.validators.EvenniaUsernameAvailabilityValidator', + }, +] # Use a custom test runner that just tests Evennia-specific apps. TEST_RUNNER = 'evennia.server.tests.EvenniaTestSuiteRunner' From bce4d3cb4200c2bfac6ef980f7d98bee3829c8b2 Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 1 Oct 2018 23:58:12 +0000 Subject: [PATCH 03/23] Moves LOGIN and CREATION throttles from Command module to Account module. --- evennia/accounts/accounts.py | 20 ++++++++++++++++++-- evennia/commands/default/unloggedin.py | 10 ++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 8da9a7ea9b..1ce0f4d9f9 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -23,6 +23,7 @@ from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB from evennia.commands import cmdhandler +from evennia.server.throttle import Throttle from evennia.utils import logger from evennia.utils.utils import (lazy_property, to_str, make_iter, to_unicode, is_iter, @@ -44,6 +45,9 @@ _MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS _CMDSET_ACCOUNT = settings.CMDSET_ACCOUNT _CONNECT_CHANNEL = None +# Create throttles for too many account-creations and login attempts +CREATION_THROTTLE = Throttle(limit=2, timeout=10 * 60) +LOGIN_THROTTLE = Throttle(limit=5, timeout=5 * 60) class AccountSessionHandler(object): """ @@ -413,15 +417,27 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): errors = [] if ip: ip = str(ip) + # See if authentication is currently being throttled + if ip and LOGIN_THROTTLE.check(ip): + errors.append('Too many login failures; please try again in a few minutes.') + + # With throttle active, do not log continued hits-- it is a + # waste of storage and can be abused to make your logs harder to + # read and fill up your disk. + return None, errors + # Authenticate and get Account object account = authenticate(username=username, password=password) if not account: # User-facing message errors.append('Username and/or password is incorrect.') - # System log message + # Log auth failures while throttle is inactive logger.log_sec('Authentication Failure: %s (IP: %s).' % (username, ip)) + # Update throttle + if ip: LOGIN_THROTTLE.update(ip) + return None, errors # Account successfully authenticated @@ -543,7 +559,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): if error: raise error super(DefaultAccount, self).set_password(password) - logger.log_info("Password succesfully changed for %s." % self) + logger.log_sec("Password successfully changed for %s." % self) self.at_password_change() def delete(self, *args, **kwargs): diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index 8ae700e2c1..d77d7ee2b9 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -7,12 +7,13 @@ import datetime from random import getrandbits from django.conf import settings from django.contrib.auth import authenticate +from evennia.accounts.accounts import CREATION_THROTTLE, LOGIN_THROTTLE from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB -from evennia.server.models import ServerConfig -from evennia.server.throttle import Throttle from evennia.comms.models import ChannelDB +from evennia.server.models import ServerConfig from evennia.server.sessionhandler import SESSIONS +from evennia.server.throttle import Throttle from evennia.utils import create, logger, utils, gametime from evennia.commands.cmdhandler import CMD_LOGINSTART @@ -26,11 +27,8 @@ __all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", MULTISESSION_MODE = settings.MULTISESSION_MODE CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE -# Create throttles for too many connections, account-creations and login attempts +# Create throttles for too many connections CONNECTION_THROTTLE = Throttle(limit=5, timeout=1 * 60) -CREATION_THROTTLE = Throttle(limit=2, timeout=10 * 60) -LOGIN_THROTTLE = Throttle(limit=5, timeout=5 * 60) - def create_guest_account(session): """ From 1fe44704f709cf2801bbb18d3f9067001e34c0bf Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 2 Oct 2018 00:05:07 +0000 Subject: [PATCH 04/23] Adds logging of throttle activation and customizable message upon update. --- evennia/accounts/accounts.py | 2 +- evennia/server/throttle.py | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 1ce0f4d9f9..a6a29fab72 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -436,7 +436,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): logger.log_sec('Authentication Failure: %s (IP: %s).' % (username, ip)) # Update throttle - if ip: LOGIN_THROTTLE.update(ip) + if ip: LOGIN_THROTTLE.update(ip, 'Too many authentication failures') return None, errors diff --git a/evennia/server/throttle.py b/evennia/server/throttle.py index 56c88c63f2..944b7f880e 100644 --- a/evennia/server/throttle.py +++ b/evennia/server/throttle.py @@ -1,4 +1,5 @@ from collections import defaultdict, deque +from evennia.utils import logger import time class Throttle(object): @@ -50,22 +51,34 @@ class Throttle(object): if ip: return self.storage.get(ip, deque(maxlen=self.cache_size)) else: return self.storage - def update(self, ip): + def update(self, ip, failmsg='Exceeded threshold.'): """ - Store the time of the latest failure/ + Store the time of the latest failure. Args: ip (str): IP address of requestor + failmsg (str, optional): Message to display in logs upon activation + of throttle. Returns: None """ + # Get current status + previously_throttled = self.check(ip) + # Enforce length limits if not self.storage[ip].maxlen: self.storage[ip] = deque(maxlen=self.cache_size) self.storage[ip].append(time.time()) + + # See if this update caused a change in status + currently_throttled = self.check(ip) + + # If this makes it engage, log a single activation event + if (not previously_throttled and currently_throttled): + logger.log_sec('Throttle Activated: %s (IP: %s, %i hits in %i seconds.)' % (failmsg, ip, self.limit, self.timeout)) def check(self, ip): """ From d570be49be3fa12733510c8e0df719c19e47dbf8 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 2 Oct 2018 20:23:23 +0000 Subject: [PATCH 05/23] Moves account creation logic from Commands module to Account class. --- evennia/accounts/accounts.py | 269 ++++++++++++++++++++++++- evennia/accounts/tests.py | 37 +++- evennia/commands/default/unloggedin.py | 222 +++++--------------- evennia/server/validators.py | 2 +- 4 files changed, 354 insertions(+), 176 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index a6a29fab72..6bd812b6fa 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -23,8 +23,9 @@ from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB from evennia.commands import cmdhandler +from evennia.server.models import ServerConfig from evennia.server.throttle import Throttle -from evennia.utils import logger +from evennia.utils import create, logger from evennia.utils.utils import (lazy_property, to_str, make_iter, to_unicode, is_iter, variable_from_module) @@ -34,6 +35,7 @@ from evennia.commands.cmdsethandler import CmdSetHandler from django.utils.translation import ugettext as _ from future.utils import with_metaclass +from random import getrandbits __all__ = ("DefaultAccount",) @@ -364,6 +366,31 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): puppet = property(__get_single_puppet) # utility methods + @classmethod + def is_banned(cls, **kwargs): + """ + Checks if a given username or IP is banned. + + Kwargs: + ip (str, optional): IP address. + username (str, optional): Username. + + Returns: + is_banned (bool): Whether either is banned or not. + + """ + + ip = kwargs.get('ip', '').strip() + username = kwargs.get('username', '').lower().strip() + + # Check IP and/or name bans + bans = ServerConfig.objects.conf("server_bans") + if bans and (any(tup[0] == username for tup in bans if username) or + any(tup[2].match(ip) for tup in bans if ip and tup[2])): + return True + + return False + @classmethod def get_username_validators(cls, validator_config=getattr(settings, 'AUTH_USERNAME_VALIDATORS', [])): """ @@ -386,9 +413,85 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): raise ImproperlyConfigured(msg % validator['NAME']) objs.append(klass(**validator.get('OPTIONS', {}))) return objs + + @classmethod + def authenticate_guest(cls, **kwargs): + """ + Gets or creates a Guest account object. + + Kwargs: + ip (str, optional): IP address of requestor; used for ban checking, + throttling and logging + + """ + errors = [] + account = None + username = None + ip = kwargs.get('ip', '').strip() + + # check if guests are enabled. + if not settings.GUEST_ENABLED: + errors.append('Guest accounts are not enabled on this server.') + return None, errors + + # See if authentication is currently being throttled + if ip and LOGIN_THROTTLE.check(ip): + errors.append('Too many login failures; please try again in a few minutes.') + + # With throttle active, do not log continued hits-- it is a + # waste of storage and can be abused to make your logs harder to + # read and/or fill up your disk. + return None, errors + + # check if IP banned + if ip and cls.is_banned(ip=ip): + errors.append("|rYou have been banned and cannot continue from here." \ + "\nIf you feel this ban is in error, please email an admin.|x") + logger.log_sec('Authentication Denied (Banned): %s (IP: %s).' % ('guest', ip)) + LOGIN_THROTTLE.update(ip, 'Too many sightings of banned IP.') + return None, errors + + try: + # Find an available guest name. + for name in settings.GUEST_LIST: + if not AccountDB.objects.filter(username__iexact=name).count(): + username = name + break + if not username: + errors.append("All guest accounts are in use. Please try again later.") + if ip: LOGIN_THROTTLE.update(ip, 'Too many requests for Guest access.') + return None, errors + else: + # build a new account with the found guest username + password = "%016x" % getrandbits(64) + home = ObjectDB.objects.get_id(settings.GUEST_HOME) + permissions = settings.PERMISSION_GUEST_DEFAULT + character_typeclass = settings.BASE_CHARACTER_TYPECLASS + account_typeclass = settings.BASE_GUEST_TYPECLASS + account, errs = cls.create( + guest=True, + username=username, + password=password, + permissions=permissions, + account_typeclass=account_typeclass, + character_typeclass=character_typeclass, + ip=ip, + ) + errors.extend(errs) + return account, errors + + except Exception: + # We are in the middle between logged in and -not, so we have + # to handle tracebacks ourselves at this point. If we don't, + # we won't see any errors at all. + errors.append("An error occurred. Please e-mail an admin if the problem persists.") + logger.log_trace() + return None, errors + + return account, errors @classmethod - def authenticate(cls, username, password, ip=None): + def authenticate(cls, username, password, ip='', **kwargs): """ Checks the given username/password against the database to see if the credentials are valid. @@ -408,6 +511,9 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): password (str): Password of account ip (str, optional): IP address of client + Kwargs: + session (Session, optional): Session requesting authentication + Returns: account (DefaultAccount, None): Account whose credentials were provided if not banned. @@ -423,7 +529,17 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): # With throttle active, do not log continued hits-- it is a # waste of storage and can be abused to make your logs harder to - # read and fill up your disk. + # read and/or fill up your disk. + return None, errors + + # Check IP and/or name bans + banned = cls.is_banned(username=username, ip=ip) + if banned: + # this is a banned IP or name! + errors.append("|rYou have been banned and cannot continue from here." \ + "\nIf you feel this ban is in error, please email an admin.|x") + logger.log_sec('Authentication Denied (Banned): %s (IP: %s).' % (username, ip)) + LOGIN_THROTTLE.update(ip, 'Too many sightings of banned artifact.') return None, errors # Authenticate and get Account object @@ -436,7 +552,14 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): logger.log_sec('Authentication Failure: %s (IP: %s).' % (username, ip)) # Update throttle - if ip: LOGIN_THROTTLE.update(ip, 'Too many authentication failures') + if ip: LOGIN_THROTTLE.update(ip, 'Too many authentication failures.') + + # Try to call post-failure hook + session = kwargs.get('session', None) + if session: + account = AccountDB.objects.get_account_from_name(username) + if account: + account.at_failed_login(session) return None, errors @@ -493,7 +616,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): valid.append(not validator(username)) except ValidationError as e: valid.append(False) - [errors.append(x) for x in e.messages] + errors.extend(e.messages) # Disqualify if any check failed if False in valid: @@ -561,6 +684,142 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): super(DefaultAccount, self).set_password(password) logger.log_sec("Password successfully changed for %s." % self) self.at_password_change() + + @classmethod + def create(cls, *args, **kwargs): + """ + Creates an Account (or Account/Character pair for MM<2) with default + (or overridden) permissions and having joined them to the appropriate + default channels. + + Kwargs: + username (str): Username of Account owner + password (str): Password of Account owner + email (str, optional): Email address of Account owner + ip (str, optional): IP address of requesting connection + guest (bool, optional): Whether or not this is to be a Guest account + + permissions (str, optional): Default permissions for the Account + account_typeclass (str, optional): Typeclass to use for new Account + character_typeclass (str, optional): Typeclass to use for new char + when applicable. + + Returns: + account (Account): Account if successfully created; None if not + errors (list): List of error messages in string form + + """ + + account = None + errors = [] + + username = kwargs.get('username') + password = kwargs.get('password') + email = kwargs.get('email', '').strip() + guest = kwargs.get('guest', False) + + permissions = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) + account_typeclass = kwargs.get('account_typeclass', settings.BASE_ACCOUNT_TYPECLASS) + character_typeclass = kwargs.get('character_typeclass', settings.BASE_CHARACTER_TYPECLASS) + + ip = kwargs.get('ip', '') + if ip and CREATION_THROTTLE.check(ip): + errors.append("You are creating too many accounts. Please log into an existing account.") + return None, errors + + # Normalize username + username = cls.normalize_username(username) + + # Validate username + if not guest: + valid, errs = cls.validate_username(username) + if not valid: + # this echoes the restrictions made by django's auth + # module (except not allowing spaces, for convenience of + # logging in). + errors.extend(errs) + return None, errors + + # Validate password + # Have to create a dummy Account object to check username similarity + valid, errs = cls.validate_password(password, account=cls(username=username)) + if not valid: + errors.extend(errs) + return None, errors + + # Check IP and/or name bans + banned = cls.is_banned(username=username, ip=ip) + if banned: + # this is a banned IP or name! + string = "|rYou have been banned and cannot continue from here." \ + "\nIf you feel this ban is in error, please email an admin.|x" + errors.append(string) + return None, errors + + # everything's ok. Create the new account account. + try: + try: + account = create.create_account(username, email, password, permissions=permissions, typeclass=account_typeclass) + logger.log_sec('Account Created: %s (IP: %s).' % (account, ip)) + + except Exception as e: + errors.append("There was an error creating the Account. If this problem persists, contact an admin.") + logger.log_trace() + return None, errors + + # This needs to be set so the engine knows this account is + # logging in for the first time. (so it knows to call the right + # hooks during login later) + account.db.FIRST_LOGIN = True + + # Record IP address of creation, if available + if ip: account.db.creator_ip = ip + + # join the new account to the public channel + pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) + if not pchannel or not pchannel.connect(account): + string = "New account '%s' could not connect to public channel!" % account.key + errors.append(string) + logger.log_err(string) + + if account: + if settings.MULTISESSION_MODE < 2: + default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) + + try: + character = create.create_object(character_typeclass, key=account.key, home=default_home, permissions=permissions) + + # set playable character list + account.db._playable_characters.append(character) + + # allow only the character itself and the account to puppet this character (and Developers). + character.locks.add("puppet:id(%i) or pid(%i) or perm(Developer) or pperm(Developer)" % + (character.id, account.id)) + + # If no description is set, set a default description + if not character.db.desc: + character.db.desc = "This is a character." + # We need to set this to have @ic auto-connect to this character + account.db._last_puppet = character + + # Record creator id and creation IP + if ip: character.db.creator_ip = ip + character.db.creator_id = account.id + + except Exception as e: + errors.append("There was an error creating a Character. If this problem persists, contact an admin.") + logger.log_trace() + + except Exception: + # We are in the middle between logged in and -not, so we have + # to handle tracebacks ourselves at this point. If we don't, + # we won't see any errors at all. + errors.append("An error occurred. Please e-mail an admin if the problem persists.") + logger.log_trace() + + # Update the throttle to indicate a new account was created from this IP + if ip and not guest: CREATION_THROTTLE.update(ip, 'Too many accounts being created.') + return account, errors def delete(self, *args, **kwargs): """ diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index f1a9f16c28..72f13bbb3a 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -75,6 +75,41 @@ class TestDefaultAccount(TestCase): obj, errors = DefaultAccount.authenticate(self.account.name, 'xyzzy') self.assertFalse(obj, 'Account authenticated using invalid credentials.') + def test_create(self): + "Confirm Account creation is working as expected." + # Create a normal account + account, errors = DefaultAccount.create(username='ziggy', password='stardust11') + self.assertTrue(account, 'New account should have been created.') + + # Try creating a duplicate account + account, errors = DefaultAccount.create(username='Ziggy', password='starman11') + self.assertFalse(account, 'Duplicate account name should not have been allowed.') + + # Guest account should not be permitted + account, errors = DefaultAccount.authenticate_guest() + self.assertFalse(account, 'Guest account was created despite being disabled.') + + settings.GUEST_ENABLED = True + settings.GUEST_LIST = ['bruce_wayne'] + + # Create a guest account + account, errors = DefaultAccount.authenticate_guest() + self.assertTrue(account, 'Guest account should have been created.') + + # Create a second guest account + account, errors = DefaultAccount.authenticate_guest() + self.assertFalse(account, 'Two guest accounts were created despite a single entry on the guest list!') + + settings.GUEST_ENABLED = False + + def test_throttle(self): + "Confirm throttle activates on too many failures." + for x in xrange(20): + obj, errors = DefaultAccount.authenticate(self.account.name, 'xyzzy', ip='12.24.36.48') + self.assertFalse(obj, 'Authentication was provided a bogus password; this should NOT have returned an account!') + + self.assertTrue('too many login failures' in errors[-1].lower(), 'Failed logins should have been throttled.') + def test_username_validation(self): "Check username validators deny relevant usernames" # Should not accept Unicode by default, lest users pick names like this @@ -92,7 +127,7 @@ class TestDefaultAccount(TestCase): def test_password_validation(self): "Check password validators deny bad passwords" - self.account = create.create_account("TestAccount%s" % randint(0, 9), + self.account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password="testpassword", typeclass=DefaultAccount) for bad in ('', '123', 'password', 'TestAccount', '#', 'xyzzy'): self.assertFalse(self.account.validate_password(bad, account=self.account)[0]) diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index d77d7ee2b9..7cf8b40c88 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -4,10 +4,9 @@ Commands that are available from the connect screen. import re import time import datetime -from random import getrandbits + from django.conf import settings from django.contrib.auth import authenticate -from evennia.accounts.accounts import CREATION_THROTTLE, LOGIN_THROTTLE from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB @@ -15,7 +14,7 @@ from evennia.server.models import ServerConfig from evennia.server.sessionhandler import SESSIONS from evennia.server.throttle import Throttle -from evennia.utils import create, logger, utils, gametime +from evennia.utils import class_from_module, create, logger, utils, gametime from evennia.commands.cmdhandler import CMD_LOGINSTART COMMAND_DEFAULT_CLASS = utils.class_from_module(settings.COMMAND_DEFAULT_CLASS) @@ -27,9 +26,6 @@ __all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", MULTISESSION_MODE = settings.MULTISESSION_MODE CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE -# Create throttles for too many connections -CONNECTION_THROTTLE = Throttle(limit=5, timeout=1 * 60) - def create_guest_account(session): """ Creates a guest account/character for this session, if one is available. @@ -42,50 +38,20 @@ def create_guest_account(session): the boolean is whether guest accounts are enabled at all. the Account which was created from an available guest name. """ - # check if guests are enabled. - if not settings.GUEST_ENABLED: - return False, None - - # Check IP bans. - bans = ServerConfig.objects.conf("server_bans") - if bans and any(tup[2].match(session.address) for tup in bans if tup[2]): - # this is a banned IP! - string = "|rYou have been banned and cannot continue from here." \ - "\nIf you feel this ban is in error, please email an admin.|x" - session.msg(string) - session.sessionhandler.disconnect(session, "Good bye! Disconnecting.") - return True, None - - try: - # Find an available guest name. - accountname = None - for name in settings.GUEST_LIST: - if not AccountDB.objects.filter(username__iexact=accountname).count(): - accountname = name - break - if not accountname: - session.msg("All guest accounts are in use. Please try again later.") - return True, None - else: - # build a new account with the found guest accountname - password = "%016x" % getrandbits(64) - home = ObjectDB.objects.get_id(settings.GUEST_HOME) - permissions = settings.PERMISSION_GUEST_DEFAULT - typeclass = settings.BASE_CHARACTER_TYPECLASS - ptypeclass = settings.BASE_GUEST_TYPECLASS - new_account = _create_account(session, accountname, password, permissions, ptypeclass) - if new_account: - _create_character(session, new_account, typeclass, home, permissions) - return True, new_account - - except Exception: - # We are in the middle between logged in and -not, so we have - # to handle tracebacks ourselves at this point. If we don't, - # we won't see any errors at all. - session.msg("An error occurred. Please e-mail an admin if the problem persists.") - logger.log_trace() - raise - + enabled = settings.GUEST_ENABLED + address = session.address + + # Get account class + Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) + + # Get an available guest account + # authenticate_guest() handles its own throttling + account, errors = Account.authenticate_guest(ip=address) + if account: + return enabled, account + else: + session.msg("|R%s|n" % '\n'.join(errors)) + return enabled, None def create_normal_account(session, name, password): """ @@ -99,38 +65,17 @@ def create_normal_account(session, name, password): Returns: account (Account): the account which was created from the name and password. """ - # check for too many login errors too quick. + # Get account class + Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) + address = session.address - if isinstance(address, tuple): - address = address[0] - - if LOGIN_THROTTLE.check(address): - session.msg("|RYou made too many connection attempts. Try again in a few minutes.|n") - return None - + # Match account name and check password - account = authenticate(username=name, password=password) - + # authenticate() handles all its own throttling + account, errors = Account.authenticate(username=name, password=password, ip=address, session=session) if not account: # No accountname or password match - session.msg("Incorrect login information given.") - # this just updates the throttle - LOGIN_THROTTLE.update(address) - # calls account hook for a failed login if possible. - account = AccountDB.objects.get_account_from_name(name) - if account: - account.at_failed_login(session) - return None - - # Check IP and/or name bans - bans = ServerConfig.objects.conf("server_bans") - if bans and (any(tup[0] == account.name.lower() for tup in bans) or - any(tup[2].match(session.address) for tup in bans if tup[2])): - # this is a banned IP or name! - string = "|rYou have been banned and cannot continue from here." \ - "\nIf you feel this ban is in error, please email an admin.|x" - session.msg(string) - session.sessionhandler.disconnect(session, "Good bye! Disconnecting.") + session.msg("|R%s|n" % '\n'.join(errors)) return None return account @@ -162,15 +107,10 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): there is no object yet before the account has logged in) """ session = self.caller - - # check for too many login errors too quick. address = session.address - if isinstance(address, tuple): - address = address[0] - if CONNECTION_THROTTLE.check(address): - # timeout is 5 minutes. - session.msg("|RYou made too many connection attempts. Try again in a few minutes.|n") - return + + # Get account class + Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) args = self.args # extract double quote parts @@ -178,23 +118,27 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): if len(parts) == 1: # this was (hopefully) due to no double quotes being found, or a guest login parts = parts[0].split(None, 1) + # Guest login if len(parts) == 1 and parts[0].lower() == "guest": - enabled, new_account = create_guest_account(session) - if new_account: - session.sessionhandler.login(session, new_account) - if enabled: + account, errors = Account.authenticate_guest(ip=address) + if account: + session.sessionhandler.login(session, account) return - + else: + session.msg("|R%s|n" % '\n'.join(errors)) + return + if len(parts) != 2: session.msg("\n\r Usage (without <>): connect ") return - CONNECTION_THROTTLE.update(address) name, password = parts - account = create_normal_account(session, name, password) + account, errors = Account.authenticate(username=name, password=password, ip=address, session=session) if account: session.sessionhandler.login(session, account) + else: + session.msg("|R%s|n" % '\n'.join(errors)) class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS): @@ -220,14 +164,10 @@ class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS): session = self.caller args = self.args.strip() - # Rate-limit account creation. address = session.address - - if isinstance(address, tuple): - address = address[0] - if CREATION_THROTTLE.check(address): - session.msg("|RYou are creating too many accounts. Try again in a few minutes.|n") - return + + # Get account class + Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) # extract double quoted parts parts = [part.strip() for part in re.split(r"\"", args) if part.strip()] @@ -239,77 +179,21 @@ class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS): "\nIf or contains spaces, enclose it in double quotes." session.msg(string) return - accountname, password = parts - - # sanity checks - if not re.findall(r"^[\w. @+\-']+$", accountname) or not (0 < len(accountname) <= 30): - # this echoes the restrictions made by django's auth - # module (except not allowing spaces, for convenience of - # logging in). - string = "\n\r Accountname can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_/' only." - session.msg(string) - return - # strip excessive spaces in accountname - accountname = re.sub(r"\s+", " ", accountname).strip() - if AccountDB.objects.filter(username__iexact=accountname): - # account already exists (we also ignore capitalization here) - session.msg("Sorry, there is already an account with the name '%s'." % accountname) - return - # Reserve accountnames found in GUEST_LIST - if settings.GUEST_LIST and accountname.lower() in (guest.lower() for guest in settings.GUEST_LIST): - string = "\n\r That name is reserved. Please choose another Accountname." - session.msg(string) - return - - # Validate password - Account = utils.class_from_module(settings.BASE_ACCOUNT_TYPECLASS) - # Have to create a dummy Account object to check username similarity - valid, error = Account.validate_password(password, account=Account(username=accountname)) - if error: - errors = [e for suberror in error.messages for e in error.messages] - string = "\n".join(errors) - session.msg(string) - return - - # Check IP and/or name bans - bans = ServerConfig.objects.conf("server_bans") - if bans and (any(tup[0] == accountname.lower() for tup in bans) or - - any(tup[2].match(session.address) for tup in bans if tup[2])): - # this is a banned IP or name! - string = "|rYou have been banned and cannot continue from here." \ - "\nIf you feel this ban is in error, please email an admin.|x" - session.msg(string) - session.sessionhandler.disconnect(session, "Good bye! Disconnecting.") - return + + username, password = parts # everything's ok. Create the new account account. - try: - permissions = settings.PERMISSION_ACCOUNT_DEFAULT - typeclass = settings.BASE_CHARACTER_TYPECLASS - new_account = _create_account(session, accountname, password, permissions) - if new_account: - if MULTISESSION_MODE < 2: - default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) - _create_character(session, new_account, typeclass, default_home, permissions) - - # Update the throttle to indicate a new account was created from this IP - CREATION_THROTTLE.update(address) - - # tell the caller everything went well. - string = "A new account '%s' was created. Welcome!" - if " " in accountname: - string += "\n\nYou can now log in with the command 'connect \"%s\" '." - else: - string += "\n\nYou can now log with the command 'connect %s '." - session.msg(string % (accountname, accountname)) - - except Exception: - # We are in the middle between logged in and -not, so we have - # to handle tracebacks ourselves at this point. If we don't, - # we won't see any errors at all. - session.msg("An error occurred. Please e-mail an admin if the problem persists.") - logger.log_trace() + account, errors = Account.create(username=username, password=password, ip=address, session=session) + if account: + # tell the caller everything went well. + string = "A new account '%s' was created. Welcome!" + if " " in username: + string += "\n\nYou can now log in with the command 'connect \"%s\" '." + else: + string += "\n\nYou can now log with the command 'connect %s '." + session.msg(string % (username, username)) + else: + session.msg("|R%s|n" % '\n'.join(errors)) class CmdUnconnectedQuit(COMMAND_DEFAULT_CLASS): diff --git a/evennia/server/validators.py b/evennia/server/validators.py index bccbde6b51..fdadeda6e3 100644 --- a/evennia/server/validators.py +++ b/evennia/server/validators.py @@ -23,7 +23,7 @@ class EvenniaUsernameAvailabilityValidator: """ # Check guest list - if settings.GUEST_LIST and username.lower() in (guest.lower() for guest in settings.GUEST_LIST): + if (settings.GUEST_LIST and username.lower() in (guest.lower() for guest in settings.GUEST_LIST)): raise ValidationError( _('Sorry, that username is reserved.'), code='evennia_username_reserved', From cfd1efa2f3463b5721a2d908ef5175de5eaaf673 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 20:28:47 +0000 Subject: [PATCH 06/23] Updates docstring to expand MM acronym for clarity. --- evennia/accounts/accounts.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 6bd812b6fa..e7f838ecbd 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -688,9 +688,9 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): @classmethod def create(cls, *args, **kwargs): """ - Creates an Account (or Account/Character pair for MM<2) with default - (or overridden) permissions and having joined them to the appropriate - default channels. + Creates an Account (or Account/Character pair for MULTISESSION_MODE<2) + with default (or overridden) permissions and having joined them to the + appropriate default channels. Kwargs: username (str): Username of Account owner From 3d7a6a40dccdd2909f506083d8252e39ca8779a2 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 20:29:12 +0000 Subject: [PATCH 07/23] Implements create() method migrated from CmdCreate on DefaultObject. --- evennia/objects/objects.py | 69 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index 27d8147999..6525e2f39a 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -857,6 +857,75 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): string = "This place should not exist ... contact an admin." obj.msg(_(string)) obj.move_to(home) + + @classmethod + def create(cls, key, **kwargs): + """ + Creates a basic object with default parameters, unless otherwise + specified or extended. + + Provides a friendlier interface to the utils.create_object() function. + + Args: + key (str): Name of the new object. + + Kwargs: + caller (Object): Intended owner (read: 'caller') of object. + description (str): Brief description of this object. + home (Object or str): Obj or #dbref to use as the object's + home location. + permissions (list): A list of permission strings or tuples (permstring, category). + locks (str): one or more lockstrings, separated by semicolons. + aliases (list): A list of alternative keys or tuples (aliasstring, category). + tags (list): List of tag keys or tuples (tagkey, category) or (tagkey, category, data). + destination (Object or str): Obj or #dbref to use as an Exit's + target. + report_to (Object): The object to return error messages to. + nohome (bool): This allows the creation of objects without a + default home location; only used when creating the default + location itself or during unittests. + attributes (list): Tuples on the form (key, value) or (key, value, category), + (key, value, lockstring) or (key, value, lockstring, default_access). + to set as Attributes on the new object. + nattributes (list): Non-persistent tuples on the form (key, value). Note that + adding this rarely makes sense since this data will not survive a reload. + typeclass (class or str): Class or python path to a typeclass. + + Returns: + object (Object): A newly created object of the given typeclass. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + caller = kwargs.get('caller') + + # If no typeclass supplied, use this class + kwargs['typeclass'] = kwargs.pop('typeclass', cls) + + # Set the supplied key as the name of the intended object + kwargs['key'] = key + + # Create a sane lockstring if one wasn't supplied + lockstring = kwargs.get('locks') + if caller and not lockstring: + lock_template = "control:id({id}) or perm(Admin);delete:id({id}) or perm(Admin)" + lockstring = lock_template.format(id=caller.id) + kwargs['locks'] = lockstring + + # Create object + try: + obj = create.create_object(**kwargs) + except Exception as e: + errors.append("Object '%s' could not be created." % key) + logger.log_trace() + return None, errors + + # Set description if there is none, or update it if provided + if kwargs.get('description') or not obj.db.desc: + desc = kwargs.get('description', "You see nothing special.") + obj.db.desc = desc + + return obj, errors def copy(self, new_key=None): """ From 0217e4915ba8b271ced4c652b7b4c666759f93a3 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 22:20:06 +0000 Subject: [PATCH 08/23] Implements create() methods on DefaultObject, DefaultCharacter, DefaultRoom and DefaultExit. --- evennia/objects/objects.py | 268 ++++++++++++++++++++++++++++++++----- 1 file changed, 234 insertions(+), 34 deletions(-) diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index 6525e2f39a..7d9e344936 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -191,6 +191,10 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): without `obj.save()` having to be called explicitly. """ + # lockstring of newly created objects, for easy overloading. + # Will be formatted with the appropriate attributes. + lockstring = "control:id({account_id}) or perm(Admin);delete:id({account_id}) or perm(Admin)" + objects = ObjectManager() # on-object properties @@ -859,7 +863,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): obj.move_to(home) @classmethod - def create(cls, key, **kwargs): + def create(cls, key, account=None, **kwargs): """ Creates a basic object with default parameters, unless otherwise specified or extended. @@ -868,28 +872,11 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): Args: key (str): Name of the new object. + account (Account): Account to attribute this object to Kwargs: - caller (Object): Intended owner (read: 'caller') of object. - description (str): Brief description of this object. - home (Object or str): Obj or #dbref to use as the object's - home location. - permissions (list): A list of permission strings or tuples (permstring, category). - locks (str): one or more lockstrings, separated by semicolons. - aliases (list): A list of alternative keys or tuples (aliasstring, category). - tags (list): List of tag keys or tuples (tagkey, category) or (tagkey, category, data). - destination (Object or str): Obj or #dbref to use as an Exit's - target. - report_to (Object): The object to return error messages to. - nohome (bool): This allows the creation of objects without a - default home location; only used when creating the default - location itself or during unittests. - attributes (list): Tuples on the form (key, value) or (key, value, category), - (key, value, lockstring) or (key, value, lockstring, default_access). - to set as Attributes on the new object. - nattributes (list): Non-persistent tuples on the form (key, value). Note that - adding this rarely makes sense since this data will not survive a reload. - typeclass (class or str): Class or python path to a typeclass. + description (str): Brief description for this object. + ip (str): IP address of creator (for object auditing). Returns: object (Object): A newly created object of the given typeclass. @@ -897,7 +884,10 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): """ errors = [] - caller = kwargs.get('caller') + obj = None + + # Get IP address of creator, if available + ip = kwargs.pop('ip') # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) @@ -907,24 +897,27 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): # Create a sane lockstring if one wasn't supplied lockstring = kwargs.get('locks') - if caller and not lockstring: - lock_template = "control:id({id}) or perm(Admin);delete:id({id}) or perm(Admin)" - lockstring = lock_template.format(id=caller.id) + if account and not lockstring: + lockstring = cls.lockstring.format(account_id=account.id) kwargs['locks'] = lockstring # Create object try: obj = create.create_object(**kwargs) - except Exception as e: - errors.append("Object '%s' could not be created." % key) - logger.log_trace() - return None, errors - - # Set description if there is none, or update it if provided - if kwargs.get('description') or not obj.db.desc: - desc = kwargs.get('description', "You see nothing special.") - obj.db.desc = desc + # Record creator id and creation IP + if ip: obj.db.creator_ip = ip + if caller: obj.db.creator_id = account.id + + # Set description if there is none, or update it if provided + if kwargs.get('description') or not obj.db.desc: + desc = kwargs.get('description', "You see nothing special.") + obj.db.desc = desc + + except Exception as e: + errors.append("There was an error creating the Object '%s'. If this problem persists, contact an admin." % key) + logger.log_trace() + return obj, errors def copy(self, new_key=None): @@ -1890,7 +1883,79 @@ class DefaultCharacter(DefaultObject): a character avatar controlled by an account. """ + # lockstring of newly created rooms, for easy overloading. + # Will be formatted with the appropriate attributes. + lockstring = "puppet:id({character_id}) or pid({account_id}) or perm(Developer) or pperm(Developer)" + + @classmethod + def create(cls, key, account, **kwargs): + """ + Creates a basic Character with default parameters, unless otherwise + specified or extended. + + Provides a friendlier interface to the utils.create_character() function. + + Args: + key (str): Name of the new Character. + account (obj): Account to associate this Character with. Required as + an argument, but one can fake it out by supplying None-- it will + change the default lockset and skip creator attribution. + + Kwargs: + description (str): Brief description for this object. + ip (str): IP address of creator (for object auditing). + + Returns: + character (Object): A newly created Character of the given typeclass. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + obj = None + + # Get IP address of creator, if available + ip = kwargs.pop('ip') + + # If no typeclass supplied, use this class + kwargs['typeclass'] = kwargs.pop('typeclass', cls) + + # Set the supplied key as the name of the intended object + kwargs['key'] = key + + # Get home for character + kwargs['home'] = ObjectDB.objects.get_id(kwargs.get('home', settings.DEFAULT_HOME)) + + # Get permissions + kwargs['permissions'] = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) + + try: + # Create the Character + obj = create.create_object(**kwargs) + + # Record creator id and creation IP + if ip: obj.db.creator_ip = ip + if account: obj.db.creator_id = account.id + + # Add locks + locks = kwargs.pop('locks') + if not locks and account: + # Allow only the character itself and the creator account to puppet this character (and Developers). + locks = cls.lockstring.format(**{'character_id': obj.id, 'account_id': account.id}) + elif not locks and not account: + locks = cls.lockstring.format(**{'character_id': obj.id, 'account_id': -1}) + + obj.locks.add(locks) + # If no description is set, set a default description + if kwargs.get('description') or not obj.db.desc: + obj.db.desc = kwargs.get('description', "This is a character.") + + except Exception as e: + errors.append("There was an error creating a Character. If this problem persists, contact an admin.") + logger.log_trace() + + return obj, errors + def basetype_setup(self): """ Setup character-specific security. @@ -2007,6 +2072,69 @@ class DefaultRoom(DefaultObject): This is the base room object. It's just like any Object except its location is always `None`. """ + # lockstring of newly created rooms, for easy overloading. + # Will be formatted with the {id} of the creating object. + lockstring = "control:id({id}) or perm(Admin); " \ + "delete:id({id}) or perm(Admin); " \ + "edit:id({id}) or perm(Admin)" + + @classmethod + def create(cls, key, account, **kwargs): + """ + Creates a basic Room with default parameters, unless otherwise + specified or extended. + + Provides a friendlier interface to the utils.create_object() function. + + Args: + key (str): Name of the new Room. + account (obj): Account to associate this Room with. + + Kwargs: + description (str): Brief description for this object. + ip (str): IP address of creator (for object auditing). + + Returns: + room (Object): A newly created Room of the given typeclass. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + obj = None + + # Get IP address of creator, if available + ip = kwargs.pop('ip') + + # If no typeclass supplied, use this class + kwargs['typeclass'] = kwargs.pop('typeclass', cls) + + # Set the supplied key as the name of the intended object + kwargs['key'] = key + + # Get who to send errors to + kwargs['report_to'] = kwargs.pop('report_to', account) + + try: + # Create the Room + obj = create.create_object(**kwargs) + + # Set appropriate locks + lockstring = kwargs.get('locks', cls.lockstring.format(id=account.id)) + obj.locks.add(lockstring) + + # Record creator id and creation IP + if ip: obj.db.creator_ip = ip + if account: obj.db.creator_id = account.id + + # If no description is set, set a default description + if kwargs.get('description') or not obj.db.desc: + obj.db.desc = kwargs.get('description', "This is a room.") + + except Exception as e: + errors.append("There was an error creating a Room. If this problem persists, contact an admin.") + logger.log_trace() + + return obj, errors def basetype_setup(self): """ @@ -2085,6 +2213,13 @@ class DefaultExit(DefaultObject): exit_command = ExitCommand priority = 101 + + # lockstring of newly created exits, for easy overloading. + # Will be formatted with the {id} of the creating object. + lockstring = "control:id({id}) or perm(Admin); " \ + "delete:id({id}) or perm(Admin); " \ + "edit:id({id}) or perm(Admin)" + # Helper classes and methods to implement the Exit. These need not # be overloaded unless one want to change the foundation for how # Exits work. See the end of the class for hook methods to overload. @@ -2122,6 +2257,71 @@ class DefaultExit(DefaultObject): return exit_cmdset # Command hooks + + @classmethod + def create(cls, key, source, dest, account, **kwargs): + """ + Creates a basic Exit with default parameters, unless otherwise + specified or extended. + + Provides a friendlier interface to the utils.create_object() function. + + Args: + key (str): Name of the new Exit, as it should appear from the + source room. + source (Room): The room to create this exit in. + dest (Room): The room to which this exit should go. + account (obj): Account to associate this Exit with. + + Kwargs: + description (str): Brief description for this object. + ip (str): IP address of creator (for object auditing). + + Returns: + exit (Object): A newly created Room of the given typeclass. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + obj = None + + # Get IP address of creator, if available + ip = kwargs.pop('ip') + + # If no typeclass supplied, use this class + kwargs['typeclass'] = kwargs.pop('typeclass', cls) + + # Set the supplied key as the name of the intended object + kwargs['key'] = key + + # Get who to send errors to + kwargs['report_to'] = kwargs.pop('report_to', account) + + # Set to/from rooms + kwargs['location'] = source + kwargs['destination'] = dest + + try: + # Create the Exit + obj = create.create_object(**kwargs) + + # Set appropriate locks + lockstring = kwargs.get('locks', cls.lockstring.format(id=account.id)) + obj.locks.add(lockstring) + + # Record creator id and creation IP + if ip: obj.db.creator_ip = ip + if account: obj.db.creator_id = account.id + + # If no description is set, set a default description + if kwargs.get('description') or not obj.db.desc: + obj.db.desc = kwargs.get('description', "This is an exit.") + + except Exception as e: + errors.append("There was an error creating an Exit. If this problem persists, contact an admin.") + logger.log_trace() + + return obj, errors def basetype_setup(self): """ From d9336dd7189b7e719353de3e95348123a141686f Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 23:04:01 +0000 Subject: [PATCH 09/23] Bugfixes. --- evennia/objects/objects.py | 63 ++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index 7d9e344936..83ec5fd2ff 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -21,6 +21,7 @@ from evennia.scripts.scripthandler import ScriptHandler from evennia.commands import cmdset, command from evennia.commands.cmdsethandler import CmdSetHandler from evennia.commands import cmdhandler +from evennia.utils import create from evennia.utils import search from evennia.utils import logger from evennia.utils import ansi @@ -429,7 +430,8 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): # only allow exact matching if searching the entire database # or unique #dbrefs exact = True - elif candidates is None: + else: + # TODO: write code...if candidates is None: # no custom candidates given - get them automatically if location: # location(s) were given @@ -872,7 +874,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): Args: key (str): Name of the new object. - account (Account): Account to attribute this object to + account (Account): Account to attribute this object to. Kwargs: description (str): Brief description for this object. @@ -887,7 +889,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): obj = None # Get IP address of creator, if available - ip = kwargs.pop('ip') + ip = kwargs.pop('ip', '') # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) @@ -895,6 +897,9 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): # Set the supplied key as the name of the intended object kwargs['key'] = key + # Get a supplied description, if any + description = kwargs.pop('description', '') + # Create a sane lockstring if one wasn't supplied lockstring = kwargs.get('locks') if account and not lockstring: @@ -907,16 +912,15 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): # Record creator id and creation IP if ip: obj.db.creator_ip = ip - if caller: obj.db.creator_id = account.id + if account: obj.db.creator_id = account.id # Set description if there is none, or update it if provided - if kwargs.get('description') or not obj.db.desc: - desc = kwargs.get('description', "You see nothing special.") + if description or not obj.db.desc: + desc = description if description else "You see nothing special." obj.db.desc = desc except Exception as e: - errors.append("There was an error creating the Object '%s'. If this problem persists, contact an admin." % key) - logger.log_trace() + errors.append(str(e)) return obj, errors @@ -1914,7 +1918,7 @@ class DefaultCharacter(DefaultObject): obj = None # Get IP address of creator, if available - ip = kwargs.pop('ip') + ip = kwargs.pop('ip', '') # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) @@ -1928,6 +1932,12 @@ class DefaultCharacter(DefaultObject): # Get permissions kwargs['permissions'] = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) + # Get description if provided + description = kwargs.pop('description', '') + + # Get locks if provided + locks = kwargs.pop('locks', '') + try: # Create the Character obj = create.create_object(**kwargs) @@ -1937,7 +1947,6 @@ class DefaultCharacter(DefaultObject): if account: obj.db.creator_id = account.id # Add locks - locks = kwargs.pop('locks') if not locks and account: # Allow only the character itself and the creator account to puppet this character (and Developers). locks = cls.lockstring.format(**{'character_id': obj.id, 'account_id': account.id}) @@ -1947,12 +1956,11 @@ class DefaultCharacter(DefaultObject): obj.locks.add(locks) # If no description is set, set a default description - if kwargs.get('description') or not obj.db.desc: - obj.db.desc = kwargs.get('description', "This is a character.") + if description or not obj.db.desc: + obj.db.desc = description if description else "This is a character." except Exception as e: - errors.append("There was an error creating a Character. If this problem persists, contact an admin.") - logger.log_trace() + errors.append(str(e)) return obj, errors @@ -2103,7 +2111,7 @@ class DefaultRoom(DefaultObject): obj = None # Get IP address of creator, if available - ip = kwargs.pop('ip') + ip = kwargs.pop('ip', '') # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) @@ -2114,6 +2122,9 @@ class DefaultRoom(DefaultObject): # Get who to send errors to kwargs['report_to'] = kwargs.pop('report_to', account) + # Get description, if provided + description = kwargs.pop('description', '') + try: # Create the Room obj = create.create_object(**kwargs) @@ -2127,12 +2138,11 @@ class DefaultRoom(DefaultObject): if account: obj.db.creator_id = account.id # If no description is set, set a default description - if kwargs.get('description') or not obj.db.desc: - obj.db.desc = kwargs.get('description', "This is a room.") + if description or not obj.db.desc: + obj.db.desc = description if description else "This is a room." except Exception as e: - errors.append("There was an error creating a Room. If this problem persists, contact an admin.") - logger.log_trace() + errors.append(str(e)) return obj, errors @@ -2259,7 +2269,7 @@ class DefaultExit(DefaultObject): # Command hooks @classmethod - def create(cls, key, source, dest, account, **kwargs): + def create(cls, key, account, source, dest, **kwargs): """ Creates a basic Exit with default parameters, unless otherwise specified or extended. @@ -2269,9 +2279,9 @@ class DefaultExit(DefaultObject): Args: key (str): Name of the new Exit, as it should appear from the source room. + account (obj): Account to associate this Exit with. source (Room): The room to create this exit in. dest (Room): The room to which this exit should go. - account (obj): Account to associate this Exit with. Kwargs: description (str): Brief description for this object. @@ -2286,7 +2296,7 @@ class DefaultExit(DefaultObject): obj = None # Get IP address of creator, if available - ip = kwargs.pop('ip') + ip = kwargs.pop('ip', '') # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) @@ -2301,6 +2311,8 @@ class DefaultExit(DefaultObject): kwargs['location'] = source kwargs['destination'] = dest + description = kwargs.pop('description', '') + try: # Create the Exit obj = create.create_object(**kwargs) @@ -2314,12 +2326,11 @@ class DefaultExit(DefaultObject): if account: obj.db.creator_id = account.id # If no description is set, set a default description - if kwargs.get('description') or not obj.db.desc: - obj.db.desc = kwargs.get('description', "This is an exit.") + if description or not obj.db.desc: + obj.db.desc = description if description else "This is an exit." except Exception as e: - errors.append("There was an error creating an Exit. If this problem persists, contact an admin.") - logger.log_trace() + errors.append(str(e)) return obj, errors From 940b8e4ff9e9363e0c5d6627f7e9ca2c70d3bac9 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 23:04:22 +0000 Subject: [PATCH 10/23] Adds unit tests for create() methods. --- evennia/objects/tests.py | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 evennia/objects/tests.py diff --git a/evennia/objects/tests.py b/evennia/objects/tests.py new file mode 100644 index 0000000000..144ac5a678 --- /dev/null +++ b/evennia/objects/tests.py @@ -0,0 +1,41 @@ + +from evennia.utils.test_resources import EvenniaTest +from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit + +class ObjectCreationTest(EvenniaTest): + + ip = '212.216.139.14' + + def test_object_create(self): + description = 'A home for a grouch.' + obj, errors = DefaultObject.create('trashcan', self.account, description=description, ip=self.ip) + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + self.assertEqual(description, obj.db.desc) + self.assertEqual(obj.db.creator_ip, self.ip) + + def test_character_create(self): + description = 'A furry green monster, reeking of garbage.' + obj, errors = DefaultCharacter.create('oscar', self.account, description=description, ip=self.ip) + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + self.assertEqual(description, obj.db.desc) + self.assertEqual(obj.db.creator_ip, self.ip) + + def test_room_create(self): + description = 'A dimly-lit alley behind the local Chinese restaurant.' + obj, errors = DefaultRoom.create('oscar', self.account, description=description, ip=self.ip) + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + self.assertEqual(description, obj.db.desc) + self.assertEqual(obj.db.creator_ip, self.ip) + + def test_exit_create(self): + description = 'The steaming depths of the dumpster, ripe with refuse in various states of decomposition.' + obj, errors = DefaultExit.create('in', self.account, self.room1, self.room2, description=description, ip=self.ip) + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + self.assertEqual(description, obj.db.desc) + self.assertEqual(obj.db.creator_ip, self.ip) + + \ No newline at end of file From 9a7368865d83012b9d6769e11cb1d4c074136408 Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 23:21:39 +0000 Subject: [PATCH 11/23] Modifies Account.create() to use Character.create() on lesser multisession modes. --- evennia/accounts/accounts.py | 39 ++++++++++++------------------------ 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index e7f838ecbd..4825891b9f 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -25,7 +25,7 @@ from evennia.comms.models import ChannelDB from evennia.commands import cmdhandler from evennia.server.models import ServerConfig from evennia.server.throttle import Throttle -from evennia.utils import create, logger +from evennia.utils import class_from_module, create, logger from evennia.utils.utils import (lazy_property, to_str, make_iter, to_unicode, is_iter, variable_from_module) @@ -782,33 +782,20 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): errors.append(string) logger.log_err(string) - if account: - if settings.MULTISESSION_MODE < 2: - default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) - - try: - character = create.create_object(character_typeclass, key=account.key, home=default_home, permissions=permissions) - - # set playable character list - account.db._playable_characters.append(character) + if account and settings.MULTISESSION_MODE < 2: + # Load the appropriate Character class + Character = class_from_module(settings.BASE_CHARACTER_TYPECLASS) - # allow only the character itself and the account to puppet this character (and Developers). - character.locks.add("puppet:id(%i) or pid(%i) or perm(Developer) or pperm(Developer)" % - (character.id, account.id)) + # Create the character + character, errs = Character.create(account.key, account, ip=ip) + errors.extend(errs) - # If no description is set, set a default description - if not character.db.desc: - character.db.desc = "This is a character." - # We need to set this to have @ic auto-connect to this character - account.db._last_puppet = character - - # Record creator id and creation IP - if ip: character.db.creator_ip = ip - character.db.creator_id = account.id - - except Exception as e: - errors.append("There was an error creating a Character. If this problem persists, contact an admin.") - logger.log_trace() + if character: + # Update playable character list + account.db._playable_characters.append(character) + + # We need to set this to have @ic auto-connect to this character + account.db._last_puppet = character except Exception: # We are in the middle between logged in and -not, so we have From fadb6b59b718011026f29897c838077f7725cccd Mon Sep 17 00:00:00 2001 From: Johnny Date: Tue, 9 Oct 2018 23:41:04 +0000 Subject: [PATCH 12/23] Adds create() method to DefaultScript and unit test for DefaultScript.create(). --- evennia/scripts/scripts.py | 28 +++++++++++++++++++++++++++- evennia/scripts/tests.py | 10 ++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/evennia/scripts/scripts.py b/evennia/scripts/scripts.py index 8bff161cf5..ba6f7edff2 100644 --- a/evennia/scripts/scripts.py +++ b/evennia/scripts/scripts.py @@ -12,7 +12,7 @@ from django.utils.translation import ugettext as _ from evennia.typeclasses.models import TypeclassBase from evennia.scripts.models import ScriptDB from evennia.scripts.manager import ScriptManager -from evennia.utils import logger +from evennia.utils import create, logger from future.utils import with_metaclass __all__ = ["DefaultScript", "DoNothing", "Store"] @@ -323,6 +323,32 @@ class DefaultScript(ScriptBase): or describe a state that changes under certain conditions. """ + + @classmethod + def create(cls, key, **kwargs): + """ + Provides a passthrough interface to the utils.create_script() function. + + Args: + key (str): Name of the new object. + + Returns: + object (Object): A newly created object of the given typeclass. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + obj = None + + kwargs['key'] = key + + try: + obj = create.create_script(**kwargs) + except Exception as e: + errors.append("The script '%s' encountered errors and could not be created." % key) + logger.log_err(e) + + return obj, errors def at_script_creation(self): """ diff --git a/evennia/scripts/tests.py b/evennia/scripts/tests.py index dbd36ae956..f5120d0da5 100644 --- a/evennia/scripts/tests.py +++ b/evennia/scripts/tests.py @@ -1,10 +1,20 @@ # this is an optimized version only available in later Django versions from unittest import TestCase +from evennia import DefaultScript from evennia.scripts.models import ScriptDB, ObjectDoesNotExist from evennia.utils.create import create_script +from evennia.utils.test_resources import EvenniaTest from evennia.scripts.scripts import DoNothing +class TestScript(EvenniaTest): + + def test_create(self): + "Check the script can be created via the convenience method." + obj, errors = DefaultScript.create('useless-machine') + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + class TestScriptDB(TestCase): "Check the singleton/static ScriptDB object works correctly" From eb9fdbc7e2f2448d60dd4a8157adf392cb73deed Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 10 Oct 2018 00:41:27 +0000 Subject: [PATCH 13/23] Implements create() and authenticate() on DefaultGuest object; migrates DefaultAccount.authenticate_guest(). --- evennia/accounts/accounts.py | 164 +++++++++++++++++------------------ evennia/accounts/tests.py | 46 +++++----- 2 files changed, 108 insertions(+), 102 deletions(-) diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 4825891b9f..845db6794e 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -413,82 +413,6 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): raise ImproperlyConfigured(msg % validator['NAME']) objs.append(klass(**validator.get('OPTIONS', {}))) return objs - - @classmethod - def authenticate_guest(cls, **kwargs): - """ - Gets or creates a Guest account object. - - Kwargs: - ip (str, optional): IP address of requestor; used for ban checking, - throttling and logging - - """ - errors = [] - account = None - username = None - ip = kwargs.get('ip', '').strip() - - # check if guests are enabled. - if not settings.GUEST_ENABLED: - errors.append('Guest accounts are not enabled on this server.') - return None, errors - - # See if authentication is currently being throttled - if ip and LOGIN_THROTTLE.check(ip): - errors.append('Too many login failures; please try again in a few minutes.') - - # With throttle active, do not log continued hits-- it is a - # waste of storage and can be abused to make your logs harder to - # read and/or fill up your disk. - return None, errors - - # check if IP banned - if ip and cls.is_banned(ip=ip): - errors.append("|rYou have been banned and cannot continue from here." \ - "\nIf you feel this ban is in error, please email an admin.|x") - logger.log_sec('Authentication Denied (Banned): %s (IP: %s).' % ('guest', ip)) - LOGIN_THROTTLE.update(ip, 'Too many sightings of banned IP.') - return None, errors - - try: - # Find an available guest name. - for name in settings.GUEST_LIST: - if not AccountDB.objects.filter(username__iexact=name).count(): - username = name - break - if not username: - errors.append("All guest accounts are in use. Please try again later.") - if ip: LOGIN_THROTTLE.update(ip, 'Too many requests for Guest access.') - return None, errors - else: - # build a new account with the found guest username - password = "%016x" % getrandbits(64) - home = ObjectDB.objects.get_id(settings.GUEST_HOME) - permissions = settings.PERMISSION_GUEST_DEFAULT - character_typeclass = settings.BASE_CHARACTER_TYPECLASS - account_typeclass = settings.BASE_GUEST_TYPECLASS - account, errs = cls.create( - guest=True, - username=username, - password=password, - permissions=permissions, - account_typeclass=account_typeclass, - character_typeclass=character_typeclass, - ip=ip, - ) - errors.extend(errs) - return account, errors - - except Exception: - # We are in the middle between logged in and -not, so we have - # to handle tracebacks ourselves at this point. If we don't, - # we won't see any errors at all. - errors.append("An error occurred. Please e-mail an admin if the problem persists.") - logger.log_trace() - return None, errors - - return account, errors @classmethod def authenticate(cls, username, password, ip='', **kwargs): @@ -700,7 +624,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): guest (bool, optional): Whether or not this is to be a Guest account permissions (str, optional): Default permissions for the Account - account_typeclass (str, optional): Typeclass to use for new Account + typeclass (str, optional): Typeclass to use for new Account character_typeclass (str, optional): Typeclass to use for new char when applicable. @@ -719,8 +643,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): guest = kwargs.get('guest', False) permissions = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) - account_typeclass = kwargs.get('account_typeclass', settings.BASE_ACCOUNT_TYPECLASS) - character_typeclass = kwargs.get('character_typeclass', settings.BASE_CHARACTER_TYPECLASS) + typeclass = kwargs.get('typeclass', settings.BASE_ACCOUNT_TYPECLASS) ip = kwargs.get('ip', '') if ip and CREATION_THROTTLE.check(ip): @@ -759,7 +682,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): # everything's ok. Create the new account account. try: try: - account = create.create_account(username, email, password, permissions=permissions, typeclass=account_typeclass) + account = create.create_account(username, email, password, permissions=permissions, typeclass=typeclass) logger.log_sec('Account Created: %s (IP: %s).' % (account, ip)) except Exception as e: @@ -784,10 +707,15 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): if account and settings.MULTISESSION_MODE < 2: # Load the appropriate Character class - Character = class_from_module(settings.BASE_CHARACTER_TYPECLASS) + character_typeclass = kwargs.get('character_typeclass', settings.BASE_CHARACTER_TYPECLASS) + character_home = kwargs.get('home') + Character = class_from_module(character_typeclass) # Create the character - character, errs = Character.create(account.key, account, ip=ip) + character, errs = Character.create( + account.key, account, ip=ip, typeclass=character_typeclass, + permissions=permissions, home=character_home + ) errors.extend(errs) if character: @@ -1453,6 +1381,78 @@ class DefaultGuest(DefaultAccount): This class is used for guest logins. Unlike Accounts, Guests and their characters are deleted after disconnection. """ + + @classmethod + def create(cls, **kwargs): + """ + Forwards request to cls.authenticate(); returns a DefaultGuest object + if one is available for use. + """ + return cls.authenticate(**kwargs) + + @classmethod + def authenticate(cls, **kwargs): + """ + Gets or creates a Guest account object. + + Kwargs: + ip (str, optional): IP address of requestor; used for ban checking, + throttling and logging + + Returns: + account (Object): Guest account object, if available + errors (list): List of error messages accrued during this request. + + """ + errors = [] + account = None + username = None + ip = kwargs.get('ip', '').strip() + + # check if guests are enabled. + if not settings.GUEST_ENABLED: + errors.append('Guest accounts are not enabled on this server.') + return None, errors + + try: + # Find an available guest name. + for name in settings.GUEST_LIST: + if not AccountDB.objects.filter(username__iexact=name).count(): + username = name + break + if not username: + errors.append("All guest accounts are in use. Please try again later.") + if ip: LOGIN_THROTTLE.update(ip, 'Too many requests for Guest access.') + return None, errors + else: + # build a new account with the found guest username + password = "%016x" % getrandbits(64) + home = settings.GUEST_HOME + permissions = settings.PERMISSION_GUEST_DEFAULT + typeclass = settings.BASE_GUEST_TYPECLASS + + # Call parent class creator + account, errs = super(DefaultGuest, cls).create( + guest=True, + username=username, + password=password, + permissions=permissions, + typeclass=typeclass, + home=home, + ip=ip, + ) + errors.extend(errs) + return account, errors + + except Exception as e: + # We are in the middle between logged in and -not, so we have + # to handle tracebacks ourselves at this point. If we don't, + # we won't see any errors at all. + errors.append("An error occurred. Please e-mail an admin if the problem persists.") + logger.log_trace() + return None, errors + + return account, errors def at_post_login(self, session=None, **kwargs): """ diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index f68d344e37..e78cf9ffd1 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -6,8 +6,9 @@ from unittest import TestCase from django.test import override_settings from evennia.accounts.accounts import AccountSessionHandler -from evennia.accounts.accounts import DefaultAccount +from evennia.accounts.accounts import DefaultAccount, DefaultGuest from evennia.server.session import Session +from evennia.utils.test_resources import EvenniaTest from evennia.utils import create from django.conf import settings @@ -59,9 +60,31 @@ class TestAccountSessionHandler(TestCase): def test_count(self): "Check count method" self.assertEqual(self.handler.count(), len(self.handler.get())) + +class TestDefaultGuest(EvenniaTest): + "Check DefaultGuest class" + + ip = '212.216.134.22' + + def test_authenticate(self): + # Guest account should not be permitted + account, errors = DefaultGuest.authenticate(ip=self.ip) + self.assertFalse(account, 'Guest account was created despite being disabled.') + + settings.GUEST_ENABLED = True + settings.GUEST_LIST = ['bruce_wayne'] + + # Create a guest account + account, errors = DefaultGuest.authenticate(ip=self.ip) + self.assertTrue(account, 'Guest account should have been created.') + + # Create a second guest account + account, errors = DefaultGuest.authenticate(ip=self.ip) + self.assertFalse(account, 'Two guest accounts were created with a single entry on the guest list!') + + settings.GUEST_ENABLED = False - -class TestDefaultAccount(TestCase): +class TestDefaultAccount(EvenniaTest): "Check DefaultAccount class" def setUp(self): @@ -92,23 +115,6 @@ class TestDefaultAccount(TestCase): account, errors = DefaultAccount.create(username='Ziggy', password='starman11') self.assertFalse(account, 'Duplicate account name should not have been allowed.') - # Guest account should not be permitted - account, errors = DefaultAccount.authenticate_guest() - self.assertFalse(account, 'Guest account was created despite being disabled.') - - settings.GUEST_ENABLED = True - settings.GUEST_LIST = ['bruce_wayne'] - - # Create a guest account - account, errors = DefaultAccount.authenticate_guest() - self.assertTrue(account, 'Guest account should have been created.') - - # Create a second guest account - account, errors = DefaultAccount.authenticate_guest() - self.assertFalse(account, 'Two guest accounts were created despite a single entry on the guest list!') - - settings.GUEST_ENABLED = False - def test_throttle(self): "Confirm throttle activates on too many failures." for x in xrange(20): From 06f2cba42b0414a7f038d0c6e91274513eff5d6e Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 10 Oct 2018 00:48:54 +0000 Subject: [PATCH 14/23] Changes method used for guest authentication. --- evennia/commands/default/unloggedin.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index 7cf8b40c88..dc0f1ed476 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -109,9 +109,6 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): session = self.caller address = session.address - # Get account class - Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) - args = self.args # extract double quote parts parts = [part.strip() for part in re.split(r"\"", args) if part.strip()] @@ -121,7 +118,10 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): # Guest login if len(parts) == 1 and parts[0].lower() == "guest": - account, errors = Account.authenticate_guest(ip=address) + # Get Guest typeclass + Guest = class_from_module(settings.BASE_GUEST_TYPECLASS) + + account, errors = Guest.authenticate(ip=address) if account: session.sessionhandler.login(session, account) return @@ -133,6 +133,9 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): session.msg("\n\r Usage (without <>): connect ") return + # Get account class + Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) + name, password = parts account, errors = Account.authenticate(username=name, password=password, ip=address, session=session) if account: From 7d93098176b1a9288f21c2e07183bcc7555d71fe Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 10 Oct 2018 00:57:39 +0000 Subject: [PATCH 15/23] Corrects additional incorrect guest authentication method. --- evennia/commands/default/unloggedin.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index dc0f1ed476..7ff2c9a29a 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -42,11 +42,11 @@ def create_guest_account(session): address = session.address # Get account class - Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) + Guest = class_from_module(settings.BASE_GUEST_TYPECLASS) # Get an available guest account - # authenticate_guest() handles its own throttling - account, errors = Account.authenticate_guest(ip=address) + # authenticate() handles its own throttling + account, errors = Guest.authenticate(ip=address) if account: return enabled, account else: From 60c9d2c6ec13a08b520bfb9640923dd74c676c43 Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 10 Oct 2018 01:15:19 +0000 Subject: [PATCH 16/23] Redirects system errors from user-facing return to error log. --- evennia/objects/objects.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index 83ec5fd2ff..1b5cca6f64 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -920,7 +920,8 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): obj.db.desc = desc except Exception as e: - errors.append(str(e)) + errors.append("An error occurred while creating this '%s' object." % key) + logger.log_err(e) return obj, errors @@ -1960,7 +1961,8 @@ class DefaultCharacter(DefaultObject): obj.db.desc = description if description else "This is a character." except Exception as e: - errors.append(str(e)) + errors.append("An error occurred while creating this '%s' object." % key) + logger.log_err(e) return obj, errors @@ -2142,7 +2144,8 @@ class DefaultRoom(DefaultObject): obj.db.desc = description if description else "This is a room." except Exception as e: - errors.append(str(e)) + errors.append("An error occurred while creating this '%s' object." % key) + logger.log_err(e) return obj, errors @@ -2330,7 +2333,8 @@ class DefaultExit(DefaultObject): obj.db.desc = description if description else "This is an exit." except Exception as e: - errors.append(str(e)) + errors.append("An error occurred while creating this '%s' object." % key) + logger.log_err(e) return obj, errors From 6d0a670340b4812215626c9ff68af36c60c566b7 Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 17 Oct 2018 20:25:28 +0000 Subject: [PATCH 17/23] Compacts options dict for username validators list. --- evennia/settings_default.py | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/evennia/settings_default.py b/evennia/settings_default.py index d6da94fb2f..7926ed276c 100644 --- a/evennia/settings_default.py +++ b/evennia/settings_default.py @@ -813,25 +813,12 @@ AUTH_PASSWORD_VALIDATORS = [ # Username validation plugins AUTH_USERNAME_VALIDATORS = [ - { - 'NAME': 'django.contrib.auth.validators.ASCIIUsernameValidator', - }, - { - 'NAME': 'django.core.validators.MinLengthValidator', - 'OPTIONS': { - 'limit_value': 3, - } - }, - { - 'NAME': 'django.core.validators.MaxLengthValidator', - 'OPTIONS': { - 'limit_value': 30, - } - }, - { - 'NAME': 'evennia.server.validators.EvenniaUsernameAvailabilityValidator', - }, -] + {'NAME': 'django.contrib.auth.validators.ASCIIUsernameValidator'}, + {'NAME': 'django.core.validators.MinLengthValidator', + 'OPTIONS': {'limit_value': 3}}, + {'NAME': 'django.core.validators.MaxLengthValidator', + 'OPTIONS': {'limit_value': 30}}, + {'NAME': 'evennia.server.validators.EvenniaUsernameAvailabilityValidator'}] # Use a custom test runner that just tests Evennia-specific apps. TEST_RUNNER = 'evennia.server.tests.EvenniaTestSuiteRunner' From 98bc76cd60823d63addba635246ec7194b7b3e51 Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 17 Oct 2018 20:26:51 +0000 Subject: [PATCH 18/23] Adds create() method to DefaultChannel object, and unit test. --- evennia/comms/comms.py | 38 +++++++++++++++++++++++++++++++++++++- evennia/comms/tests.py | 13 +++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 evennia/comms/tests.py diff --git a/evennia/comms/comms.py b/evennia/comms/comms.py index a7d74ae0e4..adb90c66ac 100644 --- a/evennia/comms/comms.py +++ b/evennia/comms/comms.py @@ -5,7 +5,7 @@ Base typeclass for in-game Channels. from evennia.typeclasses.models import TypeclassBase from evennia.comms.models import TempMsg, ChannelDB from evennia.comms.managers import ChannelManager -from evennia.utils import logger +from evennia.utils import create, logger from evennia.utils.utils import make_iter from future.utils import with_metaclass _CHANNEL_HANDLER = None @@ -220,6 +220,42 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)): return self.locks.check(accessing_obj, access_type=access_type, default=default, no_superuser_bypass=no_superuser_bypass) + @classmethod + def create(cls, key, *args, **kwargs): + """ + Creates a basic Channel with default parameters, unless otherwise + specified or extended. + + Provides a friendlier interface to the utils.create_channel() function. + + Args: + key (str): This must be unique. + + Kwargs: + aliases (list of str): List of alternative (likely shorter) keynames. + description (str): A description of the channel, for use in listings. + locks (str): Lockstring. + keep_log (bool): Log channel throughput. + typeclass (str or class): The typeclass of the Channel (not + often used). + + Returns: + channel (Channel): A newly created Channel. + errors (list): A list of errors in string form, if any. + + """ + errors = [] + obj = None + + try: + kwargs['desc'] = kwargs.pop('description', '') + obj = create.create_channel(key, *args, **kwargs) + except Exception as exc: + errors.append("An error occurred while creating this '%s' object." % key) + logger.log_err(exc) + + return obj, errors + def delete(self): """ Deletes channel while also cleaning up channelhandler. diff --git a/evennia/comms/tests.py b/evennia/comms/tests.py new file mode 100644 index 0000000000..d38e34544b --- /dev/null +++ b/evennia/comms/tests.py @@ -0,0 +1,13 @@ + +from evennia.utils.test_resources import EvenniaTest +from evennia import DefaultChannel + +class ObjectCreationTest(EvenniaTest): + + def test_channel_create(self): + description = "A place to talk about coffee." + + obj, errors = DefaultChannel.create('coffeetalk', description=description) + self.assertTrue(obj, errors) + self.assertFalse(errors, errors) + self.assertEqual(description, obj.db.desc) \ No newline at end of file From c1a94d0369146607688be20cb51b67fee7093183 Mon Sep 17 00:00:00 2001 From: Johnny Date: Wed, 17 Oct 2018 21:37:49 +0000 Subject: [PATCH 19/23] Adds object auditing options to DefaultChannel. --- evennia/comms/comms.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/evennia/comms/comms.py b/evennia/comms/comms.py index adb90c66ac..90d1b04ad5 100644 --- a/evennia/comms/comms.py +++ b/evennia/comms/comms.py @@ -221,7 +221,7 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)): default=default, no_superuser_bypass=no_superuser_bypass) @classmethod - def create(cls, key, *args, **kwargs): + def create(cls, key, account=None, *args, **kwargs): """ Creates a basic Channel with default parameters, unless otherwise specified or extended. @@ -230,6 +230,7 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)): Args: key (str): This must be unique. + account (Account): Account to attribute this object to. Kwargs: aliases (list of str): List of alternative (likely shorter) keynames. @@ -238,6 +239,7 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)): keep_log (bool): Log channel throughput. typeclass (str or class): The typeclass of the Channel (not often used). + ip (str): IP address of creator (for object auditing). Returns: channel (Channel): A newly created Channel. @@ -246,10 +248,16 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)): """ errors = [] obj = None + ip = kwargs.pop('ip', '') try: kwargs['desc'] = kwargs.pop('description', '') obj = create.create_channel(key, *args, **kwargs) + + # Record creator id and creation IP + if ip: obj.db.creator_ip = ip + if account: obj.db.creator_id = account.id + except Exception as exc: errors.append("An error occurred while creating this '%s' object." % key) logger.log_err(exc) From dc299b1e7f2733791794f2a5cfbb5ba667bea739 Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 22 Oct 2018 21:57:38 +0000 Subject: [PATCH 20/23] Fixes failing tests. --- evennia/accounts/tests.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index a6f9d5bcbf..2f2d6cc7eb 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -84,16 +84,14 @@ class TestDefaultGuest(EvenniaTest): self.assertFalse(account, 'Two guest accounts were created with a single entry on the guest list!') settings.GUEST_ENABLED = False - -class TestDefaultAccount(EvenniaTest): - "Check DefaultAccount class" - + +class TestDefaultAccountAuth(EvenniaTest): + def setUp(self): - self.s1 = MagicMock() - self.s1.puppet = None - self.s1.sessid = 0 + super(TestDefaultAccountAuth, self).setUp() self.password = "testpassword" + self.account.delete() self.account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password=self.password, typeclass=DefaultAccount) def test_authentication(self): @@ -138,10 +136,6 @@ class TestDefaultAccount(EvenniaTest): result, error = DefaultAccount.validate_username('xx') self.assertFalse(result, "2-character username passed validation.") - def tearDown(self): - if hasattr(self, "account"): - self.account.delete() - def test_password_validation(self): "Check password validators deny bad passwords" @@ -167,6 +161,14 @@ class TestDefaultAccount(EvenniaTest): # Try setting a better password (test for False; returns None on success) self.assertFalse(self.account.set_password('Mxyzptlk')) +class TestDefaultAccount(TestCase): + "Check DefaultAccount class" + + def setUp(self): + self.s1 = MagicMock() + self.s1.puppet = None + self.s1.sessid = 0 + def test_puppet_object_no_object(self): "Check puppet_object method called with no object param" From 1ddb887d7ae79b2f69a2feb74b0e9f319ffc040f Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 22 Oct 2018 22:12:54 +0000 Subject: [PATCH 21/23] Fixes failed unit tests. --- evennia/accounts/tests.py | 38 +++++++++++++------------------------- 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index 81ac25c2a3..2cfd9350cb 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -6,12 +6,14 @@ from unittest import TestCase from django.test import override_settings from evennia.accounts.accounts import AccountSessionHandler - from evennia.accounts.accounts import DefaultAccount, DefaultGuest from evennia.server.session import Session +from evennia.utils.test_resources import EvenniaTest from evennia.utils import create from evennia.utils.test_resources import EvenniaTest +from django.conf import settings + class TestAccountSessionHandler(TestCase): "Check AccountSessionHandler class" @@ -134,43 +136,30 @@ class TestDefaultAccountAuth(EvenniaTest): result, error = DefaultAccount.validate_username('xx') self.assertFalse(result, "2-character username passed validation.") - def test_absolute_url(self): - "Get URL for account detail page on website" - self.account = create.create_account("TestAccount%s" % randint(100000, 999999), - email="test@test.com", password="testpassword", typeclass=DefaultAccount) - self.assertTrue(self.account.web_get_detail_url()) - - def test_admin_url(self): - "Get object's URL for access via Admin pane" - self.account = create.create_account("TestAccount%s" % randint(100000, 999999), - email="test@test.com", password="testpassword", typeclass=DefaultAccount) - self.assertTrue(self.account.web_get_admin_url()) - self.assertTrue(self.account.web_get_admin_url() != '#') - def test_password_validation(self): "Check password validators deny bad passwords" - self.account = create.create_account("TestAccount%s" % randint(100000, 999999), + account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password="testpassword", typeclass=DefaultAccount) for bad in ('', '123', 'password', 'TestAccount', '#', 'xyzzy'): - self.assertFalse(self.account.validate_password(bad, account=self.account)[0]) + self.assertFalse(account.validate_password(bad, account=self.account)[0]) "Check validators allow sufficiently complex passwords" for better in ('Mxyzptlk', "j0hn, i'M 0n1y d4nc1nG"): - self.assertTrue(self.account.validate_password(better, account=self.account)[0]) + self.assertTrue(account.validate_password(better, account=self.account)[0]) def test_password_change(self): "Check password setting and validation is working as expected" - self.account = create.create_account("TestAccount%s" % randint(0, 9), + account = create.create_account("TestAccount%s" % randint(0, 9), email="test@test.com", password="testpassword", typeclass=DefaultAccount) from django.core.exceptions import ValidationError # Try setting some bad passwords for bad in ('', '#', 'TestAccount', 'password'): - self.assertRaises(ValidationError, self.account.set_password, bad) + self.assertRaises(ValidationError, account.set_password, bad) # Try setting a better password (test for False; returns None on success) - self.assertFalse(self.account.set_password('Mxyzptlk')) + self.assertFalse(account.set_password('Mxyzptlk')) class TestDefaultAccount(TestCase): "Check DefaultAccount class" @@ -285,18 +274,17 @@ class TestDefaultAccount(TestCase): class TestAccountPuppetDeletion(EvenniaTest): - + @override_settings(MULTISESSION_MODE=2) def test_puppet_deletion(self): # Check for existing chars self.assertFalse(self.account.db._playable_characters, 'Account should not have any chars by default.') - + # Add char1 to account's playable characters self.account.db._playable_characters.append(self.char1) self.assertTrue(self.account.db._playable_characters, 'Char was not added to account.') - + # See what happens when we delete char1. self.char1.delete() # Playable char list should be empty. - self.assertFalse(self.account.db._playable_characters, - 'Playable character list is not empty! %s' % self.account.db._playable_characters) + self.assertFalse(self.account.db._playable_characters, 'Playable character list is not empty! %s' % self.account.db._playable_characters) \ No newline at end of file From 52b58dbeb23a00c1143beeae3fb895f77d1fffa7 Mon Sep 17 00:00:00 2001 From: Johnny Date: Mon, 22 Oct 2018 22:26:29 +0000 Subject: [PATCH 22/23] Fixes failed tests, hopefully for real this time. --- evennia/accounts/tests.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index 2cfd9350cb..5e8e58cf9f 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -111,8 +111,9 @@ class TestDefaultAccountAuth(EvenniaTest): self.assertTrue(account, 'New account should have been created.') # Try creating a duplicate account - account, errors = DefaultAccount.create(username='Ziggy', password='starman11') - self.assertFalse(account, 'Duplicate account name should not have been allowed.') + account2, errors = DefaultAccount.create(username='Ziggy', password='starman11') + self.assertFalse(account2, 'Duplicate account name should not have been allowed.') + account.delete() def test_throttle(self): "Confirm throttle activates on too many failures." @@ -147,10 +148,11 @@ class TestDefaultAccountAuth(EvenniaTest): "Check validators allow sufficiently complex passwords" for better in ('Mxyzptlk', "j0hn, i'M 0n1y d4nc1nG"): self.assertTrue(account.validate_password(better, account=self.account)[0]) + account.delete() def test_password_change(self): "Check password setting and validation is working as expected" - account = create.create_account("TestAccount%s" % randint(0, 9), + account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password="testpassword", typeclass=DefaultAccount) from django.core.exceptions import ValidationError @@ -160,6 +162,7 @@ class TestDefaultAccountAuth(EvenniaTest): # Try setting a better password (test for False; returns None on success) self.assertFalse(account.set_password('Mxyzptlk')) + account.delete() class TestDefaultAccount(TestCase): "Check DefaultAccount class" From c03c077d73da4901da2341c73cae72af99b0eef6 Mon Sep 17 00:00:00 2001 From: Griatch Date: Tue, 23 Oct 2018 01:04:25 +0200 Subject: [PATCH 23/23] Update CHANGELOG, pep8 fixes --- CHANGELOG.md | 26 +++- evennia/accounts/accounts.py | 160 ++++++++++++------------- evennia/accounts/tests.py | 48 ++++---- evennia/commands/default/unloggedin.py | 30 ++--- evennia/objects/objects.py | 146 +++++++++++----------- evennia/objects/tests.py | 13 +- evennia/scripts/scripts.py | 14 +-- evennia/server/throttle.py | 55 +++++---- evennia/server/validators.py | 41 ++++--- evennia/settings_default.py | 21 ++-- 10 files changed, 290 insertions(+), 264 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a31aecb97..da326f766f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,30 @@ - Add the Portal uptime to the `@time` command. - Make the `@link` command first make a local search before a global search. +### Typeclasses + +- Add new methods on all typeclasses, useful specifically for viewing the object in the web/admin: + + `web_get_admin_url()`: Returns a path that, if followed, will display the object in the Admin backend. + + `web_get_create_url()`: Returns a path for a view allowing the creation of new instances of this object. + + `web_get_absolute_url()`: Django construct; returns a path that should display the object in a DetailView. + + `web_get_update_url()`: Returns a path that should display the object in an UpdateView. + + `web_get_delete_url()`: Returns a path that should display the object in a DeleteView. +- All typeclasses has new helper class method `create`, which encompasses useful functionality + that used to be embedded for example in the respective `@create` or `@connect` commands. +- DefaultAccount now has new class methods implementing many things that used to be in unloggedin + commands (these can now be customized on the class instead): + + `is_banned()`: Checks if a given username or IP is banned. + + `get_username_validators`: Return list of validators for username validation (see + `settings.AUTH_USERNAME_VALIDATORS`) + + `authenticate`: Method to check given username/password. + + `normalize_username`: Normalizes names so you can't fake names with similar-looking Unicode + chars. + + `validate_username`: Mechanism for validating a username. + + `validate_password`: Mechanism for validating a password. + + `set_password`: Apply password to account, using validation checks. + + + ### Utils - Added more unit tests. @@ -34,7 +58,7 @@ to terminal and can be stopped with Ctrl-C. Using `evennia reload`, or reloading in-game, will return Server to normal daemon operation. - For validating passwords, use safe Django password-validation backend instead of custom Evennia one. -- Alias `evennia restart` to mean the same as `evennia reload`. +- Alias `evennia restart` to mean the same as `evennia reload`. ### Prototype changes diff --git a/evennia/accounts/accounts.py b/evennia/accounts/accounts.py index 7e1ddb80e8..3fed8dc25e 100644 --- a/evennia/accounts/accounts.py +++ b/evennia/accounts/accounts.py @@ -370,40 +370,40 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): def is_banned(cls, **kwargs): """ Checks if a given username or IP is banned. - + Kwargs: ip (str, optional): IP address. username (str, optional): Username. - + Returns: is_banned (bool): Whether either is banned or not. - + """ - + ip = kwargs.get('ip', '').strip() username = kwargs.get('username', '').lower().strip() - + # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0] == username for tup in bans if username) or any(tup[2].match(ip) for tup in bans if ip and tup[2])): return True - + return False - + @classmethod def get_username_validators(cls, validator_config=getattr(settings, 'AUTH_USERNAME_VALIDATORS', [])): """ Retrieves and instantiates validators for usernames. - + Args: validator_config (list): List of dicts comprising the battery of validators to apply to a username. - + Returns: validators (list): List of instantiated Validator objects. """ - + objs = [] for validator in validator_config: try: @@ -413,49 +413,49 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): raise ImproperlyConfigured(msg % validator['NAME']) objs.append(klass(**validator.get('OPTIONS', {}))) return objs - + @classmethod def authenticate(cls, username, password, ip='', **kwargs): """ - Checks the given username/password against the database to see if the + Checks the given username/password against the database to see if the credentials are valid. - + Note that this simply checks credentials and returns a valid reference to the user-- it does not log them in! - + To finish the job: After calling this from a Command, associate the account with a Session: - session.sessionhandler.login(session, account) - + ...or after calling this from a View, associate it with an HttpRequest: - django.contrib.auth.login(account, request) - + Args: username (str): Username of account password (str): Password of account ip (str, optional): IP address of client - + Kwargs: session (Session, optional): Session requesting authentication - + Returns: account (DefaultAccount, None): Account whose credentials were provided if not banned. errors (list): Error messages of any failures. - + """ errors = [] if ip: ip = str(ip) - + # See if authentication is currently being throttled if ip and LOGIN_THROTTLE.check(ip): errors.append('Too many login failures; please try again in a few minutes.') - + # With throttle active, do not log continued hits-- it is a # waste of storage and can be abused to make your logs harder to # read and/or fill up your disk. return None, errors - + # Check IP and/or name bans banned = cls.is_banned(username=username, ip=ip) if banned: @@ -465,19 +465,19 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): logger.log_sec('Authentication Denied (Banned): %s (IP: %s).' % (username, ip)) LOGIN_THROTTLE.update(ip, 'Too many sightings of banned artifact.') return None, errors - + # Authenticate and get Account object account = authenticate(username=username, password=password) if not account: # User-facing message errors.append('Username and/or password is incorrect.') - + # Log auth failures while throttle is inactive logger.log_sec('Authentication Failure: %s (IP: %s).' % (username, ip)) - + # Update throttle if ip: LOGIN_THROTTLE.update(ip, 'Too many authentication failures.') - + # Try to call post-failure hook session = kwargs.get('session', None) if session: @@ -486,49 +486,49 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): account.at_failed_login(session) return None, errors - + # Account successfully authenticated logger.log_sec('Authentication Success: %s (IP: %s).' % (account, ip)) return account, errors - + @classmethod def normalize_username(cls, username): """ - Django: Applies NFKC Unicode normalization to usernames so that visually - identical characters with different Unicode code points are considered + Django: Applies NFKC Unicode normalization to usernames so that visually + identical characters with different Unicode code points are considered identical. - + (This deals with the Turkish "i" problem and similar - annoyances. Only relevant if you go out of your way to allow Unicode + annoyances. Only relevant if you go out of your way to allow Unicode usernames though-- Evennia accepts ASCII by default.) - + In this case we're simply piggybacking on this feature to apply additional normalization per Evennia's standards. """ username = super(DefaultAccount, cls).normalize_username(username) - + # strip excessive spaces in accountname username = re.sub(r"\s+", " ", username).strip() - + return username - + @classmethod def validate_username(cls, username): """ Checks the given username against the username validator associated with Account objects, and also checks the database to make sure it is unique. - + Args: username (str): Username to validate - + Returns: valid (bool): Whether or not the password passed validation errors (list): Error messages of any failures - + """ valid = [] errors = [] - + # Make sure we're at least using the default validator validators = cls.get_username_validators() if not validators: @@ -541,14 +541,14 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): except ValidationError as e: valid.append(False) errors.extend(e.messages) - + # Disqualify if any check failed if False in valid: valid = False else: valid = True - + return valid, errors - + @classmethod def validate_password(cls, password, account=None): """ @@ -608,48 +608,48 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): super(DefaultAccount, self).set_password(password) logger.log_sec("Password successfully changed for %s." % self) self.at_password_change() - + @classmethod def create(cls, *args, **kwargs): """ - Creates an Account (or Account/Character pair for MULTISESSION_MODE<2) - with default (or overridden) permissions and having joined them to the + Creates an Account (or Account/Character pair for MULTISESSION_MODE<2) + with default (or overridden) permissions and having joined them to the appropriate default channels. - + Kwargs: username (str): Username of Account owner password (str): Password of Account owner email (str, optional): Email address of Account owner ip (str, optional): IP address of requesting connection guest (bool, optional): Whether or not this is to be a Guest account - + permissions (str, optional): Default permissions for the Account typeclass (str, optional): Typeclass to use for new Account character_typeclass (str, optional): Typeclass to use for new char when applicable. - + Returns: account (Account): Account if successfully created; None if not errors (list): List of error messages in string form - + """ - + account = None errors = [] - + username = kwargs.get('username') password = kwargs.get('password') email = kwargs.get('email', '').strip() guest = kwargs.get('guest', False) - + permissions = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) typeclass = kwargs.get('typeclass', settings.BASE_ACCOUNT_TYPECLASS) - + ip = kwargs.get('ip', '') if ip and CREATION_THROTTLE.check(ip): errors.append("You are creating too many accounts. Please log into an existing account.") return None, errors - + # Normalize username username = cls.normalize_username(username) @@ -678,50 +678,50 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): "\nIf you feel this ban is in error, please email an admin.|x" errors.append(string) return None, errors - + # everything's ok. Create the new account account. try: try: account = create.create_account(username, email, password, permissions=permissions, typeclass=typeclass) logger.log_sec('Account Created: %s (IP: %s).' % (account, ip)) - + except Exception as e: errors.append("There was an error creating the Account. If this problem persists, contact an admin.") logger.log_trace() return None, errors - + # This needs to be set so the engine knows this account is # logging in for the first time. (so it knows to call the right # hooks during login later) account.db.FIRST_LOGIN = True - + # Record IP address of creation, if available if ip: account.db.creator_ip = ip - + # join the new account to the public channel pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) if not pchannel or not pchannel.connect(account): string = "New account '%s' could not connect to public channel!" % account.key errors.append(string) logger.log_err(string) - + if account and settings.MULTISESSION_MODE < 2: # Load the appropriate Character class character_typeclass = kwargs.get('character_typeclass', settings.BASE_CHARACTER_TYPECLASS) character_home = kwargs.get('home') Character = class_from_module(character_typeclass) - + # Create the character character, errs = Character.create( - account.key, account, ip=ip, typeclass=character_typeclass, + account.key, account, ip=ip, typeclass=character_typeclass, permissions=permissions, home=character_home ) errors.extend(errs) - + if character: # Update playable character list account.db._playable_characters.append(character) - + # We need to set this to have @ic auto-connect to this character account.db._last_puppet = character @@ -731,7 +731,7 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)): # we won't see any errors at all. errors.append("An error occurred. Please e-mail an admin if the problem persists.") logger.log_trace() - + # Update the throttle to indicate a new account was created from this IP if ip and not guest: CREATION_THROTTLE.update(ip, 'Too many accounts being created.') return account, errors @@ -1384,7 +1384,7 @@ class DefaultGuest(DefaultAccount): This class is used for guest logins. Unlike Accounts, Guests and their characters are deleted after disconnection. """ - + @classmethod def create(cls, **kwargs): """ @@ -1392,31 +1392,31 @@ class DefaultGuest(DefaultAccount): if one is available for use. """ return cls.authenticate(**kwargs) - + @classmethod def authenticate(cls, **kwargs): """ Gets or creates a Guest account object. - + Kwargs: ip (str, optional): IP address of requestor; used for ban checking, throttling and logging - + Returns: account (Object): Guest account object, if available errors (list): List of error messages accrued during this request. - + """ errors = [] account = None username = None ip = kwargs.get('ip', '').strip() - + # check if guests are enabled. if not settings.GUEST_ENABLED: errors.append('Guest accounts are not enabled on this server.') return None, errors - + try: # Find an available guest name. for name in settings.GUEST_LIST: @@ -1433,20 +1433,20 @@ class DefaultGuest(DefaultAccount): home = settings.GUEST_HOME permissions = settings.PERMISSION_GUEST_DEFAULT typeclass = settings.BASE_GUEST_TYPECLASS - + # Call parent class creator account, errs = super(DefaultGuest, cls).create( guest=True, - username=username, - password=password, - permissions=permissions, - typeclass=typeclass, + username=username, + password=password, + permissions=permissions, + typeclass=typeclass, home=home, ip=ip, ) errors.extend(errs) return account, errors - + except Exception as e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, @@ -1454,7 +1454,7 @@ class DefaultGuest(DefaultAccount): errors.append("An error occurred. Please e-mail an admin if the problem persists.") logger.log_trace() return None, errors - + return account, errors def at_post_login(self, session=None, **kwargs): diff --git a/evennia/accounts/tests.py b/evennia/accounts/tests.py index 5e8e58cf9f..1d31e93e2c 100644 --- a/evennia/accounts/tests.py +++ b/evennia/accounts/tests.py @@ -7,10 +7,8 @@ from unittest import TestCase from django.test import override_settings from evennia.accounts.accounts import AccountSessionHandler from evennia.accounts.accounts import DefaultAccount, DefaultGuest -from evennia.server.session import Session from evennia.utils.test_resources import EvenniaTest from evennia.utils import create -from evennia.utils.test_resources import EvenniaTest from django.conf import settings @@ -61,78 +59,78 @@ class TestAccountSessionHandler(TestCase): def test_count(self): "Check count method" self.assertEqual(self.handler.count(), len(self.handler.get())) - + class TestDefaultGuest(EvenniaTest): "Check DefaultGuest class" - + ip = '212.216.134.22' - + def test_authenticate(self): # Guest account should not be permitted account, errors = DefaultGuest.authenticate(ip=self.ip) self.assertFalse(account, 'Guest account was created despite being disabled.') - + settings.GUEST_ENABLED = True settings.GUEST_LIST = ['bruce_wayne'] - + # Create a guest account account, errors = DefaultGuest.authenticate(ip=self.ip) self.assertTrue(account, 'Guest account should have been created.') - + # Create a second guest account account, errors = DefaultGuest.authenticate(ip=self.ip) self.assertFalse(account, 'Two guest accounts were created with a single entry on the guest list!') - + settings.GUEST_ENABLED = False - + class TestDefaultAccountAuth(EvenniaTest): - + def setUp(self): super(TestDefaultAccountAuth, self).setUp() - + self.password = "testpassword" self.account.delete() self.account = create.create_account("TestAccount%s" % randint(100000, 999999), email="test@test.com", password=self.password, typeclass=DefaultAccount) - + def test_authentication(self): "Confirm Account authentication method is authenticating/denying users." # Valid credentials obj, errors = DefaultAccount.authenticate(self.account.name, self.password) self.assertTrue(obj, 'Account did not authenticate given valid credentials.') - + # Invalid credentials obj, errors = DefaultAccount.authenticate(self.account.name, 'xyzzy') self.assertFalse(obj, 'Account authenticated using invalid credentials.') - + def test_create(self): "Confirm Account creation is working as expected." # Create a normal account account, errors = DefaultAccount.create(username='ziggy', password='stardust11') self.assertTrue(account, 'New account should have been created.') - + # Try creating a duplicate account account2, errors = DefaultAccount.create(username='Ziggy', password='starman11') self.assertFalse(account2, 'Duplicate account name should not have been allowed.') account.delete() - + def test_throttle(self): "Confirm throttle activates on too many failures." for x in xrange(20): obj, errors = DefaultAccount.authenticate(self.account.name, 'xyzzy', ip='12.24.36.48') self.assertFalse(obj, 'Authentication was provided a bogus password; this should NOT have returned an account!') - + self.assertTrue('too many login failures' in errors[-1].lower(), 'Failed logins should have been throttled.') - + def test_username_validation(self): "Check username validators deny relevant usernames" # Should not accept Unicode by default, lest users pick names like this result, error = DefaultAccount.validate_username('¯\_(ツ)_/¯') self.assertFalse(result, "Validator allowed kanji in username.") - + # Should not allow duplicate username result, error = DefaultAccount.validate_username(self.account.name) self.assertFalse(result, "Duplicate username should not have passed validation.") - + # Should not allow username too short result, error = DefaultAccount.validate_username('xx') self.assertFalse(result, "2-character username passed validation.") @@ -277,17 +275,17 @@ class TestDefaultAccount(TestCase): class TestAccountPuppetDeletion(EvenniaTest): - + @override_settings(MULTISESSION_MODE=2) def test_puppet_deletion(self): # Check for existing chars self.assertFalse(self.account.db._playable_characters, 'Account should not have any chars by default.') - + # Add char1 to account's playable characters self.account.db._playable_characters.append(self.char1) self.assertTrue(self.account.db._playable_characters, 'Char was not added to account.') - + # See what happens when we delete char1. self.char1.delete() # Playable char list should be empty. - self.assertFalse(self.account.db._playable_characters, 'Playable character list is not empty! %s' % self.account.db._playable_characters) \ No newline at end of file + self.assertFalse(self.account.db._playable_characters, 'Playable character list is not empty! %s' % self.account.db._playable_characters) diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index 7ff2c9a29a..607c95439b 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -2,17 +2,11 @@ Commands that are available from the connect screen. """ import re -import time import datetime from django.conf import settings -from django.contrib.auth import authenticate -from evennia.accounts.models import AccountDB -from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB -from evennia.server.models import ServerConfig from evennia.server.sessionhandler import SESSIONS -from evennia.server.throttle import Throttle from evennia.utils import class_from_module, create, logger, utils, gametime from evennia.commands.cmdhandler import CMD_LOGINSTART @@ -26,6 +20,7 @@ __all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", MULTISESSION_MODE = settings.MULTISESSION_MODE CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE + def create_guest_account(session): """ Creates a guest account/character for this session, if one is available. @@ -40,10 +35,10 @@ def create_guest_account(session): """ enabled = settings.GUEST_ENABLED address = session.address - + # Get account class Guest = class_from_module(settings.BASE_GUEST_TYPECLASS) - + # Get an available guest account # authenticate() handles its own throttling account, errors = Guest.authenticate(ip=address) @@ -53,6 +48,7 @@ def create_guest_account(session): session.msg("|R%s|n" % '\n'.join(errors)) return enabled, None + def create_normal_account(session, name, password): """ Creates an account with the given name and password. @@ -67,9 +63,9 @@ def create_normal_account(session, name, password): """ # Get account class Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) - + address = session.address - + # Match account name and check password # authenticate() handles all its own throttling account, errors = Account.authenticate(username=name, password=password, ip=address, session=session) @@ -108,19 +104,19 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): """ session = self.caller address = session.address - + args = self.args # extract double quote parts parts = [part.strip() for part in re.split(r"\"", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no double quotes being found, or a guest login parts = parts[0].split(None, 1) - + # Guest login if len(parts) == 1 and parts[0].lower() == "guest": # Get Guest typeclass Guest = class_from_module(settings.BASE_GUEST_TYPECLASS) - + account, errors = Guest.authenticate(ip=address) if account: session.sessionhandler.login(session, account) @@ -128,14 +124,14 @@ class CmdUnconnectedConnect(COMMAND_DEFAULT_CLASS): else: session.msg("|R%s|n" % '\n'.join(errors)) return - + if len(parts) != 2: session.msg("\n\r Usage (without <>): connect ") return # Get account class Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) - + name, password = parts account, errors = Account.authenticate(username=name, password=password, ip=address, session=session) if account: @@ -168,7 +164,7 @@ class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS): args = self.args.strip() address = session.address - + # Get account class Account = class_from_module(settings.BASE_ACCOUNT_TYPECLASS) @@ -182,7 +178,7 @@ class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS): "\nIf or contains spaces, enclose it in double quotes." session.msg(string) return - + username, password = parts # everything's ok. Create the new account account. diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index b829ab7165..f41dd02d02 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -195,7 +195,7 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): # lockstring of newly created objects, for easy overloading. # Will be formatted with the appropriate attributes. lockstring = "control:id({account_id}) or perm(Admin);delete:id({account_id}) or perm(Admin)" - + objects = ObjectManager() # on-object properties @@ -863,66 +863,66 @@ class DefaultObject(with_metaclass(TypeclassBase, ObjectDB)): string = "This place should not exist ... contact an admin." obj.msg(_(string)) obj.move_to(home) - + @classmethod def create(cls, key, account=None, **kwargs): """ Creates a basic object with default parameters, unless otherwise specified or extended. - + Provides a friendlier interface to the utils.create_object() function. - + Args: key (str): Name of the new object. account (Account): Account to attribute this object to. - + Kwargs: description (str): Brief description for this object. ip (str): IP address of creator (for object auditing). - + Returns: object (Object): A newly created object of the given typeclass. errors (list): A list of errors in string form, if any. - + """ errors = [] obj = None - + # Get IP address of creator, if available ip = kwargs.pop('ip', '') - + # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) - + # Set the supplied key as the name of the intended object kwargs['key'] = key - + # Get a supplied description, if any description = kwargs.pop('description', '') - + # Create a sane lockstring if one wasn't supplied lockstring = kwargs.get('locks') if account and not lockstring: lockstring = cls.lockstring.format(account_id=account.id) kwargs['locks'] = lockstring - + # Create object try: obj = create.create_object(**kwargs) - + # Record creator id and creation IP if ip: obj.db.creator_ip = ip if account: obj.db.creator_id = account.id - + # Set description if there is none, or update it if provided if description or not obj.db.desc: desc = description if description else "You see nothing special." obj.db.desc = desc - + except Exception as e: errors.append("An error occurred while creating this '%s' object." % key) logger.log_err(e) - + return obj, errors def copy(self, new_key=None): @@ -1895,81 +1895,81 @@ class DefaultCharacter(DefaultObject): # lockstring of newly created rooms, for easy overloading. # Will be formatted with the appropriate attributes. lockstring = "puppet:id({character_id}) or pid({account_id}) or perm(Developer) or pperm(Developer)" - + @classmethod def create(cls, key, account, **kwargs): """ Creates a basic Character with default parameters, unless otherwise specified or extended. - + Provides a friendlier interface to the utils.create_character() function. - + Args: key (str): Name of the new Character. account (obj): Account to associate this Character with. Required as an argument, but one can fake it out by supplying None-- it will change the default lockset and skip creator attribution. - + Kwargs: description (str): Brief description for this object. ip (str): IP address of creator (for object auditing). - + Returns: character (Object): A newly created Character of the given typeclass. errors (list): A list of errors in string form, if any. - + """ errors = [] obj = None - + # Get IP address of creator, if available ip = kwargs.pop('ip', '') - + # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) - + # Set the supplied key as the name of the intended object kwargs['key'] = key - + # Get home for character kwargs['home'] = ObjectDB.objects.get_id(kwargs.get('home', settings.DEFAULT_HOME)) - + # Get permissions kwargs['permissions'] = kwargs.get('permissions', settings.PERMISSION_ACCOUNT_DEFAULT) - + # Get description if provided description = kwargs.pop('description', '') - + # Get locks if provided locks = kwargs.pop('locks', '') - + try: # Create the Character obj = create.create_object(**kwargs) - + # Record creator id and creation IP if ip: obj.db.creator_ip = ip if account: obj.db.creator_id = account.id - + # Add locks if not locks and account: # Allow only the character itself and the creator account to puppet this character (and Developers). locks = cls.lockstring.format(**{'character_id': obj.id, 'account_id': account.id}) elif not locks and not account: locks = cls.lockstring.format(**{'character_id': obj.id, 'account_id': -1}) - + obj.locks.add(locks) # If no description is set, set a default description if description or not obj.db.desc: obj.db.desc = description if description else "This is a character." - + except Exception as e: errors.append("An error occurred while creating this '%s' object." % key) logger.log_err(e) - + return obj, errors - + def basetype_setup(self): """ Setup character-specific security. @@ -2097,60 +2097,60 @@ class DefaultRoom(DefaultObject): """ Creates a basic Room with default parameters, unless otherwise specified or extended. - + Provides a friendlier interface to the utils.create_object() function. - + Args: key (str): Name of the new Room. account (obj): Account to associate this Room with. - + Kwargs: description (str): Brief description for this object. ip (str): IP address of creator (for object auditing). - + Returns: room (Object): A newly created Room of the given typeclass. errors (list): A list of errors in string form, if any. - + """ errors = [] obj = None - + # Get IP address of creator, if available ip = kwargs.pop('ip', '') - + # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) - + # Set the supplied key as the name of the intended object kwargs['key'] = key - + # Get who to send errors to kwargs['report_to'] = kwargs.pop('report_to', account) - + # Get description, if provided description = kwargs.pop('description', '') - + try: # Create the Room obj = create.create_object(**kwargs) - + # Set appropriate locks lockstring = kwargs.get('locks', cls.lockstring.format(id=account.id)) obj.locks.add(lockstring) - + # Record creator id and creation IP if ip: obj.db.creator_ip = ip if account: obj.db.creator_id = account.id - + # If no description is set, set a default description if description or not obj.db.desc: obj.db.desc = description if description else "This is a room." - + except Exception as e: errors.append("An error occurred while creating this '%s' object." % key) logger.log_err(e) - + return obj, errors def basetype_setup(self): @@ -2230,13 +2230,13 @@ class DefaultExit(DefaultObject): exit_command = ExitCommand priority = 101 - + # lockstring of newly created exits, for easy overloading. # Will be formatted with the {id} of the creating object. lockstring = "control:id({id}) or perm(Admin); " \ "delete:id({id}) or perm(Admin); " \ "edit:id({id}) or perm(Admin)" - + # Helper classes and methods to implement the Exit. These need not # be overloaded unless one want to change the foundation for how # Exits work. See the end of the class for hook methods to overload. @@ -2274,72 +2274,72 @@ class DefaultExit(DefaultObject): return exit_cmdset # Command hooks - + @classmethod def create(cls, key, account, source, dest, **kwargs): """ Creates a basic Exit with default parameters, unless otherwise specified or extended. - + Provides a friendlier interface to the utils.create_object() function. - + Args: key (str): Name of the new Exit, as it should appear from the source room. account (obj): Account to associate this Exit with. source (Room): The room to create this exit in. dest (Room): The room to which this exit should go. - + Kwargs: description (str): Brief description for this object. ip (str): IP address of creator (for object auditing). - + Returns: exit (Object): A newly created Room of the given typeclass. errors (list): A list of errors in string form, if any. - + """ errors = [] obj = None - + # Get IP address of creator, if available ip = kwargs.pop('ip', '') - + # If no typeclass supplied, use this class kwargs['typeclass'] = kwargs.pop('typeclass', cls) - + # Set the supplied key as the name of the intended object kwargs['key'] = key - + # Get who to send errors to kwargs['report_to'] = kwargs.pop('report_to', account) - + # Set to/from rooms kwargs['location'] = source kwargs['destination'] = dest - + description = kwargs.pop('description', '') - + try: # Create the Exit obj = create.create_object(**kwargs) - + # Set appropriate locks lockstring = kwargs.get('locks', cls.lockstring.format(id=account.id)) obj.locks.add(lockstring) - + # Record creator id and creation IP if ip: obj.db.creator_ip = ip if account: obj.db.creator_id = account.id - + # If no description is set, set a default description if description or not obj.db.desc: obj.db.desc = description if description else "This is an exit." - + except Exception as e: errors.append("An error occurred while creating this '%s' object." % key) logger.log_err(e) - + return obj, errors def basetype_setup(self): diff --git a/evennia/objects/tests.py b/evennia/objects/tests.py index cb999bc616..6bfe34248f 100644 --- a/evennia/objects/tests.py +++ b/evennia/objects/tests.py @@ -1,10 +1,11 @@ from evennia.utils.test_resources import EvenniaTest from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit + class DefaultObjectTest(EvenniaTest): - + ip = '212.216.139.14' - + def test_object_create(self): description = 'A home for a grouch.' obj, errors = DefaultObject.create('trashcan', self.account, description=description, ip=self.ip) @@ -12,7 +13,7 @@ class DefaultObjectTest(EvenniaTest): self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) - + def test_character_create(self): description = 'A furry green monster, reeking of garbage.' obj, errors = DefaultCharacter.create('oscar', self.account, description=description, ip=self.ip) @@ -20,7 +21,7 @@ class DefaultObjectTest(EvenniaTest): self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) - + def test_room_create(self): description = 'A dimly-lit alley behind the local Chinese restaurant.' obj, errors = DefaultRoom.create('alley', self.account, description=description, ip=self.ip) @@ -28,7 +29,7 @@ class DefaultObjectTest(EvenniaTest): self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) - + def test_exit_create(self): description = 'The steaming depths of the dumpster, ripe with refuse in various states of decomposition.' obj, errors = DefaultExit.create('in', self.account, self.room1, self.room2, description=description, ip=self.ip) @@ -43,4 +44,4 @@ class DefaultObjectTest(EvenniaTest): self.assertTrue('admin' in self.char1.web_get_admin_url()) self.assertTrue(self.room1.get_absolute_url()) - self.assertTrue('admin' in self.room1.web_get_admin_url()) \ No newline at end of file + self.assertTrue('admin' in self.room1.web_get_admin_url()) diff --git a/evennia/scripts/scripts.py b/evennia/scripts/scripts.py index ba6f7edff2..e611ede0e2 100644 --- a/evennia/scripts/scripts.py +++ b/evennia/scripts/scripts.py @@ -323,31 +323,31 @@ class DefaultScript(ScriptBase): or describe a state that changes under certain conditions. """ - + @classmethod def create(cls, key, **kwargs): """ Provides a passthrough interface to the utils.create_script() function. - + Args: key (str): Name of the new object. - + Returns: object (Object): A newly created object of the given typeclass. errors (list): A list of errors in string form, if any. - + """ errors = [] obj = None - + kwargs['key'] = key - + try: obj = create.create_script(**kwargs) except Exception as e: errors.append("The script '%s' encountered errors and could not be created." % key) logger.log_err(e) - + return obj, errors def at_script_creation(self): diff --git a/evennia/server/throttle.py b/evennia/server/throttle.py index 944b7f880e..a1e6092844 100644 --- a/evennia/server/throttle.py +++ b/evennia/server/throttle.py @@ -2,25 +2,26 @@ from collections import defaultdict, deque from evennia.utils import logger import time + class Throttle(object): """ - Keeps a running count of failed actions per IP address. - + Keeps a running count of failed actions per IP address. + Available methods indicate whether or not the number of failures exceeds a particular threshold. - + This version of the throttle is usable by both the terminal server as well as the web server, imposes limits on memory consumption by using deques with length limits instead of open-ended lists, and removes sparse keys when no recent failures have been recorded. """ - + error_msg = 'Too many failed attempts; you must wait a few minutes before trying again.' - + def __init__(self, **kwargs): """ Allows setting of throttle parameters. - + Kwargs: limit (int): Max number of failures before imposing limiter timeout (int): number of timeout seconds after @@ -32,67 +33,67 @@ class Throttle(object): self.storage = defaultdict(deque) self.cache_size = self.limit = kwargs.get('limit', 5) self.timeout = kwargs.get('timeout', 5 * 60) - + def get(self, ip=None): """ Convenience function that returns the storage table, or part of. - + Args: ip (str, optional): IP address of requestor - + Returns: - storage (dict): When no IP is provided, returns a dict of all - current IPs being tracked and the timestamps of their recent + storage (dict): When no IP is provided, returns a dict of all + current IPs being tracked and the timestamps of their recent failures. - timestamps (deque): When an IP is provided, returns a deque of + timestamps (deque): When an IP is provided, returns a deque of timestamps of recent failures only for that IP. - + """ if ip: return self.storage.get(ip, deque(maxlen=self.cache_size)) else: return self.storage - + def update(self, ip, failmsg='Exceeded threshold.'): """ Store the time of the latest failure. - + Args: ip (str): IP address of requestor failmsg (str, optional): Message to display in logs upon activation of throttle. - + Returns: None - + """ # Get current status previously_throttled = self.check(ip) - + # Enforce length limits if not self.storage[ip].maxlen: self.storage[ip] = deque(maxlen=self.cache_size) - + self.storage[ip].append(time.time()) - + # See if this update caused a change in status currently_throttled = self.check(ip) - + # If this makes it engage, log a single activation event if (not previously_throttled and currently_throttled): logger.log_sec('Throttle Activated: %s (IP: %s, %i hits in %i seconds.)' % (failmsg, ip, self.limit, self.timeout)) - + def check(self, ip): """ This will check the session's address against the - storage dictionary to check they haven't spammed too many + storage dictionary to check they haven't spammed too many fails recently. - + Args: ip (str): IP address of requestor - + Returns: throttled (bool): True if throttling is active, False otherwise. - + """ now = time.time() ip = str(ip) @@ -110,5 +111,3 @@ class Throttle(object): return False else: return False - - \ No newline at end of file diff --git a/evennia/server/validators.py b/evennia/server/validators.py index fdadeda6e3..faa1aa68c8 100644 --- a/evennia/server/validators.py +++ b/evennia/server/validators.py @@ -4,31 +4,32 @@ from django.utils.translation import gettext as _ from evennia.accounts.models import AccountDB import re + class EvenniaUsernameAvailabilityValidator: """ Checks to make sure a given username is not taken or otherwise reserved. """ - + def __call__(self, username): """ Validates a username to make sure it is not in use or reserved. - + Args: username (str): Username to validate - + Returns: None (None): None if password successfully validated, raises ValidationError otherwise. - + """ - + # Check guest list if (settings.GUEST_LIST and username.lower() in (guest.lower() for guest in settings.GUEST_LIST)): raise ValidationError( _('Sorry, that username is reserved.'), code='evennia_username_reserved', ) - + # Check database exists = AccountDB.objects.filter(username__iexact=username).exists() if exists: @@ -37,33 +38,36 @@ class EvenniaUsernameAvailabilityValidator: code='evennia_username_taken', ) + class EvenniaPasswordValidator: - - def __init__(self, regex=r"^[\w. @+\-',]+$", policy="Password should contain a mix of letters, spaces, digits and @/./+/-/_/'/, only."): + + def __init__(self, regex=r"^[\w. @+\-',]+$", + policy="Password should contain a mix of letters, " + "spaces, digits and @/./+/-/_/'/, only."): """ Constructs a standard Django password validator. - + Args: regex (str): Regex pattern of valid characters to allow. policy (str): Brief explanation of what the defined regex permits. - + """ self.regex = regex self.policy = policy - + def validate(self, password, user=None): """ Validates a password string to make sure it meets predefined Evennia acceptable character policy. - + Args: password (str): Password to validate user (None): Unused argument but required by Django - + Returns: None (None): None if password successfully validated, raises ValidationError otherwise. - + """ # Check complexity if not re.findall(self.regex, password): @@ -76,11 +80,12 @@ class EvenniaPasswordValidator: """ Returns a user-facing explanation of the password policy defined by this validator. - + Returns: text (str): Explanation of password policy. - + """ return _( - "%s From a terminal client, you can also use a phrase of multiple words if you enclose the password in double quotes." % self.policy - ) \ No newline at end of file + "%s From a terminal client, you can also use a phrase of multiple words if " + "you enclose the password in double quotes." % self.policy + ) diff --git a/evennia/settings_default.py b/evennia/settings_default.py index 7926ed276c..40c36e6f7e 100644 --- a/evennia/settings_default.py +++ b/evennia/settings_default.py @@ -222,7 +222,8 @@ COMMAND_RATE_WARNING = "You entered commands too fast. Wait a moment and try aga # 0 or less. MAX_CHAR_LIMIT = 6000 # The warning to echo back to users if they enter a very large string -MAX_CHAR_LIMIT_WARNING = "You entered a string that was too long. Please break it up into multiple parts." +MAX_CHAR_LIMIT_WARNING = ("You entered a string that was too long. " + "Please break it up into multiple parts.") # If this is true, errors and tracebacks from the engine will be # echoed as text in-game as well as to the log. This can speed up # debugging. OBS: Showing full tracebacks to regular users could be a @@ -410,12 +411,14 @@ CMDSET_CHARACTER = "commands.default_cmdsets.CharacterCmdSet" CMDSET_ACCOUNT = "commands.default_cmdsets.AccountCmdSet" # Location to search for cmdsets if full path not given CMDSET_PATHS = ["commands", "evennia", "contribs"] -# Fallbacks for cmdset paths that fail to load. Note that if you change the path for your default cmdsets, -# you will also need to copy CMDSET_FALLBACKS after your change in your settings file for it to detect the change. -CMDSET_FALLBACKS = {CMDSET_CHARACTER: 'evennia.commands.default.cmdset_character.CharacterCmdSet', - CMDSET_ACCOUNT: 'evennia.commands.default.cmdset_account.AccountCmdSet', - CMDSET_SESSION: 'evennia.commands.default.cmdset_session.SessionCmdSet', - CMDSET_UNLOGGEDIN: 'evennia.commands.default.cmdset_unloggedin.UnloggedinCmdSet'} +# Fallbacks for cmdset paths that fail to load. Note that if you change the path for your +# default cmdsets, you will also need to copy CMDSET_FALLBACKS after your change in your +# settings file for it to detect the change. +CMDSET_FALLBACKS = { + CMDSET_CHARACTER: 'evennia.commands.default.cmdset_character.CharacterCmdSet', + CMDSET_ACCOUNT: 'evennia.commands.default.cmdset_account.AccountCmdSet', + CMDSET_SESSION: 'evennia.commands.default.cmdset_session.SessionCmdSet', + CMDSET_UNLOGGEDIN: 'evennia.commands.default.cmdset_unloggedin.UnloggedinCmdSet'} # Parent class for all default commands. Changing this class will # modify all default commands, so do so carefully. COMMAND_DEFAULT_CLASS = "evennia.commands.default.muxcommand.MuxCommand" @@ -810,7 +813,7 @@ AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, {'NAME': 'evennia.server.validators.EvenniaPasswordValidator'}] - + # Username validation plugins AUTH_USERNAME_VALIDATORS = [ {'NAME': 'django.contrib.auth.validators.ASCIIUsernameValidator'}, @@ -830,7 +833,7 @@ TEST_RUNNER = 'evennia.server.tests.EvenniaTestSuiteRunner' # Django extesions are useful third-party tools that are not # always included in the default django distro. try: - import django_extensions + import django_extensions # noqa INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) except ImportError: # Django extensions are not installed in all distros.