Пример #1
0
 def perspective_register(self, username, password):
     """Create a user account with specified username and password."""
     # TODO: consider defer.succeed, defer.fail, failure.Failure
     try:
         server.registerUser(username, password)
     except ValueError as err:  # Username/password validation failed.
         raise DeniedRequest(err)
Пример #2
0
    def perspective_changePassword(self, password):
        """Sets avatar's user account password to that specified."""
        if not isinstance(password, str):
            raise IllegalRequest("Invalid parameter for password")

        try:  # Validate password before it is changed.
            server.setUserPassword(self.name, password)
        except ValueError as err:  # Password validation failed.
            raise DeniedRequest(err)
Пример #3
0
    def perspective_getRoster(self, name):
        """Provides roster requested by client."""
        self.oldVersionCheck()  # TODO: remove after 0.4

        if name == 'tables':
            return server.availableTables
        elif name == 'users':
            return server.onlineUsers
        else:
            raise DeniedRequest("Unknown roster name \'%s\'" % name)
Пример #4
0
    def perspective_leaveTable(self, tableid):
        """Leaves a table."""
        self.oldVersionCheck()  # TODO: remove after 0.4

        if not isinstance(tableid, str):
            raise IllegalRequest("Invalid parameter for table identifier")
        if tableid not in self.joinedTables:
            raise DeniedRequest("Not joined to table")
        
        del self.joinedTables[tableid]  # Implicitly removes user from table.
Пример #5
0
    def perspective_joinTable(self, tableid, host=False, **hostParams):
        """Joins an existing table, or creates and joins a new table."""
        self.oldVersionCheck()  # TODO: remove after 0.4

        if not isinstance(tableid, str):
            raise IllegalRequest("Invalid parameter for table identifier")
        if tableid in self.joinedTables:
            raise DeniedRequest("Already joined table")

        if host:
            table = server.createTable(tableid, **hostParams)
        else:
            try:
                table = server.availableTables[tableid]
            except KeyError:
                raise DeniedRequest("No such table")

        self.joinedTables[tableid] = table
        return table
Пример #6
0
    def leaveGame(self, user, position):
        if position not in self.game.positions:
            raise IllegalRequest("Invalid position type")
        # Ensure that user is playing at specified position.
        if self.players.get(position) != user:
            raise DeniedRequest("Not playing at position")

        self.game.removePlayer(position)  # May raise GameError.
        del self.players[position]
        self.notify('leaveGame', player=user.name, position=position)
Пример #7
0
    def send(self, message):
        # Validate message.
        if message.text == '':
            raise DeniedRequest("Message must contain text")
        if len(message.text) > self.messageMaxLength:
            raise DeniedRequest("Message text longer than character limit")
        # TODO: filter message for spam, obscenity, ...

        if message.recipients:  # Specified recipients.
            sendTo = [
                p for p in self.observers if p.name in message.recipients
            ]  # O(n^2)
            if sendTo == []:
                raise DeniedRequest("No named recipient present at table.")
        else:
            sendTo = list(self.observers.keys())

        self.messages.append(message)
        self.notify('gotMessage', message=message)
Пример #8
0
def setUserPassword(username, password):
    """Changes the password of user's account.
    
    @param username: the user identifier.
    @param password: the new password for user.
    """
    try:
        user = db.UserAccount.selectBy(username=username)[0]
        user.set(password=password)  # May raise ValueError.
    except IndexError:
        raise DeniedRequest("User account does not exist")
Пример #9
0
def registerUser(username, password):
    """Registers a new user account in the database.
    
    @param username: the unique username requested by user.
    @param password: the password to be associated with the account.
    """
    # Check that username has not already been registered.
    if db.UserAccount.selectBy(username=username).count() > 0:
        raise DeniedRequest("Username already registered")

    # Create user account - may raise ValueError.
    db.UserAccount(username=username, password=password, allowLogin=True)
    log.msg("New user %s registered" % username)
Пример #10
0
    def joinGame(self, user, position):
        if position not in self.game.positions:
            raise IllegalRequest("Invalid position type")
        # Check that user is not already playing at table.
        if not self.config.get('MultiplePlayersPerUser'):
            if user in list(self.players.values()):
                raise DeniedRequest("Already playing in game")

        player = self.game.addPlayer(position)  # May raise GameError.
        self.players[position] = user
        self.notify('joinGame', player=user.name, position=position)

        return player
Пример #11
0
def createTable(tableid, gamename, **tableOptions):
    """Create a new table for the specified game type.
    
    @param tableid: a unique identifier for the table.
    @param gamename: a game class identifier.
    @param tableOptions: optional parameters for table initialisation.
    """
    # TODO: convert gametype string to corresponding class.

    if not 0 < len(tableid) <= 20 or re.search("[^A-Za-z0-9_ ]", tableid):
        raise IllegalRequest("Invalid table identifier format")
    if tableid in availableTables:
        raise DeniedRequest("Table name exists")
    if gamename not in SUPPORTED_GAMES:
        raise DeniedRequest("Unsupported game class %s" % gamename)

    gameclass = SUPPORTED_GAMES[gamename]
    table = LocalTable(tableid, gameclass)
    # Provide table instance with a means of closing itself.
    table.close = lambda: availableTables.closeTable(table)
    availableTables.openTable(table)

    return table
Пример #12
0
    def perspective_getUserInformation(self, username=None):
        """Returns public information for user with specified username.
        
        If username is unspecified, returns user's own public information.
        """
        if username is None:
            username = self.name

        try:
            user = db.UserAccount.selectBy(username=username)[0]
        except IndexError:
            raise DeniedRequest("Specified user does not exist")

        info = {}
        for field in 'realname', 'email', 'country', 'profile':
            value = getattr(user, field, None)
            # Do not send unspecified (null) values.
            if value is not None:
                info[field] = value
        return info