def func(self): foobar = create.create_player("TestPlayer4", email="*****@*****.**", password="******", typeclass=settings.BASE_PLAYER_TYPECLASS) foobar.db.FIRST_LOGIN = True self.msg("%s" % foobar) unloggedin._create_character(self, foobar, settings.BASE_CHARACTER_TYPECLASS, settings.DEFAULT_HOME, settings.PERMISSION_PLAYER_DEFAULT)
def create_password(caller, string_input): """Ask the user to create a password. This node is at the end of the menu for account creation. If a proper MULTI_SESSION is configured, a character is also created with the same name (we try to login into it). """ menutree = caller.ndb._menutree text = "" options = ( {"key": "", "exec": lambda caller: caller.msg("", options={"echo": True}), "goto": "start"}, {"key": "_default", "goto": "create_password"}) password = string_input.strip() accountname = menutree.accountname if len(password) < LEN_PASSWD: # The password is too short text = dedent(""" |rYour password must be at least {} characters long.|n Enter another password or leave it empty to go back. """.strip("\n")).format(LEN_PASSWD) else: # Everything's OK. Create the new player account and # possibly the character, depending on the multisession mode from evennia.commands.default import unloggedin # We make use of the helper functions from the default set here. try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = unloggedin._create_account(caller, accountname, password, permissions) if new_account: if settings.MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id( settings.DEFAULT_HOME) unloggedin._create_character(caller, new_account, typeclass, default_home, permissions) 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. caller.msg(dedent(""" |rAn error occurred.|n Please e-mail an admin if the problem persists. Try another password or leave it empty to go back to the login screen. """.strip("\n"))) logger.log_trace() else: text = "" caller.msg("|gWelcome, your new account has been created!|n") caller.msg("", options={"echo": True}) caller.sessionhandler.login(caller, new_account) return text, options
def func(self): "Execute the command" password = self.args self.caller.msg(echo=False) if not hasattr(self.menutree, 'playername'): self.caller.msg( "{rSomething went wrong! Playername not remembered from previous step!{n" ) self.menutree.goto("node2a") return playername = self.menutree.playername if len(password) < 3: # too short password string = "{rYour password must be at least 3 characters or longer." string += "\n\rFor best security, make it at least 8 characters " string += "long, avoid making it a real word and mix numbers " string += "into it.{n" self.caller.msg(string) self.menutree.goto("node2b") return # everything's ok. Create the new player account and possibly the character # depending on the multisession mode from evennia.commands.default import unloggedin # we make use of the helper functions from the default set here. try: permissions = settings.PERMISSION_PLAYER_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_player = unloggedin._create_player(self.caller, playername, password, permissions) if new_player: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id( settings.DEFAULT_HOME) unloggedin._create_character(self.caller, new_player, typeclass, default_home, permissions) # tell the caller everything went well. string = "{gA new account '%s' was created. Now go log in from the menu!{n" self.caller.msg(string % (playername)) self.menutree.goto("START") 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. self.caller.msg( "An error occurred. Please e-mail an admin if the problem persists." ) logger.log_trace()
def func(self): "Execute the command" password = self.args self.caller.msg(echo=False) if not hasattr(self.menutree, 'playername'): self.caller.msg("{rSomething went wrong! Playername not remembered from previous step!{n") self.menutree.goto("node2a") return playername = self.menutree.playername if len(password) < 3: # too short password string = "{rYour password must be at least 3 characters or longer." string += "\n\rFor best security, make it at least 8 characters " string += "long, avoid making it a real word and mix numbers " string += "into it.{n" self.caller.msg(string) self.menutree.goto("node2b") return # everything's ok. Create the new player account and possibly the character # depending on the multisession mode from evennia.commands.default import unloggedin # we make use of the helper functions from the default set here. try: permissions = settings.PERMISSION_PLAYER_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_player = unloggedin._create_player(self.caller, playername, password, permissions) if new_player: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) unloggedin._create_character(self.caller, new_player, typeclass, default_home, permissions) # tell the caller everything went well. string = "{gA new account '%s' was created. Now go log in from the menu!{n" self.caller.msg(string % (playername)) self.menutree.goto("START") 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. string = "%s\nThis is a bug. Please e-mail an admin if the problem persists." self.caller.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc())
def create_password(caller, string_input): """Ask the user to create a password. This node is at the end of the menu for account creation. If a proper MULTI_SESSION is configured, a character is also created with the same name (we try to login into it). """ menutree = caller.ndb._menutree text = "" options = ({ "key": "", "exec": lambda caller: caller.msg("", options={"echo": True}), "goto": "start" }, { "key": "_default", "goto": "create_password" }) password = string_input.strip() accountname = menutree.accountname if len(password) < LEN_PASSWD: # The password is too short text = dedent(""" |rYour password must be at least {} characters long.|n Enter another password or leave it empty to go back. """.strip("\n")).format(LEN_PASSWD) else: # Everything's OK. Create the new player account and # possibly the character, depending on the multisession mode from evennia.commands.default import unloggedin # We make use of the helper functions from the default set here. try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = unloggedin._create_account(caller, accountname, password, permissions) if new_account: if settings.MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id( settings.DEFAULT_HOME) unloggedin._create_character(caller, new_account, typeclass, default_home, permissions) 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. caller.msg( dedent(""" |rAn error occurred.|n Please e-mail an admin if the problem persists. Try another password or leave it empty to go back to the login screen. """.strip("\n"))) logger.log_trace() else: text = "" caller.msg("|gWelcome, your new account has been created!|n") caller.msg("", options={"echo": True}) caller.sessionhandler.login(caller, new_account) return text, options
def creating(request): user = request.user #foobar = create.create_player("TestPlayer42", email="*****@*****.**", password="******", typeclass=settings.BASE_PLAYER_TYPECLASS) #foobar.db.FIRST_LOGIN = True #unloggedin._create_character(self, foobar, settings.BASE_CHARACTER_TYPECLASS, settings.DEFAULT_HOME, settings.PERMISSION_PLAYER_DEFAULT) if request.method == 'POST': myform = request.POST test = myform['validation'] if test.lower() != "june": return HttpResponseRedirect('/chargen') fields = myform['name'] pwd = myform['password'] circuit = create.create_player(fields, email="*****@*****.**", password=pwd, typeclass=settings.BASE_PLAYER_TYPECLASS) unloggedin._create_character(user, circuit, settings.BASE_CHARACTER_TYPECLASS, settings.DEFAULT_HOME, settings.PERMISSION_PLAYER_DEFAULT) newchar = circuit.db._last_puppet newchar.db.tradition = myform['tradition'] newchar.db.desc = myform['description'] newchar.db.image = myform['image'] newchar.db.essence = myform['testinput'] newchar.db.concept = myform['concept'] newchar.db.strength = trans(myform['Strength']) newchar.db.dexterity = trans(myform['Dexterity']) newchar.db.stamina = trans(myform['Stamina']) newchar.db.charisma = trans(myform['Charisma']) newchar.db.manipulation = trans(myform['Manipulation']) newchar.db.appearance = trans(myform['Appearance']) newchar.db.perception = trans(myform['Perception']) newchar.db.intelligence = trans(myform['Intelligence']) newchar.db.wits = trans(myform['Wits']) newchar.db.alertness = trans(myform['testA'])-1 newchar.db.athletics = trans(myform['testA1'])-1 newchar.db.awareness = trans(myform['testA2'])-1 newchar.db.brawl = trans(myform['testA3'])-1 newchar.db.intimidation = trans(myform['testA4'])-1 newchar.db.firearms = trans(myform['testB1'])-1 newchar.db.martialarts = trans(myform['testB2'])-1 newchar.db.melee = trans(myform['testB3'])-1 newchar.db.meditation = trans(myform['testB4'])-1 newchar.db.stealth = trans(myform['testB5'])-1 newchar.db.computer = trans(myform['testC1'])-1 newchar.db.medicine = trans(myform['testC3'])-1 newchar.db.occult = trans(myform['testC4'])-1 newchar.db.rituals = trans(myform['testC5'])-1 newchar.db.melee = trans(myform['testB3'])-1 newchar.db.meditation = trans(myform['testB4'])-1 newchar.db.stealth = trans(myform['testB5'])-1 newchar.db.astrology = trans(myform['testC'])-1 newchar.db.computer = trans(myform['testC1'])-1 newchar.db.medicine = trans(myform['testC3'])-1 newchar.db.occult = trans(myform['testC4'])-1 newchar.db.rituals = trans(myform['testC5'])-1 newchar.db.correspondence = trans(myform["Correspondence"])-1 newchar.db.entropy = trans(myform["Entropy"])-1 newchar.db.life = trans(myform["Life"])-1 newchar.db.forces = trans(myform["Forces"])-1 newchar.db.matter = trans(myform["Matter"])-1 newchar.db.mind = trans(myform["Mind"])-1 newchar.db.prime = trans(myform["Prime"])-1 newchar.db.spirit = trans(myform["Spirit"])-1 newchar.db.time = trans(myform["Time"])-1 newchar.db.quintessence = trans(myform["Quintessence"])-1 newchar.db.arete = trans(myform["Arete"])-1 newchar.db.willpower = trans(myform["Willpower"])-1 newchar.db.arcane = trans(myform["Arcane"])-1 newchar.db.belief = trans(myform["Belief"])-1 newchar.db.luck = trans(myform["Luck"])-1 newchar.db.avatar = trans(myform["Avatar"])-1 newchar.db.familiar = trans(myform["Familiar"])-1 newchar.db.resources = trans(myform["Resources"])-1 urlz = '/character/sheet/' nchr = str(newchar.id); urlz = urlz + nchr + '/' return redirect(urlz)
def func(self): """Do checks and create account""" session = self.caller try: accountname, email, password = self.accountinfo except ValueError: string = "\n\r Usage (without <>): create \"<accountname>\" <email> <password>" session.msg(string) return if not email or not password: session.msg("\n\r You have to supply an e-mail address followed by a password.") return if not utils.validate_email_address(email): # check so the email at least looks ok. session.msg("'%s' is not a valid e-mail address." % email) return # 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 if AccountDB.objects.get_account_from_email(email): # email already set on an account session.msg("Sorry, there is already an account with that email address.") 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 if not re.findall(r"^[\w. @+\-']+$", password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characers. Letters, spaces, digits and @/./+/-/_/' only." \ "\nFor best security, make it longer than 8 characters. You can also use a phrase of" \ "\nmany words if you enclose the password in double quotes." 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 # everything's ok. Create the new player account. try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = default_unloggedin._create_account(session, accountname, password, permissions, email=email) if new_account: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) default_unloggedin._create_character(session, new_account, typeclass, default_home, permissions) # 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\" <your password>'." else: string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (accountname, email)) 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
def create_password(caller, string_input): """Ask the user to create a password. This node is at the end of the menu for account creation. If a proper MULTI_SESSION is configured, a character is also created with the same name (we try to login into it). """ menutree = caller.ndb._menutree text = "" options = ( { "key": "r", "exec": lambda caller: caller.msg("", options={"echo": True}), "goto": "start", }, { "key": "_default", "goto": "create_password", }, ) password = string_input.strip() accountname = menutree.accountname if len(password) < LEN_PASSWD: # The password is too short text = dedent(""" |rLe mot de passe doit comporter au moins {} caractères.|n Entrez un nouveau mot de passe ou entrez |yr|n pour revenir à l'écran d'accueil. """.strip("\n")).format(LEN_PASSWD) else: from evennia.commands.default import unloggedin try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = unloggedin._create_account(caller, accountname, password, permissions) if new_account: new_account.email = "" new_account.save() if settings.MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id( settings.DEFAULT_HOME) unloggedin._create_character(caller, new_account, typeclass, default_home, permissions) 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. caller.msg( dedent(""" |rUne erreur inattendue s'est produite..|n S'il vous plaît, envoyez un e-mail à [email protected] pour signaler ce problème. """.strip("\n"))) logger.log_trace() else: menutree.account = new_account caller.msg("", options={"echo": True}) text = dedent(""" Le nouvel utilisateur a bien été créé. Pour l'utiliser, il vous faut préciser une adresse e-mail valide. Un code de validation vous sera envoyé par e-mail. Vous devrez entrer ce code de validation dans votre client pour utiliser ce compte. Veuillez entrer une adresse e-mail valide : """).strip() options = ({ "key": "_default", "goto": "create_email_address", }, ) return text, options
def creating(request): user = request.user #foobar = create.create_player("TestPlayer42", email="*****@*****.**", password="******", typeclass=settings.BASE_PLAYER_TYPECLASS) #foobar.db.FIRST_LOGIN = True #unloggedin._create_character(self, foobar, settings.BASE_CHARACTER_TYPECLASS, settings.DEFAULT_HOME, settings.PERMISSION_PLAYER_DEFAULT) if request.method == 'POST': myform = request.POST print(request.POST) print(myform) fields = myform['name'] pwd = myform['password'] circuit = create.create_player( fields, email="*****@*****.**", password=pwd, typeclass=settings.BASE_PLAYER_TYPECLASS) unloggedin._create_character(user, circuit, settings.BASE_CHARACTER_TYPECLASS, settings.DEFAULT_HOME, settings.PERMISSION_PLAYER_DEFAULT) newchar = circuit.db._last_puppet newchar.db.tradition = myform['tradition'] newchar.db.desc = myform['description'] newchar.db.image = myform['image'] newchar.db.essence = myform['testinput'] newchar.db.concept = myform['concept'] newchar.db.strength = trans(myform['Strength']) newchar.db.dexterity = trans(myform['Dexterity']) newchar.db.stamina = trans(myform['Stamina']) newchar.db.charisma = trans(myform['Charisma']) newchar.db.manipulation = trans(myform['Manipulation']) newchar.db.appearance = trans(myform['Appearance']) newchar.db.perception = trans(myform['Perception']) newchar.db.intelligence = trans(myform['Intelligence']) newchar.db.wits = trans(myform['Wits']) newchar.db.alertness = trans(myform['testA']) - 1 newchar.db.athletics = trans(myform['testA1']) - 1 newchar.db.awareness = trans(myform['testA2']) - 1 newchar.db.brawl = trans(myform['testA3']) - 1 newchar.db.intimidation = trans(myform['testA4']) - 1 newchar.db.streetwise = trans(myform['testA5']) - 1 newchar.db.drive = trans(myform['testB']) - 1 newchar.db.firearms = trans(myform['testB1']) - 1 newchar.db.martialarts = trans(myform['testB2']) - 1 newchar.db.melee = trans(myform['testB3']) - 1 newchar.db.meditation = trans(myform['testB4']) - 1 newchar.db.stealth = trans(myform['testB5']) - 1 newchar.db.astrology = trans(myform['testC']) - 1 newchar.db.computer = trans(myform['testC1']) - 1 newchar.db.language = trans(myform['testC2']) - 1 newchar.db.medicine = trans(myform['testC3']) - 1 newchar.db.occult = trans(myform['testC4']) - 1 newchar.db.rituals = trans(myform['testC5']) - 1 newchar.db.melee = trans(myform['testB3']) - 1 newchar.db.meditation = trans(myform['testB4']) - 1 newchar.db.stealth = trans(myform['testB5']) - 1 newchar.db.astrology = trans(myform['testC']) - 1 newchar.db.computer = trans(myform['testC1']) - 1 newchar.db.language = trans(myform['testC2']) - 1 newchar.db.medicine = trans(myform['testC3']) - 1 newchar.db.occult = trans(myform['testC4']) - 1 newchar.db.rituals = trans(myform['testC5']) - 1 newchar.db.correspondence = trans(myform["Correspondence"]) - 1 newchar.db.entropy = trans(myform["Entropy"]) - 1 newchar.db.life = trans(myform["Life"]) - 1 newchar.db.forces = trans(myform["Forces"]) - 1 newchar.db.matter = trans(myform["Matter"]) - 1 newchar.db.mind = trans(myform["Mind"]) - 1 newchar.db.prime = trans(myform["Prime"]) - 1 newchar.db.spirit = trans(myform["Spirit"]) - 1 newchar.db.time = trans(myform["Time"]) - 1 newchar.db.quintessence = trans(myform["Quintessence"]) - 1 newchar.db.arete = trans(myform["Arete"]) - 1 newchar.db.willpower = trans(myform["Willpower"]) - 1 newchar.db.arcane = trans(myform["Arcane"]) - 1 newchar.db.belief = trans(myform["Belief"]) - 1 newchar.db.luck = trans(myform["Luck"]) - 1 newchar.db.avatar = trans(myform["Avatar"]) - 1 newchar.db.familiar = trans(myform["Familiar"]) - 1 newchar.db.resources = trans(myform["Resources"]) - 1 urlz = '/character/sheet/' nchr = str(newchar.id) urlz = urlz + nchr + '/' return redirect(urlz)
def func(self): """Do checks and create account""" session = self.caller try: accountname, email, password = self.accountinfo except ValueError: string = "\n\r Usage (without <>): create \"<accountname>\" <email> <password>" session.msg(string) return if not email or not password: session.msg("\n\r You have to supply an e-mail address followed by a password.") return if not utils.validate_email_address(email): # check so the email at least looks ok. session.msg("'%s' is not a valid e-mail address." % email) return # 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 if AccountDB.objects.get_account_from_email(email): # email already set on an account session.msg("Sorry, there is already an account with that email address.") 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 if not re.findall(r"^[\w. @+\-']+$", password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characters. Letters, spaces, digits and @/./+/-/_/' only." \ "\nFor best security, make it longer than 8 characters. You can also use a phrase of" \ "\nmany words if you enclose the password in double quotes." 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 # everything's ok. Create the new player account. try: permissions = settings.PERMISSION_ACCOUNT_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_account = default_unloggedin._create_account(session, accountname, password, permissions, email=email) if new_account: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) default_unloggedin._create_character(session, new_account, typeclass, default_home, permissions) # 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\" <your password>'." else: string += "\n\nYou can now log with the command 'connect %s <your password>'." session.msg(string % (accountname, email)) 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
def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller # check for too many login errors too quick. if _throttle(session, maxlim=5, timeout=5 * 60, storage=_LATEST_FAILED_LOGINS): # timeout is 5 minutes. session.msg( "{RВы совершаете слишклм много подключений. Подождите пару минут и попробуйте снова.{n" ) return args = self.args # extract quoted parts parts = [ part.strip() for part in re.split(r"\"|\'", args) if part.strip() ] if len(parts) == 1: # this was (hopefully) due to no quotes being found, or a guest login parts = parts[0].split(None, 1) # Guest login if len(parts) == 1 and parts[0].lower( ) == "guest" and settings.GUEST_ENABLED: try: # Find an available guest name. for playername in settings.GUEST_LIST: if not PlayerDB.objects.filter( username__iexact=playername): break playername = None if playername == None: session.msg( "Все гостевые аккаунты сейчас используются. Попробуйте немного позже." ) return password = "******" % 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_player = _create_player(session, playername, password, permissions, ptypeclass) if new_player: _create_character(session, new_player, typeclass, home, permissions) session.sessionhandler.login(session, new_player) 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. string = "%s\nЭто баг. Напишите пожалуйста на почту администратора." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) finally: return if len(parts) != 2: session.msg( "\n\r Использование (без <>): коннект <имя пользователя> <пароль>. Сокашенные варианты: кон, ко, войти" ) return playername, password = parts # Match account name and check password player = PlayerDB.objects.get_player_from_name(playername) pswd = None if player: pswd = player.check_password(password) if not (player and pswd): # No playername or password match string = "Неверные логин или пароль.\nЕсли в вашем логине или " \ "пароле есть пробелы, поместите их в кавычки." \ "\nЕсли вы новичек, создайте аккаунт при помощи" \ "команды 'создать'." session.msg(string) # this just updates the throttle _throttle(session, storage=_LATEST_FAILED_LOGINS) # calls player hook for a failed login if possible. if player: player.at_failed_login(session) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0] == player.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 = "{rВы были забанены." \ "\nЕсли считате, что мы были не правы, пишите на е-маил администратора.{x" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all other hooks: # session.at_login() # player.at_init() # always called when object is loaded from disk # player.at_pre_login() # player.at_first_login() # only once # player.at_post_login(sessid=sessid) session.sessionhandler.login(session, player)
def func(self): "Do checks and create account" session = self.caller args = self.args.strip() # extract quoted parts parts = [ part.strip() for part in re.split(r"\"|\'", args) if part.strip() ] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: string = u"\n Использование (без <>): создать <имя персонажа> <пароль>" \ u"\nЕсли <имя персонажа> или <пароль> содержат пробелы, нужно взять их в ковычки" session.msg(string) return playername, password = parts # sanity checks if not re.findall('^[\w. @+-]+$', playername, re.UNICODE) or not (0 < len(playername) <= 30): # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). string = u"\n\r Имя персонажа не должно превышать 30 символов. Имя может содержать только, буквы пробелы, цифры и @/./+/-/_" #string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only." session.msg(string) return # strip excessive spaces in playername playername = re.sub(r"\s+", " ", playername).strip() if PlayerDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg(u"Игрок с таким именем '%s' уже есть." % playername) return # Reserve playernames found in GUEST_LIST if settings.GUEST_LIST and playername.lower() in map( str.lower, settings.GUEST_LIST): string = u"\n\r Это имя зарезервировано. Пожалуйста выберите другое имя." session.msg(string) return if not re.findall('^[\w. @+-]+$', password, re.UNICODE) or not (3 < len(password)): string = u"\n\r Пароль должен быть больше трех символов и может состоять только из пробелов, цифр @\.\+\-\_" \ u"\nДля лучшей безопасности выберите пароль от 8 символов " session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0] == playername.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 = u"{rТы забанен{x" session.msg(string) session.execute_cmd("quit") return # everything's ok. Create the new player account. try: permissions = settings.PERMISSION_PLAYER_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_player = _create_player(session, playername, password, permissions) if new_player: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id( settings.DEFAULT_HOME) _create_character(session, new_player, typeclass, default_home, permissions) # tell the caller everything went well. string = u"Новый аккаунт создан Добро пожаловать %%USERNAME%%" if " " in playername: string += u"\n\nТеперь можно войти в игру 'connect \"%s\" <пароль>'." else: string += u"\n\nТеперь можно войти в игру 'connect %s <пароль>'." session.msg(string % (playername)) 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. string = u"%s\nСлучилась проблема, чиним." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc())
def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller # check for too many login errors too quick. if _throttle(session, maxlim=5, timeout=5*60, storage=_LATEST_FAILED_LOGINS): # timeout is 5 minutes. session.msg("{RВы совершаете слишклм много подключений. Подождите пару минут и попробуйте снова.{n") return args = self.args # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found, or a guest login parts = parts[0].split(None, 1) # Guest login if len(parts) == 1 and parts[0].lower() == "guest" and settings.GUEST_ENABLED: try: # Find an available guest name. for playername in settings.GUEST_LIST: if not PlayerDB.objects.filter(username__iexact=playername): break playername = None if playername == None: session.msg("Все гостевые аккаунты сейчас используются. Попробуйте немного позже.") return password = "******" % 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_player = _create_player(session, playername, password, permissions, ptypeclass) if new_player: _create_character(session, new_player, typeclass, home, permissions) session.sessionhandler.login(session, new_player) 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. string = "%s\nЭто баг. Напишите пожалуйста на почту администратора." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) finally: return if len(parts) != 2: session.msg("\n\r Использование (без <>): коннект <имя пользователя> <пароль>. Сокашенные варианты: кон, ко, войти") return playername, password = parts # Match account name and check password player = PlayerDB.objects.get_player_from_name(playername) pswd = None if player: pswd = player.check_password(password) if not (player and pswd): # No playername or password match string = "Неверные логин или пароль.\nЕсли в вашем логине или " \ "пароле есть пробелы, поместите их в кавычки." \ "\nЕсли вы новичек, создайте аккаунт при помощи" \ "команды 'создать'." session.msg(string) # this just updates the throttle _throttle(session, storage=_LATEST_FAILED_LOGINS) # calls player hook for a failed login if possible. if player: player.at_failed_login(session) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==player.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 = "{rВы были забанены." \ "\nЕсли считате, что мы были не правы, пишите на е-маил администратора.{x" session.msg(string) session.execute_cmd("quit") return # actually do the login. This will call all other hooks: # session.at_login() # player.at_init() # always called when object is loaded from disk # player.at_pre_login() # player.at_first_login() # only once # player.at_post_login(sessid=sessid) session.sessionhandler.login(session, player)
def func(self): "Do checks and create account" session = self.caller args = self.args.strip() # extract quoted parts parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: string = u"\n Использование (без <>): создать <имя персонажа> <пароль>" \ u"\nЕсли <имя персонажа> или <пароль> содержат пробелы, нужно взять их в ковычки" session.msg(string) return playername, password = parts # sanity checks if not re.findall('^[\w. @+-]+$', playername,re.UNICODE) or not (0 < len(playername) <= 30): # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). string = u"\n\r Имя персонажа не должно превышать 30 символов. Имя может содержать только, буквы пробелы, цифры и @/./+/-/_" #string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only." session.msg(string) return # strip excessive spaces in playername playername = re.sub(r"\s+", " ", playername).strip() if PlayerDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg(u"Игрок с таким именем '%s' уже есть." % playername) return # Reserve playernames found in GUEST_LIST if settings.GUEST_LIST and playername.lower() in map(str.lower, settings.GUEST_LIST): string = u"\n\r Это имя зарезервировано. Пожалуйста выберите другое имя." session.msg(string) return if not re.findall('^[\w. @+-]+$', password,re.UNICODE) or not (3 < len(password)): string = u"\n\r Пароль должен быть больше трех символов и может состоять только из пробелов, цифр @\.\+\-\_" \ u"\nДля лучшей безопасности выберите пароль от 8 символов " session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==playername.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 = u"{rТы забанен{x" session.msg(string) session.execute_cmd("quit") return # everything's ok. Create the new player account. try: permissions = settings.PERMISSION_PLAYER_DEFAULT typeclass = settings.BASE_CHARACTER_TYPECLASS new_player = _create_player(session, playername, password, permissions) if new_player: if MULTISESSION_MODE < 2: default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) _create_character(session, new_player, typeclass, default_home, permissions) # tell the caller everything went well. string = u"Новый аккаунт создан Добро пожаловать %%USERNAME%%" if " " in playername: string += u"\n\nТеперь можно войти в игру 'connect \"%s\" <пароль>'." else: string += u"\n\nТеперь можно войти в игру 'connect %s <пароль>'." session.msg(string % (playername)) 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. string = u"%s\nСлучилась проблема, чиним." session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc())