class SettingsForm(formencode.Schema): """ Validate Settings Page inputs. """ ADMINISTRATOR_NAME = formencode.All( validators.UnicodeString(not_empty=True), validators.PlainText()) ADMINISTRATOR_DISPLAY_NAME = formencode.All( validators.UnicodeString(not_empty=True), validators.PlainText()) ADMINISTRATOR_PASSWORD = validators.UnicodeString(not_empty=True) ADMINISTRATOR_EMAIL = validators.Email(not_empty=True) WEB_SERVER_PORT = PortValidator() SELECTED_DB = validators.UnicodeString(not_empty=True) URL_VALUE = validators.UnicodeString(not_empty=True) DEPLOY_CLUSTER = validators.Bool() CLUSTER_SCHEDULER = validators.UnicodeString(not_empty=True) KEYCLOAK_CONFIGURATION = validators.UnicodeString() KEYCLOAK_WEB_CONFIGURATION = validators.UnicodeString() ENABLE_KEYCLOAK_LOGIN = validators.Bool() TVB_STORAGE = validators.UnicodeString(not_empty=True) USR_DISK_SPACE = DiskSpaceValidator(not_empty=True) MATLAB_EXECUTABLE = MatlabValidator() MAXIMUM_NR_OF_THREADS = ThreadNrValidator() MAXIMUM_NR_OF_VERTICES_ON_SURFACE = SurfaceVerticesNrValidator() MAXIMUM_NR_OF_OPS_IN_RANGE = validators.Int(min=5, max=5000, not_empty=True)
class RecoveryForm(formencode.Schema): """ Validate Recover Password Form """ username = formencode.All(validators.UnicodeString(not_empty=True), validators.PlainText()) email = validators.Email(not_empty=True)
class SettingsForm(formencode.Schema): """ Validate Settings Page inputs. """ ADMINISTRATOR_NAME = formencode.All( validators.UnicodeString(not_empty=True), validators.PlainText()) ADMINISTRATOR_PASSWORD = validators.UnicodeString(not_empty=True) ADMINISTRATOR_EMAIL = validators.Email(not_empty=True) WEB_SERVER_PORT = PortValidator() MPLH5_SERVER_PORT = PortValidator() URL_WEB = validators.URL(not_empty=True, require_tld=False) URL_MPLH5 = AsciiValidator(not_empty=True) SELECTED_DB = validators.UnicodeString(not_empty=True) URL_VALUE = validators.UnicodeString(not_empty=True) DEPLOY_CLUSTER = validators.Bool() TVB_STORAGE = AsciiValidator(not_empty=True) USR_DISK_SPACE = DiskSpaceValidator(not_empty=True) MATLAB_EXECUTABLE = MatlabValidator() MAXIMUM_NR_OF_THREADS = ThreadNrValidator() MAXIMUM_NR_OF_VERTICES_ON_SURFACE = SurfaceVerticesNrValidator() MAXIMUM_NR_OF_OPS_IN_RANGE = validators.Int(min=5, max=5000, not_empty=True)
class ProfileForm(BaseForm): email = validators.Email(not_empty=True, resolve_domain=False, max=120) username = validators.PlainText(not_empty=True, strip=True) blog_name = validators.String(not_empty=False, max=40, strip=True) blog_url = URL(not_empty=False, max=600, add_http=True) next = validators.String(not_empty=False, max=600) def __after__(self): try: v = self._values length = len(v["username"]) if length < 3 or length > 40: self.add_error( "username", "Username should be more than three and less than forty characters." ) self._handler.db.execute( "UPDATE user SET username = %s, email = %s, status_ = %s, \ blog_name = %s, blog_url = %s WHERE id = %s" , v['username'].lower(), v['email'], const.Status.ACTIVE, \ v['blog_name'], v['blog_url'], self._handler.current_user.id ) self._handler.set_secure_cookie("user", v['username'], domain=options.cookie_domain) except Exception, e: logging.error(str(e)) self.add_error("username", "Save profile error, please try it later.")
class RegisterSchema(Schema): filter_extra_fields = True allow_extra_fields = True name = validators.UnicodeString(not_empty=True, strip=True) nickname = validators.PlainText(strip=True, if_empty='', if_missing='', if_invalid='') gender = validators.Int(min=0, max=3, if_empty=0, if_missing=0, if_invalid=0) email = All(validators.Email(not_empty=True, strip=True), UniqueEmail()) phoneNumber = national.USPhoneNumber(strip=True, if_empty='', if_missing='', if_invalid='') password = validators.String(not_empty=True) graduationYear = validators.Int(min=1967, not_empty=True) biography = validators.UnicodeString(strip=True, if_empty=u'', if_missing=u'', if_invalid=u'') active = validators.StringBool(if_empty=False, if_missing=False, if_invalid=False, strip=True) recaptcha_challenge_field = validators.String(strip=True, not_empty=True) recaptcha_response_field = RecaptchaValidator(strip=True, not_empty=True) _csrf = validators.String(strip=True, not_empty=True)
class SitePoweredForm(BaseForm): site_id = validators.Int(not_empty=True) projects = validators.Set(not_empty=True, use_set=True) powered_projects = validators.PlainText() def __after__(self): try: values = [] del_values = [] if self._values["powered_projects"] is not None: powered_projects = self._values["powered_projects"].split("-") else: powered_projects = [] for project in self._values["projects"]: if project not in powered_projects: values.append((self._values["site_id"], project)) for project in powered_projects: if project not in self._values["projects"]: del_values.append((self._values["site_id"], project)) self._handler.db.executemany("INSERT INTO project_sites (site_id, project_id) " "VALUES (%s, %s)", values) if del_values: self._handler.db.executemany("DELETE from project_sites where site_id = %s and project_id = %s", del_values) if values or del_values: self._handler.db.execute("UPDATE site SET updated = UTC_TIMESTAMP() where id = %s", self._values["site_id"]) except Exception, e: logging.error(str(e)) self.add_error("projects", "Submit powered by information error, please try it later.")
class NoteSchema(Schema): filter_extra_fields = True allow_extra_fields = True title = validators.String(not_empty=True) author = validators.String(not_empty=True) subject = validators.String(not_empty=True) description = validators.PlainText(not_empty=True)
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 ProjectImportForm(schema.Schema): def __init__(self, source): super(ProjectImportForm, self).__init__() provider = ProjectRegistrationProvider.get() self.add_field('tools', ToolsValidator(source)) self.add_field('project_shortname', provider.shortname_validator) self.allow_extra_fields = True neighborhood = fev.PlainText(not_empty=True) project_name = fev.UnicodeString(not_empty=True, max=40)
class RegisterForm(formencode.Schema): """ Validate Register Form """ username = formencode.All(validators.UnicodeString(not_empty=True), validators.PlainText(), UniqueUsername()) password = validators.UnicodeString(not_empty=True) password2 = validators.UnicodeString(not_empty=True) email = validators.Email(not_empty=True) comment = validators.UnicodeString() role = validators.UnicodeString() chained_validators = [validators.FieldsMatch('password', 'password2')]
class UserCreateForm(formencode.Schema): allow_extra_fields = True user_name = formencode.All(validators.PlainText(not_empty=True), forms.UniqueUsername(), forms.ContainsChar()) email = formencode.All(validators.Email(), forms.UniqueEmail()) password = validators.String(not_empty=True) password_confirm = validators.String(not_empty=True) password_confirm = validators.String(not_empty=True) chained_validators = [ validators.FieldsMatch('password', 'password_confirm') ]
class Registration(formencode.Schema): """ The schema""" first_name = validators.String(not_empty=True) last_name = validators.String(not_empty=True) email = validators.Email(resolve_domain=True) username = formencode.All(validators.PlainText(), UniqueUsername()) password = SecurePassword() password_confirm = validators.String() chained_validators = [validators.FieldsMatch( 'password', 'password_confirm')]
class EditForm(formencode.Schema): """ Validate creation of a Project entity. """ invalis_name_msg = "Please enter a name composed only of letters, numbers and underscores." name = formencode.All(validators.UnicodeString(not_empty=True), validators.PlainText(messages={'invalid': invalis_name_msg})) description = validators.UnicodeString() users = formencode.foreach.ForEach(formencode.validators.Int()) administrator = validators.UnicodeString(not_empty=False) project_id = validators.UnicodeString(not_empty=False) visited_pages = validators.UnicodeString(not_empty=False)
class TestForm(formencode.Schema): """ Example form used with PrototypeController.form1 Have a look at validators.py to see all the other available validators """ allow_extra_fields = False email = validators.Email( ) # match an email address, could also add resolve_domain=True for additional checks name = formencode.All( # require all enclosed validators to pass, could also use formencode.Any validators.String(not_empty=True, min=2, max=50), validators.PlainText()) yearborn = YearBornValidator()
class ProjectForm(BaseForm): subdomain = validators.PlainText(not_empty=True, strip=True) name = validators.String(not_empty=True, min=3, max=30, strip=True) category = validators.Int(not_empty=True) keywords = validators.String(not_empty=False, max=100) desc = validators.String(not_empty=False, max=600) website = URL(not_empty=False, max=600, add_http=True) logo = URL(not_empty=False, max=600, add_http=True) def __after__(self): try: v = self._values status = const.Status.ACTIVE length = len(v["subdomain"]) if length < 3 or length > 20: self.add_error( "subdomain", "Name should be more than three and less than twenty charaters." ) if self._handler.db.get( "select * from project where subdomain = %s", v["subdomain"]): self.add_error("subdomain", "This name already be registered.") elif self._handler.db.get( "select * from domains where domain = %s", v["subdomain"]): self.add_error("subdomain", "This name is reserved by poweredsites.org.") else: user_id = self._handler.current_user.id if (not self._handler.is_staff): user_projects = self._handler.db.get("select count(*) as c from project where user_id = %s", \ user_id) if user_projects is not None and user_projects.c >= 3: # It will need approve if someone create more than three projects status = const.Status.PENDING stmt = "INSERT INTO project (subdomain,project,website,keywords,description,"\ "category_id,user_id,logo,uuid_,created,status_) "\ "VALUES (%s,%s,%s,%s,%s,"\ "%s,%s,%s,%s,UTC_TIMESTAMP(),%s)" args = (v["subdomain"].lower(), v["name"], v["website"], v["keywords"], v["desc"], \ v["category"], user_id, v["logo"], uuid.uuid4().hex, status) self._handler.db.execute(stmt, *args) except Exception, e: logging.error(str(e)) self.add_error("subdomain", "Submit project error, please try it later.")
class SOValidation(SQLObject): name = StringCol(validator=validators.PlainText(), default='x', dbName='name_col') name2 = StringCol(validator=validators.ConfirmType(type=str), default='y') name3 = IntCol(validator=validators.Wrapper(fromPython=int), default=100) name4 = FloatCol(default=2.718) name5 = PickleCol(default=None) name6 = BoolCol(default=None) name7 = UnicodeCol(default=None) name8 = IntCol(default=None) name9 = IntCol(validator=validator1, validator2=validator2, default=0)
class BaseForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = True _xsrf = validators.PlainText(not_empty=True, max=32) def __init__(self, handler): self._parmas = {} self._values = {} self._form_errors = {} arguments = {} # re-parse qs, keep_blank_values for formencode to validate # so formencode not_empty setting work. request = handler.request content_type = request.headers.get("Content-Type", "") if request.method == "POST": if content_type.startswith("application/x-www-form-urlencoded"): arguments = urlparse.parse_qs(request.body, keep_blank_values=1) for k, v in arguments.iteritems(): if len(v) == 1: self._parmas[k] = v[0] else: # keep a list of values as list (or set) self._parmas[k] = v self._handler = handler self._result = True def validate(self): try: self._values = self.to_python(self._parmas) self._result = True self.__after__() except formencode.Invalid, error: self._values = error.value self._form_errors = error.error_dict or {} self._result = False return self._result
def verify(self): if not openid_login_allowed(): ret_abort(_("OpenID login has been disabled on this installation"), code=403) self.consumer = create_consumer(self.openid_session) info = self.consumer.complete( request.params, h.base_url('/openid/verify', absolute=True)) if not info.status == SUCCESS: return self._failure(info.identity_url, _("OpenID login failed.")) email = None user_name = None # evaluate Simple Registration Extension data srep = sreg.SRegResponse.fromSuccessResponse(info) if srep: if srep.get('nickname'): user_name = srep.get('nickname').strip() if srep.get('email'): email = srep.get('email') # evaluate Attribute Exchange data # TBD: AXSCHEMA friendlyName # TBD: SignedMembership axrep = ax.FetchResponse.fromSuccessResponse(info) if axrep: ax_mail_schema = get_ax_mail_schema(info.identity_url) try: email = axrep.getSingle(ax_mail_schema) or email except ValueError: email = axrep.get(ax_mail_schema)[0] except KeyError: email = email if 'openid_session' in session: self.delete_session() oid = model.OpenID.find(info.identity_url) if oid: if c.user: if oid.user == c.user: return self._failure( info.identity_url, _("You have already claimed this OpenID.")) else: return self._failure( info.identity_url, _("OpenID %s is already connected to an account.") % (info.identity_url, oid.user.name)) else: self._login(oid.user) # returns else: if c.user: oid = model.OpenID(unicode(info.identity_url), c.user) model.meta.Session.add(oid) model.meta.Session.commit() h.flash(_("Successfully added OpenID to user account."), 'success') redirect(h.entity_url(c.user, member='settings/login')) else: if not h.allow_user_registration(): h.flash( _("OpenID %s doesn't belong to an existing user account " "and user registration is disabled in this " "installation." % info.identity_url), 'warning') redirect(h.base_url('/login')) user_by_email = model.User.find_by_email(email) if user_by_email is not None: if is_trusted_provider(info.identity_url): # A user with the email returned by the OpenID provider # exists. As we trust the OpenID provider, we log in # that account and assign the OpenID to this user. oid = model.OpenID(unicode(info.identity_url), user_by_email) model.meta.Session.add(oid) model.meta.Session.commit() h.flash( _("Successfully added OpenID to user account."), 'success') self._login(user_by_email) else: # A user with the email returned by the OpenID provider # exists. As we don't trust the OpenID provider, we # demand that the user needs to login first. # # Note: We could store the successful OpenID # authentication in the session and assign it after # login. However probably more is gained if the # list of trusted OpenID providers is extended. h.flash( _("The email address %s which was returned by the " "OpenID provider already belongs to a different " "user account. Please login with that account " "or use the forgot password functionality, and " "add the OpenID in your user profile settings " "afterwards. Sorry for the inconvenience." % email), 'warning') redirect(h.base_url('/login')) try: forms.UniqueUsername(not_empty=True).to_python(user_name) formencode.All(validators.PlainText(not_empty=True), forms.UniqueUsername(), forms.ContainsChar()) except: session['openid_req'] = (info.identity_url, user_name, email) session.save() redirect(h.base_url('/openid/username')) user = self._create(user_name, email, info.identity_url) h.flash( _("Successfully created new user account %s" % user_name), 'success') self._login(user, register=True)
class User(models.base.BaseThing): email = validators.Email(not_empty=True, strip=True, messages={ 'noAt': u'这可不是一个正常的邮箱哦', 'empty': u'忘了填邮箱啦' }) username = formencode.All( validators.String(not_empty=True, strip=True, min=4, max=24, messages={ 'empty': u'用户名总得有一个吧', 'tooLong': u'这么长的用户名没有必要吧', 'tooShort': u'用户名长度不能少于4' }), validators.PlainText(messages={'invalid': u'用户名只能包含数字,字母和下划线'})) fullname = validators.String(not_empty=True, strip=True, max=12, messages={ 'empty': u'总得有个昵称吧', 'tooLong': u'这么长的昵称没有必要吧', }) password = validators.String(not_empty=True, messages={'empty': u'忘记设置密码了'}) def create(self): self.fullname = self.username self.created = time.time() if self.validate(): if User().find_by_username(self.username): self.errors = {'username': u'此用户名已被占用'} return if User().find_by_email(self.email): self.errors = {'email': u'此Email已被注册'} return if not self.password_confirm: self.errors = {'password_confirm': u'确认密码不能为空'} return if self.password != self.password_confirm: self.errors = {'password': u'两次密码输入不一致'} return invite_key = models.Invite_Key().find_by_hash(self.invite_key) if not invite_key: self.errors = {'invite_key': u'该邀请码不存在'} return if invite_key.used: self.errors = {'invite_key': u'该邀请码已被使用'} return del self.password_confirm del self.invite_key self.password = hash_password(self.password) user_id = self.save() signal(EVENTS['USER_CREATE']).send(self, invite_key_hash=invite_key.hash) return user_id def change_password(self, origin_password, password, password_confirm): if not origin_password: self.add_error(origin_password=u'当前密码不能为空') if not password: self.add_error(password=u'新密码不能为空') if not password_confirm: self.add_error(password_confirm=u'确认密码不能为空') if password != password_confirm: self.add_error(password_confirm=u'两次密码输入不一致') if self.errors: return False if hash_password(origin_password) != self.password: self.add_error(origin_password=u'当前密码不正确') return False self.password = hash_password(password) self.save() return self.saved def is_following(self, dest_user_id): return models.FollowShip( ).count_by_follower_user_id_and_followed_user_id( self.id, dest_user_id) def has_liked_photo(self, photo): return models.Photo_Like().count_by_user_id_and_photo_id( self.id, photo.id) @property def is_admin(self): return self.id == 1 @property def photo_count(self): return get_redis_client().hget(REDIS_KEY['USER_PHOTO_COUNT'], self.id) or 0 @property def liked_count(self): return get_redis_client().hget(REDIS_KEY['USER_LIKED_COUNT'], self.id) or 0 @property def likes_count(self): return get_redis_client().hget(REDIS_KEY['USER_LIKES_COUNT'], self.id) or 0 @property def following_count(self): return models.FollowShip().count_by_follower_user_id(self.id) @property def follower_count(self): return models.FollowShip().count_by_followed_user_id(self.id) @property def unused_invite_key_count(self): return models.Invite_Key().count_by_user_id_and_used(self.id, 0) @property def profile(self): if not getattr(self, '_profile'): profile = models.Profile().find_by_user_id(self.id) self._profile = profile return self._profile @property def left_upload_count(self): if self.is_admin: return 100 init_count = USER_LEVEL_PHOTOS_PER_WEEK[self.level] now = datetime.datetime.now() dt = now - datetime.timedelta(days=datetime.datetime.weekday(now)) start_week_timestamp = time.mktime( datetime.datetime.date(dt).timetuple()) created_count = models.Photo().where('created', '>', start_week_timestamp)\ .where('status', '=', 0)\ .where('user_id', '=', self.id)\ .count() return init_count - created_count @photo_like.connect def _photo_like(photo_like): """ re calculate user level here """ user = models.User().find(models.Photo().find( photo_like.photo_id).user_id) redis_client = get_redis_client() redis_client.hincrby(REDIS_KEY['USER_LIKED_COUNT'], user.id, 1) current_likes_count = redis_client.hget(REDIS_KEY['USER_LIKES_COUNT'], photo_like.user_id) or 0 redis_client.hset(REDIS_KEY['USER_LIKES_COUNT'], photo_like.user_id, int(current_likes_count) + 1) calculated_user_level = calculate_user_level(user) if calculated_user_level > user.level: redis_key = REDIS_KEY['USER_MESSAGE'].format(user_id=user.id) models.Invite_Key().gen_by_level(user, calculated_user_level, user.level) msg = u"{0}|恭喜你,成功升级到{1}".format( 'info', USER_LEVEL_CN[calculated_user_level]) redis_client.lpush(redis_key, msg) user.level = calculated_user_level user.save() @photo_unlike.connect def _photo_unlike(photo_like): """ re calculate user level here """ user = models.User().find(models.Photo().find( photo_like.photo_id).user_id) redis_client = get_redis_client() redis_client.hincrby(REDIS_KEY['USER_LIKED_COUNT'], user.id, -1) current_likes_count = redis_client.hget(REDIS_KEY['USER_LIKES_COUNT'], photo_like.user_id) or 0 redis_client.hset(REDIS_KEY['USER_LIKES_COUNT'], photo_like.user_id, int(current_likes_count) - 1) @photo_create.connect def _photo_create(photo): redis_client = get_redis_client() current_photo_count = redis_client.hget(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id) or 0 redis_client.hset(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id, int(current_photo_count) + 1) @photo_delete.connect def _photo_delete(photo): redis_client = get_redis_client() current_photo_count = redis_client.hget(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id) or 0 redis_client.hset(REDIS_KEY['USER_PHOTO_COUNT'], photo.user_id, int(current_photo_count) - 1)
class User(Model): __table__ = 'user' id = StringField(primary_key=True, ddl='varchar(32)', default=next_id) email = StringField(updatable=False, ddl='varchar(50)') password = StringField(ddl='varchar(50)') permission = IntegerField() name = StringField(ddl='varchar(50)') created_at = FloatField(updatable=False, default=time.time) vali_email = validators.Email(not_empty=True, strip=True, messages={ 'noAt': u'这可不是一个正常的邮箱', 'empty': u'邮箱不能爲空' }) vali_name = formencode.All( validators.String(not_empty=True, strip=True, min=4, max=24, messages={ 'empty': u'用户名不能为空', 'tooLong': u'这么长的用户名没有必要吧', 'tooShort': u'用户名长度不能少于4' }), validators.PlainText(messages={'invalid': u'用户名只能包含数字,字母和下划线'})) vali_password = validators.String(not_empty=True, messages={'empty': u'忘记设置密码了'}) vali_items = { 'email': vali_email, 'name': vali_name, 'password': vali_password } def validate(self): self.errors = {} for k, vali in self.vali_items.items(): try: vali.to_python(self[k]) except formencode.Invalid as e: self.errors[k] = e if self.errors: return False return True def create(self): self.created_at = time.time() if not self.validate(): return if User.find_first('where email = ?', self.email): self.errors = {'email': u'此email已被占用'} return if User.find_first('where name = ?', self.name): self.errors = {'name': u'此用戶名已被注冊'} return if not self.password_confirm: self.errors = {'password_confirm': u'确认密码不能为空'} return if self.password != self.password_confirm: self.errors = {'password': u'兩次密碼輸入不一致'} return self.password = hash_password(self.password) self.insert() return self.id def change_password(self, origin_password, password, password_confirm): if not origin_password: self.errors['origin_password'] = u'当前密码不能为空' if not password: self.errors['password'] = u'密码不能为空' if not password_confirm: self.errors['password_confirm'] = u'确认密码不能为空' if password != password_confirm: self.errors['password_confirm'] = u'两次密码不一致' if self.errors: return False self.password = hash_password(self.password) self.update()
class RoleSchema(BaseSchema): name = validators.PlainText() pretty_name = validators.String() comment = validators.String() display_order = validators.Int()
class UserCreate(Schema): username = v.PlainText(not_empty=True) name = v.UnicodeString(not_empty=True) description = v.UnicodeString(if_missing=None) password = v.PlainText(not_empty=True)
class UserDescribe(Schema): name = compound.All( v.UnicodeString(not_empty=True), v.PlainText(), ) description = v.UnicodeString(if_missing=None)
class OpenIDUsernameForm(formencode.Schema): login = formencode.All(validators.PlainText(), forms.UniqueUsername())
class LoginForm(formencode.Schema): username = validators.PlainText(not_empty=True) password = validators.PlainText(not_empty=True)
class OpenIDUsernameForm(formencode.Schema): login = formencode.All(validators.PlainText(not_empty=True), forms.UniqueUsername(), forms.ContainsChar())
class AddProcessRuleForm(formencode.Schema): allow_extra_fields = True process = formencode.All(validators.PlainText(not_empty=True)) check = formencode.All(validators.PlainText(not_empty=True)) metric_value = formencode.All(validators.Number(not_empty=True)) threshold = formencode.All(validators.Number(not_empty=True))
class AddServerRuleForm(formencode.Schema): allow_extra_fields = True metric = formencode.All(validators.PlainText(not_empty=True)) metric_value = formencode.All(validators.Number(not_empty=True)) threshold = formencode.All(validators.Number(not_empty=True))