class GameRole(Base, JSONAPIMixin): """The :class:`~webrpg.components.game.GameRole` represents the role a :class:`~webrpg.components.user.User` has in a :class:`~webrpg.components.game.Game`. Roles supported are: "owner" and "player". """ __tablename__ = 'games_roles' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id', name='games_roles_user_id_fk')) game_id = Column(Integer, ForeignKey('games.id', name='games_roles_game_id_fk')) role = Column(Unicode(255)) game = relationship('Game') user = relationship('User') __create_schema__ = JSONAPISchema( 'game-roles', attribute_schema=DynamicSchema( {'role': validators.UnicodeString(not_empty=True)}), relationship_schema=DynamicSchema({ 'game': { 'data': { 'type': validators.OneOf(['games'], not_empty=True), 'id': validators.Number } }, 'user': { 'data': { 'type': validators.OneOf(['users'], not_empty=True), 'id': validators.Number } } })) __json_attributes__ = ['role'] __json_computed__ = ['is_me'] __json_relationships__ = ['game', ('user', True)] def is_me(self, request): """Check if the current :class:`~webrpg.components.user.User` is the one linked to this this :class:`~webrpg.components.game.GameRole`.""" if request.current_user and request.current_user.id == self.user_id: return True else: return False def allow(self, user, action): return True
def get_tournaments(self, game_name: str) -> dict: try: game_name = validators.OneOf( api_config['game_names']).to_python(game_name) except formencode_api.Invalid as exc: return str(exc) return datanal_tools.get_tournaments(game_name)
def download_past_data(self, output: str = 'csv', log: bool = True): try: self.log = log output = validators.OneOf(['csv', 'sql']).to_python(output) except formencode_api.Invalid as exc: return str(exc) tmp_file_path = os.path.normpath( os.path.join(app_config['path_storage'], 'tmp', str(uuid.uuid4()))) if not datanal_tools.prepare_data_output('past', output, tmp_file_path): return False if output == 'csv': extension = 'zip' # More CSV files are zipped in archive for download file_name = 'esport-past-{}.{}'.format( datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'), extension) else: extension = 'sql' file_name = 'esport-past-{}.{}'.format( datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'), extension) cherrypy.request.tmp_file_path = tmp_file_path cherrypy.request.hooks.attach('on_end_request', self._download_complete) return cherrypy.lib.static.serve_download(path=tmp_file_path, name=file_name)
class DirectoryDeviceLinkCompletionValidator(Schema): """Directory User Device link completion validator""" type = validators.OneOf(['DEVICE_LINK_COMPLETION']) device_id = validators.String() device_public_key = validators.String() device_public_key_id = validators.String() allow_extra_fields = True
def set(self, op, value1, value2=None): if not op: self.default_op = self._default_op() if callable( self._default_op) else self._default_op self.op = self.default_op self.using_default_op = (self.default_op is not None) if self.op is None: return if not op and self.using_default_op: value1 = self._default_value(self.default_value1) value2 = self._default_value(self.default_value2) # set values used in display first, since processing validation may # raise exceptions self.op = feval.OneOf(self.op_keys, not_empty=True).to_python(op or self.default_op) self.value1_set_with = value1 self.value2_set_with = value2 try: self.value1 = self.process(value1, False) self.value2 = self.process(value2, True) except formencode.Invalid: self.error = True raise
def sharedstate(self): chk_type = self.request.context.chk_type self._check_security(chk_type, True) request = self.request model_state = request.model_state model_state.validators = { "state": validators.OneOf(["local", "shared"], not_empty=True), "ID": ciocvalidators.IDValidator(not_empty=True), } model_state.method = None if not model_state.validate(): self._error_page(_("Invalid ID", request)) ID = model_state.form.data["ID"] title = _("Manage Publications", request) return self._create_response_namespace( title, title, dict(ID=ID, state=model_state.value("state"), chk_type=chk_type), no_index=True, )
def grab_past_data(self, data_src: str, game_name: str, date_from: date = None, date_to: date = None, log: bool = True, delete_old: bool = True) -> OrderedDict: try: self.data_src = data_src self.log = log game_name = validators.OneOf( api_config['game_names']).to_python(game_name) if date_from: date_from = validators.DateValidator().to_python(date_from) if date_to: date_to = validators.DateValidator().to_python(date_to) if date_from and date_to: if datetime.strptime(date_from, "%Y-%m-%d") > datetime.strptime( date_to, "%Y-%m-%d"): raise ValueError('Date from should be before date to') elif datetime.strptime(date_to, "%Y-%m-%d") > datetime.utcnow(): raise ValueError('Date to should be before in future') delete_old = validators.Bool().to_python(delete_old) except formencode_api.Invalid as exc: return str(exc) except ValueError as exc: return str(exc) return self.connector.grab_past_data(game_name, date_from, date_to, delete_old)
class O211ExportOptionsSchema(Schema): allow_extra_fields = True if_key_missing = None feed = validators.OneOf("recordids taxonomy community".split(), if_empty=None, strip=True) date = ciocvalidators.ISODateConverter(if_empty=None)
def save_tournaments(self) -> True: try: game_name = validators.OneOf(api_config['game_names']).to_python( cherrypy.request.json['game_name']) except formencode_api.Invalid as exc: return str(exc) tournaments = cherrypy.request.json['tournaments'] datanal_tools.save_tournaments(game_name, tournaments) return True
class EditForm(formencode.Schema): role = formencode.All(fv.UnicodeString(not_empty=False), fv.OneOf(ROLES)) password = formencode.All(fv.UnicodeString(not_empty=False)) first_name = formencode.All(fv.UnicodeString(not_empty=False), fv.MaxLength(64)) last_name = formencode.All(fv.UnicodeString(not_empty=False), fv.MaxLength(64)) default_timezone = fv.Int(not_empty=False) is_active = fv.Bool(not_empty=False)
class Objective(formencode.Schema): reference = validators.UnicodeString(not_empty=True, strip=True, encoding='utf-8') name = validators.UnicodeString(not_empty=True, encoding='utf-8') description = validators.UnicodeString(encoding='utf-8') section = compound.Any(validators.OneOf(["none","new"]), SectionId()) newsection = validators.UnicodeString(encoding='utf-8') rationale = validators.UnicodeString(encoding='utf-8') priority = validators.Int(not_empty=True, encoding='utf-8') applicable = validators.Bool()
class Test_and_Spec(formencode.Schema): reference = validators.UnicodeString(not_empty=True, strip=True, encoding='utf-8') name = validators.UnicodeString(encoding='utf-8') test_group = compound.Any(validators.OneOf(["none","new"]), TestGroupId()) new_group = validators.UnicodeString(encoding='utf-8') description = validators.UnicodeString(encoding='utf-8') expected_result = validators.UnicodeString(encoding='utf-8') code = validators.UnicodeString(encoding='utf-8') comment = validators.UnicodeString(encoding='utf-8') dependencies = formencode.ForEach(TestSpecId())
class RegisterForm(formencode.Schema): username = formencode.All(validators.PlainText(not_empty = True), UniqueUsername) email = validators.Email(not_empty = True) email_confirm = validators.String() password = validators.String(not_empty = True) password_confirm = validators.String() TOS_accept = validators.OneOf(['1']) chained_validators = [validators.FieldsMatch('email', 'email_confirm'), validators.FieldsMatch('password', 'password_confirm'),]
class Session(Base, JSONAPIMixin): """The :class:`~webrpg.components.session.Session` represents a single gaming session for a :class:`~webrpg.components.game.Game`. It holds the following attributes: "title", "dice_roller". """ __tablename__ = 'sessions' id = Column(Integer, primary_key=True) game_id = Column(Integer, ForeignKey('games.id', name='sessions_game_id_fk')) title = Column(Unicode(255)) dice_roller = Column(Unicode(255)) game = relationship('Game') maps = relationship('Map', order_by='Map.title') chat_messages = relationship('ChatMessage', order_by='ChatMessage.id') __create_schema__ = JSONAPISchema( 'sessions', attribute_schema=DynamicSchema({ 'title': validators.UnicodeString(not_empty=True), 'dice_roller': validators.OneOf(['d20', 'eote'], not_empty=True) }), relationship_schema=DynamicSchema({ 'game': { 'data': { 'type': validators.OneOf(['games'], not_empty=True), 'id': validators.Number } } })) __json_attributes__ = ['title', 'dice_roller'] __json_relationships__ = ['game', 'chat_messages', 'maps'] def allow(self, user, action): """Check if the given :class:`~webrpg.components.user.User` is allowed to undertake the given ``action``.""" return True
class QuickSearchBaseSchema(Schema): if_key_missing = None QuickSearchID = Any(ciocvalidators.IDValidator(), validators.OneOf(["NEW"])) DisplayOrder = validators.Int(min=0, max=255, not_empty=True) PageName = validators.OneOf(search_pages) PromoteToTab = validators.Bool() QueryParameters = ciocvalidators.String(max=1000, not_empty=True) delete = validators.Bool() Descriptions = ciocvalidators.CultureDictSchema( QuickSearchDescriptionSchema(), allow_extra_fields=True, fiter_extra_fields=False, chained_validators=[ ciocvalidators.FlagRequiredIfNoCulture( QuickSearchDescriptionSchema) ], )
class MenuItemSchema(Schema): if_key_missing = None delete = validators.Bool() MenuID = Any(ciocvalidators.IDValidator(), validators.OneOf(["NEW"])) Link = ciocvalidators.String(max=150) Display = ciocvalidators.UnicodeString(max=200) MenuGroup = ciocvalidators.Int(min=1, max=3) chained_validators = [ ciocvalidators.RequireIfAny("Display", present=("Link", )), ciocvalidators.RequireIfAny("Link", present=("Display", )), ]
def collect_current_data(self, data_src: str, game_name: str, log: bool = True) -> True: try: self.data_src = data_src self.log = log game_name = validators.OneOf( api_config['game_names']).to_python(game_name) except formencode_api.Invalid as exc: return str(exc) self.connector.collect_current_data(game_name) return True
class FieldGroupBaseSchema(Schema): if_key_missing = None DisplayFieldGroupID = Any(ciocvalidators.IDValidator(), validators.OneOf(["NEW"])) DisplayOrder = validators.Int(min=0, max=256, not_empty=True) delete = validators.Bool() Descriptions = ciocvalidators.CultureDictSchema( FieldGroupDescriptionSchema(), record_cultures=True, allow_extra_fields=True, fiter_extra_fields=False, )
def __init__(self, formfields, request, send="Ändern", chained_validators=[]): token_field = HiddenField('csrf_token', value=request.session.get_csrf_token(), validator=validators.OneOf( [request.session.get_csrf_token()], hideList=True)) Form.__init__(self, formfields + [token_field], send=send, chained_validators=chained_validators)
class NaicsExampleBaseSchema(Schema): if_key_missing = None Example_ID = Any(ciocvalidators.IDValidator(), validators.OneOf(["NEW"])) LangID = validators.Int(min=0, max=ciocvalidators.MAX_SMALL_INT, not_empty=True) Description = ciocvalidators.UnicodeString( max=255) # sometimes required as per RequireIfPredicate below delete = validators.Bool() chained_validators = [ ciocvalidators.RequireIfPredicate(description_required, ["Description"]) ]
class Map(Base, JSONAPIMixin): """The :class:`~webrpg.components.map.Map` represents a game map. It has the following attributes: "title", "map", "fog". The "map" and "fog" attributes use DataURLs to represent the base map image data and the fog-of-war overlay image data. """ __tablename__ = 'maps' id = Column(Integer, primary_key=True) session_id = Column(Integer, ForeignKey('sessions.id', name='maps_session_id_fk')) title = Column(Unicode(255)) map = Column(UnicodeText) fog = Column(UnicodeText) session = relationship('Session') __create_schema__ = JSONAPISchema( 'maps', attribute_schema=DynamicSchema( {'title': validators.UnicodeString(not_empty=True)}), relationship_schema=DynamicSchema({ 'session': { 'data': { 'type': validators.OneOf(['sessions'], not_empty=True), 'id': validators.Number } } })) __update_schema__ = JSONAPISchema( 'maps', attribute_schema=DynamicSchema({ 'title': validators.UnicodeString(if_missing=DoNotStore), 'map': validators.UnicodeString(if_missing=DoNotStore), 'fog': validators.UnicodeString(if_missing=DoNotStore) })) __json_attributes__ = ['title', 'map', 'fog'] __json_relationships__ = ['session'] def allow(self, user, action): """Check if the given :class:`~webrpg.components.user.User` is allowed to undertake the given ``action``.""" return True
class TerritoryFenceValidator(Schema): """ TerritoryFence Validator""" name = validators.String(if_missing=None) type = validators.OneOf(["TERRITORY"], if_missing=None) country = validators.Regex(r"^[A-Z]{2}$", not_empty=True) administrative_area = validators.Regex(r"^[A-Z]{2}-[A-Z]{2}[A-Z]?$", if_missing=None) postal_code = validators.String(if_missing=None, if_empty=None) @staticmethod def _validate_python(value, _state): if not value["administrative_area"]: del value["administrative_area"] if not value["postal_code"]: del value["postal_code"]
class ActionSchema(CSRFSchema): """The :class:`~wte.views.user.ActionSchema` handles the validation of user action requests. """ action = All(validators.UnicodeString(not_empty=True), validators.OneOf(['validate', 'password', 'delete'])) """The action to apply""" confirm = validators.StringBool(if_empty=False, if_missing=False) """Whether the user has confirmed the action""" user_id = ForEach(validators.Int(), if_missing=None) """User ids to apply the action to""" q = validators.UnicodeString(if_empty=None, if_missing=None) """Optional query parameter for the redirect""" status = validators.UnicodeString(if_empty=None, if_missing=None) """Optional status parameter for the redirect""" start = validators.UnicodeString(if_empty=None, if_missing=None) """Optional start parameter for the redirect"""
class FenceValidator(Schema): """Fence validator""" allow_extra_fields = True type = validators.OneOf(["GEO_CIRCLE", "TERRITORY"], if_missing=None) name = validators.String(if_missing=None) @staticmethod def _validate_python(value, _state): if not value["type"]: del value["type"] GeoFenceValidator().to_python(value) elif value["type"] == "GEO_CIRCLE": GeoCircleFenceValidator().to_python(value) elif value["type"] == "TERRITORY": TerritoryFenceValidator().to_python(value)
def sharedstate_confirm(self): chk_type = self.request.context.chk_type self._check_security(chk_type, True) request = self.request model_state = request.model_state model_state.validators = { "state": validators.OneOf(["local", "shared"], not_empty=True), "ID": ciocvalidators.IDValidator(not_empty=True), } if not model_state.validate(): self._error_page(_("Invalid ID", request)) ID = model_state.form.data["ID"] # shared = model_state.value('state')=='shared' sql = """ DECLARE @OldMemberID int, @MemberID int, @ChkID int SET @MemberID=? SET @ChkID=? SELECT @OldMemberID=MemberID FROM {Table} WHERE {ID}=@ChkID UPDATE {Table} SET MODIFIED_BY=?, MODIFIED_DATE=GETDATE(), MemberID=NULL WHERE {ID}=@ChkID INSERT INTO {Table}_InactiveByMember ({ID}, MemberID) SELECT @ChkID, MemberID FROM STP_Member m WHERE MemberID NOT IN (ISNULL(@OldMemberID, 0), @MemberID) AND NOT EXISTS(SELECT * FROM {Table}_InactiveByMember WHERE {ID}=@ChkID AND MemberID=m.MemberID) """.format( Table=chk_type.Table, ID=chk_type.ID, ) with request.connmgr.get_connection("admin") as conn: conn.execute(sql, [request.dboptions.MemberID, ID, request.user.Mod]) msg = _("The value was successfully shared.", request) self._go_to_route("admin_checklists", _query=[("InfoMsg", msg), ("chk", chk_type.FieldCode)])
class ImportForm(formencode.Schema): """ Validate for Import Connectivity Form """ server_ip = validators.IPAddress(not_empty=True) username = validators.UnicodeString(not_empty=True) password = validators.UnicodeString() threads_number = validators.Number() dti_scans = FileUploadValidator() subject_name = validators.UnicodeString() subject_sex = validators.OneOf(['Any', 'Male', 'Female']) subject_age = validators.Number() subject_race = validators.UnicodeString() subject_nationality = validators.UnicodeString() subject_education = validators.UnicodeString() subject_health = validators.UnicodeString()
class DocSchema(formencode.Schema): """Validate the document and the add/remove operation. """ allow_extra_fields = True id = validators.String(not_empty=True, strip=True) lang = validators.String(not_empty=True, strip=True, if_missing='en') version = validators.String(strip=True, if_missing=datetime.now().strftime('%s')) type = validators.OneOf( ["add", "delete"], not_empty=True, strip=True, )
def analyze_current_data(self, data_src: str, game_name: str = None, data_src_tournament_id: int = None, log: bool = True) -> OrderedDict: try: self.data_src = data_src self.log = log if game_name is not None: game_name = validators.OneOf( api_config['game_names']).to_python(game_name) if data_src_tournament_id is not None: data_src_tournament_id = validators.Int( min=1).to_python(data_src_tournament_id) except formencode_api.Invalid as exc: return str(exc) return Analyzer().process_data('current', data_src, game_name, data_src_tournament_id)
class NaicsExclusionBaseSchema(Schema): if_key_missing = None Exclusion_ID = Any(ciocvalidators.IDValidator(), validators.OneOf(["NEW"])) LangID = validators.Int(min=0, max=ciocvalidators.MAX_SMALL_INT, not_empty=True) Description = ciocvalidators.UnicodeString( max=255) # sometimes required as per RequireIfPredicate below Establishment = validators.Bool() UseCodes = foreach.ForEach(ciocvalidators.NaicsCode()) delete = validators.Bool() chained_validators = [ ciocvalidators.RequireIfPredicate(description_required, ["Description"]) ]
def test_mixed_list(self): """before `_message_vars_decode`, the errors were: Value must be one of: a; b; ö; ™; 1; 2; 3 (not u'c') Value must be one of: a; b; ö; ™; 1; 2; 3 (not u'\xa7') """ o = validators.OneOf(['a', 'b', 'ö', '™', 1, 2, 3]) try: o.to_python('c') raise ValueError("exception expected") except Invalid as e: self.assertTrue( "Value must be one of: a; b; ö; ™; 1; 2; 3 (not 'c')" in unicode(e)) try: o.to_python(9) raise ValueError("exception expected") except Invalid as e: self.assertTrue("Value must be one of: a; b; ö; ™; 1; 2; 3 (not 9)" in unicode(e)) try: o.to_python(u'd') raise ValueError("exception expected") except Invalid as e: self.assertTrue( "Value must be one of: a; b; ö; ™; 1; 2; 3 (not 'd')" in unicode(e)) try: o.to_python('§') raise ValueError("exception expected") except Invalid as e: if six.PY2: self.assertTrue( r"Value must be one of: a; b; ö; ™; 1; 2; 3 (not u'\xa7')" in unicode(e)) else: self.assertTrue( r"Value must be one of: a; b; ö; ™; 1; 2; 3 (not '§')" in unicode(e))