def restpass(request): title = "Reset password" submitted_hmac = request.matchdict.get('hmac') user_id = request.matchdict.get('user_id') form = Form(request, schema=ResetPasswordForm) if 'form_submitted' in request.POST and form.validate(): user = Users.get_by_id(user_id) current_time = time.time() time_key = int(base64.b64decode(submitted_hmac[10:])) if current_time < time_key: hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', time_key), user.email).hexdigest()[0:10] if hmac_key == submitted_hmac[0:10]: #Fix me reset email, no such attribute email user.password = form.data['password'] DBSession.merge(user) DBSession.flush() request.session.flash( 'success; Password Changed. Please log in') return HTTPFound(location=request.route_url('login')) else: request.session.flash( 'warning; Invalid request, please try again') return HTTPFound(location=request.route_url('forgot_password')) action_url = request.route_url("reset_password", user_id=user_id, hmac=submitted_hmac) return { 'title': title, 'form': FormRenderer(form), 'action_url': action_url }
def view_task(request): story_id = request.matchdict['story_id'] story = DBSession.query(Story).get(story_id) task_id = request.matchdict['task_id'] task = DBSession.query(Task).get(task_id) times_spent = DBSession.query(TimeSpent.duration).filter( TimeSpent.task_id==task_id).all() form = Form(request, schema=TimeSpentSchema()) if request.method == 'POST' and form.validate(): time_spent = form.bind(TimeSpent()) time_spent.task_id = task_id time_spent.task = task DBSession.add(time_spent) DBSession.flush() return HTTPFound(location='/story/%s/task/%s' % (story_id, task_id)) return { 'story': story, 'story_id': story_id, 'task': task, 'task_id': task_id, 'times_spent': times_spent, 'renderer': FormRenderer(form), 'form': form, 'total_time_spent': str(sum_time_spent(times_spent)), 'user': get_user(request), }
def user_add(request): form = Form(request, schema=RegistrationSchema) if 'form.submitted' in request.POST and form.validate(): session = DBSession() username = form.data['username'] user = User(username=username, password=form.data['password'], name=form.data['name'], email=form.data['email']) session.add(user) headers = remember(request, username) redirect_url = route_url('main', request) return HTTPFound(location=redirect_url, headers=headers) login_form = login_form_view(request) return { 'form': FormRenderer(form), 'toolbar': toolbar_view(request), 'cloud': cloud_view(request), 'latest': latest_view(request), 'login_form': login_form, }
def login(request): message = None form = Form(request, schema=UserSchema()) if request.method == 'POST' and form.validate(): username = request.params['username'] password = request.params['password'] password_again = request.params['password_again'] if bool(password_again): if password == password_again: user = form.bind(User()) DBSession.add(user) DBSession.flush() user_id = user.id headers = remember(request, user.id) return HTTPFound(location='/', headers=headers) else: message = 'Passwords do not match.' else: user = DBSession.query(User).filter(User.username==username).first() if user and user.password == password: headers = remember(request, user.id) return HTTPFound(location='/', headers=headers) else: message = 'Username or password is incorrect.' return { 'message': message, 'form': form, 'renderer': FormRenderer(form), 'user': get_user(request), }
def ratings(self): form = Form(self.request, schema=UserRatingSchema) prefix = self.request.matchdict['prefix'] user = Users.get_by_path(prefix) title = 'Rate ' + user.fullname if 'form_submitted' in self.request.POST and form.validate(): if user.id == self.request.user.id: self.request.session.flash("danger; You can't rate yourself") return HTTPFound( location=self.request.route_url('profile', prefix=prefix)) if user.rating: for rating in user.rating: if rating.rater_id == self.request.user.id: self.request.session.flash( "warning; You have rated %s before" % user.fullname) return HTTPFound(location=self.request.route_url( 'profile', prefix=prefix)) rating = UserRating(rater_id=self.request.user.id, rated_id=user.id, rating=form.data['rating'], review=form.data['review']) DBSession.add(rating) DBSession.flush() self.request.session.flash("success; Success") return HTTPFound( location=self.request.route_url('profile', prefix=prefix)) self.request.session.flash("danger; An Error occured") return HTTPFound( location=self.request.route_url('profile', prefix=prefix))
def edit(self): user = self.request.user form = Form(self.request, schema=GallerySchema) gallery = DBSession.query(Gallery).get(self.request.matchdict['id']) roles = DBSession.query(Role).all() if form.validate(): gallery.modified = datetime.now() gallery.last_update_by = user.id gallery.title = form.data['title'] gallery.description = form.data['description'] gallery.gallery_date = form.data['gallery_date'] #Need to make an object exists validator temp_perms = [] for existing_gallery_permission in gallery.permission: DBSession.delete(existing_gallery_permission) for r_id in form.data['permissions']: temp_perms.append(GalleryPermission(gallery_id = gallery.id, role_id = r_id)) gallery.permission[:] = temp_perms return HTTPFound(self.request.route_url('gallery_view', id=gallery.id)) return {'request' : self.request, 'gallery' : gallery, 'roles' : roles, 'form_rend' : FormRenderer(form)}
def new(self): user = self.request.user form = Form(self.request, schema=GallerySchema) if form.validate(): #Generate a name for the new directory. Check if it exists. new_directory_name = None while not new_directory_name or (DBSession.query(Gallery).filter(Gallery.directory_name == new_directory_name).first()): new_directory_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(12)) gallery_directory = self.request.registry.settings['gallery.directory'] mkdir(path.join(gallery_directory, new_directory_name)) mkdir(path.join(gallery_directory, new_directory_name, 'raw')) mkdir(path.join(gallery_directory, new_directory_name, 'thumbs')) mkdir(path.join(gallery_directory, new_directory_name, 'web')) data = form.data.copy() data['directory_name'] = new_directory_name data['created'] = datetime.now() data['creator'] = user.id #temporary del data['permissions'] gallery = Gallery(**data) DBSession.add(gallery) DBSession.flush() return HTTPFound(self.request.route_url('gallery_view', id=gallery.id)) return {'request' : self.request, 'form_rend' : FormRenderer(form)}
def register_view(request): login = request.POST.get('login') form = Form(request, schema = RegisterForm) if request.method == 'POST' and form.validate(): new_user = User( username = form.data['login'], password = form.data['password'], group = 'viewer' ) DBSession.add(new_user) user_id = DBSession.query(User).\ filter(User.username == new_user.username).first().id headers = remember(request, user_id) path = os.path.join('./pyramid_app/static/', str(user_id)) if not os.path.exists(path): os.makedirs(path) return HTTPFound('/', headers = headers) else: return { 'render' : FormRenderer(form) }
def new_topic(request): ''' Create New Topic Render form and validate automatically. See Schema -> TopicSchema For understand. ''' form = Form(request,schema=TopicSchema) if form.validate(): topic = form.data['title'] author = form.data['author'] desc = form.data['description'] date = datetime.datetime.now() url = slugfy(topic) topic_tuple = {'title' : topic, 'url' : url, 'author': author, 'description': desc, 'topic_date':date.strftime("%d/%m/%Y"), } request.db['topic'].insert(topic_tuple) return HTTPFound(location='/') return render_to_response('templates/new_topic.html', {'form' : FormRenderer(form), 'count':count(request)}, request=request)
def login(self): if self.logged_in: self.request.session.flash('You are already connected!', queue='notice') return HTTPFound( location=self.request.route_url('home') ) self.c.pagename = 'Login' self.c.active_header_nav = 'tools' self.c.active_footer_nav = 'tools-login' params = self.request.params form = Form(self.request, schema=LoginForm, obj=params) if form.validate(): form.bind(params) #clear the cache for user User.by_username(params.get('username'), invalidate=True) user = User.by_username(params.get('username'), cache=None) if user: password = params.get('password') if user.password == User.pass_crypt(password)\ and user.status == 1: user.last_login_date = sa.func.now() self.request.session.flash(u'Welcome back %s !' % user.username, queue='success') headers = security.remember(self.request, user.username) return HTTPFound(location=self.request.route_url('home'), headers=headers) self.request.session.flash(u'Wrong username or password!', queue='notice') return { 'item': params, 'form': FormRenderer(form) }
def login_view(request): main_view = route_url('main', request) came_from = request.params.get('came_from', main_view) user = authenticated_userid(request) form = Form(request, schema=LoginSchema) if request.POST: if 'form.submitted' in request.POST: if form.validate(): username = form.data['username'] passphrase = form.data['passphrase'] if User.check_passphrase(username, passphrase): headers = remember(request, username) request.session.flash(u'Logged in successfully.') return HTTPFound(location=came_from, headers=headers) request.session.flash(u'Failed to login.') #return HTTPFound(location=came_from) return { 'title': not user and 'log in' or 'logged in', 'form': FormRenderer(form), 'loggedin': authenticated_userid(request), '_full': True }
def forgot_password_view(request): '''Forgotten password page''' form = Form(request, schema=ForgotPasswordSchema) if form.validate(): user = request.db.users.find_one({'email':form.data['email']}) if user: new_password = base64.b16encode(os.urandom(4)) mailer = request.registry['mailer'] office_email = request.registry.settings['office.email'] from_ = "%s <%s>" % ("Formative", office_email) body = """Your password was reset to: %s"""\ % new_password message = Message( subject='Your new password', sender=office_email, recipients=[form.data['email']], body=body, extra_headers = {"From": from_} ) mailer.send_immediately(message) change_password(user['email'], new_password, request.db) request.session.flash('Your new password was sent to you.', queue='info') else: request.session.flash('This email address is not recognized.', queue='error') return {"renderer":FormRenderer(form)}
def login_view(request): '''Login page''' referrer = request.session.get('referrer', '') if not referrer: referrer = request.referrer request.session['referrer'] = referrer login_url = request.resource_url(request.root, 'login') if referrer == login_url: referrer = '/' # never use the login form itself as referrer form = Form(request, schema=LoginSchema) if form.validate(): user_id = authenticate(form.data['email'], form.data['password'], request.db) if user_id: headers = remember(request, user_id) request.session.flash('Login successful.', queue='info') del request.session['referrer'] return HTTPFound(location = referrer, headers = headers) else: request.session.flash('Invalid email or password.', queue='error') return {"renderer":FormRenderer(form)}
def update_ticket(self): project = self.context.project ticket = self.context.ticket form = Form(self.request, schema=s.TicketSchema, obj=ticket) if form.validate(): form.bind(ticket) return HTTPFound(location=h.ticket_url(self.request, ticket))
def change_password(request): """Change user password.""" # Unpack. user = request.user notify = request.registry.notify # Validate the request. form = Form(request, schema=schema.ChangePassword, defaults={'failed': False}) location = get_redirect_location(request) if request.method == 'POST': if form.validate(): d = form.data user = authenticate_user(request, user.username, d['old_password']) if user: # Save new password to the db. user.password = model.encrypt(d['new_password']) model.save(user) # Notify that the password changed. notify(events.UserChangedPassword(request, user)) # Log the user out, so that a change of password will lock out # someone who has compromised the existing password. headers = forget(request) # Notify that the user is logged out. notify(events.UserLoggedOut(request, request.user)) # Redirect. return HTTPFound(location=location, headers=headers) else: form.errors['old_password'] = '******' form.data['next'] = location return {'renderer': FormRenderer(form), 'user': request.user}
def add_message(request): """ Add message receive an topic """ form = Form(request, schema=MessageSchema ) topic = request.matchdict['name'] if form.validate(): title = form.data['title'] author = form.data['author'] content = form.data['content'] topic_oid = topic slug = make_slug(title) d = { 'title' : title, 'author' : author, 'content':content, 'topic' : topic_oid, 'slug' : slug } request.db['Message'].insert(d) return HTTPFound(location='/topic/'+topic) return { 'form' : FormRenderer(form), 'topic' : topic }
def api_student_assignment_upload(request): conn=DBSession() validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\ title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\ description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空'))),\ uploadid=formencode.validators.Int(not_empty=False), assignmentid=formencode.validators.Int(not_empty=True)) form=Form(request,validators=validators,state=State(request=request)) student=conn.query(Student).filter(Student.userid==request.user.id).first() if form.validate(): try: assignment=conn.query(Assignment).filter(Assignment.id==form.data['assignmentid']).first() if form.data['uploadid'] and int(form.data['uploadid']): upload=conn.query(AssignmentUpload).filter(AssignmentUpload.id==int(form.data['uploadid'])).first() upload.title=form.data['title'] upload.fsfileid=form.data['fsfileid'] upload.description=form.data['description'] upload.updatetime=time.time() upload.studentid=student.id conn.flush() else: upload=AssignmentUpload() upload.assignmentid=form.data['assignmentid'] upload.title=form.data['title'] upload.fsfileid=form.data['fsfileid'] upload.createtime=time.time() upload.updatetime=time.time() upload.description=form.data['description'] upload.studentid=student.id conn.add(upload) conn.flush() return dict(return_url='/student/assignment/list') except Exception,e: log.debug(e) return dict(code=301,error=u'参数错误')
def update_personal(self): user = self.request.user form = Form(self.request, schema=PersonalSchema, obj=user) if 'personal_submitted' in self.request.POST and form.validate(): form.bind(user) DBSession.add(user) if form.data['prefix'] and form.data['prefix'] != user.prefix: user.prefix = create_path(form.data['prefix'], is_unique) DBSession.flush() if self.request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Successful </div>""" return Response(html) self.request.session.flash("success; Update successful") return HTTPFound(location=self.request.route_url("user_edit")) if self.request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Not Successful </div>""" return Response(html) self.request.session.flash("success; Update successful") return HTTPFound(location=self.request.route_url("user_edit"))
def export_key(self): self.require_verification() form = Form(self.request, schema=forms.PassphraseSchema) if 'form.submitted' in self.request.POST and form.validate(): with utils.db_session(self.dbmaker) as session: user = session.query(User).filter(User.username==self.username).first() key = session.query(Key).filter(Key.user_id==user.id, Key.name==self.key).first() pub = base64.b64decode(key.public_key) priv = base64.b64decode(key.private_key) priv = utils.decrypt(priv, pub, pub, form.data['passphrase']) filename = user.username + '.keypair.asc' content_type, encoding = mimetypes.guess_type(filename) logger.info('priv: %s', priv) with utils.tmpdir() as tmpd: tmp = os.path.join(tmpd, filename) with open(tmp, 'wb') as tmpf: tmpf.write('\n\n'.join((pub, priv))) tmpf.flush() response = FileResponse( tmp, request=self.request ) return response return dict( form=FormRenderer(form), username=self.username, key=self.key )
def motion_add(request): """create a new motion. 1. show new motion form 2. save to database after user submit """ # initialize the form to select all participants all_users = load_users() all_user_options = [(itm.id, itm.name) for itm in all_users] selected_users = [itm.id for itm in all_users] # add four blank options on new motion form form = Form(request, schema=MotionSchema, defaults=dict(participants = selected_users, options=["","","",""])) if form.validate(): title = form.data.get("title") desc = form.data.get("desc") options = form.data.get("options") users = form.data.get("participants") add_motion(title, desc, options, users) return HTTPFound(location=route_path('motion_list', request)) return dict(renderer=FormRenderer(form), all_user_options=all_user_options)
def api_mentor_assignment_add(request): conn=DBSession() validators=dict(fsfileid=formencode.validators.String(not_empty=True,min=16,messages=dict(empty=(u'文件不能为空' ))),\ title=formencode.validators.String(not_empty=True,messages=dict(empty=(u'标题不能为空'))),\ description=formencode.validators.String(not_empty=True,messages=dict(empty=(u'描述不能为空'))),\ duedate=formencode.validators.String(not_empty=True,messages=dict(empty=(u'截止时间不能为空'))), lessonid=formencode.validators.Int(not_empty=True), assignmentid=formencode.validators.Int(not_empty=False)) form=Form(request,validators=validators,state=State(request=request)) if form.validate(): try: lesson=conn.query(Lesson).filter(Lesson.id==form.data['lessonid'],Lesson.courseid.in_(\ conn.query(Course.id).filter(Course.mentorid.in_(\ conn.query(Mentor.id).filter(Mentor.userid==request.user.id))))).first() if form.data['assignmentid'] and int(form.data['assignmentid']): assignment=conn.query(Assignment).filter(Assignment.id==lesson.assignmentid).first() assignment.title=form.data['title'] assignment.fsfileid=form.data['fsfileid'] assignment.duedate=time.mktime(time.strptime(form.data['duedate'],'%Y-%m-%d')) assignment.description=form.data['description'] conn.flush() else: assignment=Assignment() assignment.title=form.data['title'] assignment.fsfileid=form.data['fsfileid'] assignment.duedate=time.mktime(time.strptime(form.data['duedate'],'%Y-%m-%d')) assignment.description=form.data['description'] conn.add(assignment) conn.flush() lesson.assignmentid=assignment.id conn.flush() return dict(return_url='/mentor/lesson/listbycourse?courseid='+str(lesson.courseid)) except Exception,e: log.debug(e) return dict(code=301,error=u'参数错误')
def band_add(request): form = Form(request, BandSchema) if 'form.submitted' in request.POST and not form.validate(): # form didn't validate request.session.flash('form does not validate!') if 'form.submitted' in request.POST and form.validate(): request.session.flash('form validated!') dbsession = DBSession() band_registrar = request.user if 'registrar_is_member' in form.data: request.session.flash( "reg_is_member: " + form.data['registrar_is_member']) band = Band( name=form.data['band_name'], homepage=form.data['band_homepage'], email=form.data['band_email'], registrar=request.user.username, registrar_id=request.user.id, ) dbsession.add(band) dbsession.flush() return HTTPFound(route_url('band_view', request, band_id=band.id)) return { 'viewer_username': authenticated_userid(request), 'form': FormRenderer(form) }
def user_add(request): form = Form(request, schema=RegistrationSchema) if 'form.submitted' in request.POST and form.validate(): session = DBSession() username=form.data['username'] user = User( username=username, password=form.data['password'], name=form.data['name'], email=form.data['email'] ) session.add(user) headers = remember(request, username) redirect_url = route_url('main', request) return HTTPFound(location=redirect_url, headers=headers) login_form = login_form_view(request) return { 'form': FormRenderer(form), 'toolbar': toolbar_view(request), 'cloud': cloud_view(request), 'latest': latest_view(request), 'login_form': login_form, }
def final_bet(request): player = request.authenticated_userid final_tip = Final.get_player_tip(player) if final_tip: request.session.flash(u'You already entered a final tip.') return HTTPFound(location=route_url('view_final_tip', request, player=player)) final_tip = Final(player) form = Form(request, schema=FinalBetSchema, obj=final_tip) if 'form.submitted' in request.POST and form.validate(): # verify, that the tip was entered on time if FINAL_DEADLINE < datetime.now(): return HTTPFound(location=route_url('too_late', request)) final_tip.d_team1 = form.data['d_team1'] final_tip.d_team2 = form.data['d_team2'] final_tip.d_score1 = form.data['d_score1'] final_tip.d_score2 = form.data['d_score2'] DBSession.add(final_tip) return HTTPFound(location=route_url('view_final_tip', request, player=player)) teams = [(team.d_id,team.d_name) for team in Team.get_all()] return { 'tip': final_tip, 'form': FormRenderer(form), 'teams': teams, 'navigation': navigation_view(request) }
def change_password(request): """Change user password.""" # Unpack. user = request.user notify = request.registry.notify # Validate the request. form = Form(request, schema=schema.ChangePassword, defaults={'failed': False}) location = get_redirect_location(request) if request.method == 'POST': if form.validate(): d = form.data user = model.authenticate(user.username, d['old_password']) if user: # Save new password to the db. user.password = model.encrypt(d['new_password']) model.save(user) # Notify that the password changed. notify(events.UserChangedPassword(request, user)) # Log the user out, so that a change of password will lock out # someone who has compromised the existing password. headers = forget(request) # Notify that the user is logged out. notify(events.UserLoggedOut(request, request.user)) # Redirect. return HTTPFound(location=location, headers=headers) else: form.errors['old_password'] = '******' form.data['next'] = location return {'renderer': FormRenderer(form), 'user': request.user}
def register(self): form = Form(self.request, schema=forms.RegistrationSchema) # Me add if 'form.submitted' in self.request.POST and form.validate(): username = form.data['username'] user = User(username=username, password=form.data['password'], name=form.data['name'], email=form.data['email'], created_at=time.time()) with utils.db_session(self.dbmaker) as session: userExist = session.query(User).filter( User.username == username).first() if not userExist: session.add(user) headers = remember(self.request, username) return HTTPFound( location=self.request.route_url('send_verify'), headers=headers) else: self.request.session.flash( u'This User is exist, please create another "Username" or "Email" !!!' ) return HTTPFound( location=self.request.route_url('register')) return dict(username=self.username)
def signup_post(request): dbsession = DBSession() settings = request.registry.settings form = Form(request, schema=schemas.Signup, obj=User()) if request.POST and form.validate(): if not validate_csrf(request): return HTTPUnauthorized("Not authorized") user = form.bind(User()) user.username = get_username(user.name, dbsession) user.password = func.sha1(user.password) cookie = facebook.get_user_from_cookie( request.cookies, settings["facebook.app.id"], settings["facebook.app.secret"] ) if cookie: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") user.fb_id = profile["id"] user.fb_profile_url = profile["link"] user.fb_access_token = cookie["access_token"] try: dbsession.add(user) dbsession.commit() headers = remember_me_header(request, user.email) redirect_url = route_url("create_profile", request) request.response_headerlist = headers return {"status": 1, "url": redirect_url} except IntegrityError: return {"errors": {"form": "Invalid Information"}} return {"errors": form.errors}
def linkcheck_add(request): form = Form(request, schema=LinkCheckSchema) redirect_url = request.route_url('linkchecks') if 'form.submitted' in request.POST and form.validate(): session = DBSession() url = form.data['url'] linkcheck = LinkCheck( url=url, root_url=form.data['root_url'], recursion_level=form.data.get('recursion_level'), active=form.data.get('active'), check_css=form.data.get('check_css'), check_html=form.data.get('check_html'), scan_virus=form.data.get('scan_virus'), warnings=form.data.get('warnings'), warning_size=form.data.get('warning_size'), anchors=form.data.get('anchors'), cookies=form.data.get('cookies'), cookiefile=form.data.get('cookiefile'), ignore_url=form.data.get('ignore_url'), no_follow_url=form.data.get('no_follow_url'), timeout=form.data.get('timeout'), pause=form.data.get('pause'), ) session.add(linkcheck) return HTTPFound(location=redirect_url) elif 'form.canceled' in request.POST: return HTTPFound(location=redirect_url) return { 'form': FormRenderer(form), }
def login(self): if self.logged_in: self.request.session.flash('You are already connected!', queue='notice') return HTTPFound(location=self.request.route_url('home')) self.c.pagename = 'Login' self.c.active_header_nav = 'tools' self.c.active_footer_nav = 'tools-login' params = self.request.params form = Form(self.request, schema=LoginForm, obj=params) if form.validate(): form.bind(params) #clear the cache for user User.by_username(params.get('username'), invalidate=True) user = User.by_username(params.get('username'), cache=None) if user: password = params.get('password') if user.password == User.pass_crypt(password)\ and user.status == 1: user.last_login_date = sa.func.now() self.request.session.flash(u'Welcome back %s !' % user.username, queue='success') headers = security.remember(self.request, user.username) return HTTPFound(location=self.request.route_url('home'), headers=headers) self.request.session.flash(u'Wrong username or password!', queue='notice') return {'item': params, 'form': FormRenderer(form)}
def __call__(self): if Permission.FILE & self.user.permissions != Permission.FILE: raise HTTPForbidden('You are not authorized to upload files.') self.breadcrumbs.add('Archives', self.request.route_url('archives')) self.breadcrumbs.add('Upload', self.request.route_url('archives_upload')) self.title = 'Upload File' form = Form(self.request, schema=FileSchema, defaults={'title': '', 'fileDate': '', 'description': ''}) if 'submit' in self.request.POST and form.validate(): token = self.request.POST.get('_csrf') if token is None or token != self.request.session.get_csrf_token(): raise HTTPForbidden('CSRF token is invalid or missing.') file = File(name=self._validated(FileSchema, form, 'title'), filename=self._validated(FileSchema, form, 'fileUpload').filename, description=self._validated(FileSchema, form, 'description'), submitTime=datetime.datetime.utcnow(), fileDate=form.data['fileDate'] or datetime.date.today(), ownerid=self.user.id, isDeleted=False) self.dbsession.add(file) self.dbsession.flush() here = os.path.dirname(__file__) thisFile = self._validated(FileSchema, form, 'fileUpload').file open(os.path.join(here, os.path.pardir, 'data', 'archive', str(file.id)), 'wb').write(\ thisFile.read()) return HTTPFound(location=self.request.route_url('archives_file', fileid=file.id)) return self.finalize({'form': form})
def contact_view(request): form = Form(request, schema=ContactSchema) if form.validate(): mailer = request.registry['mailer'] office_email = request.registry.settings['office.email'] from_ = "%s <%s>" % (form.data['name'], form.data['email']) message = Message( subject=form.data['subject'] + ' [formative.co.za]', sender=form.data['email'], recipients=[office_email], body=form.data['message'], extra_headers = {"From": from_} ) mailer.send_immediately(message) request.session.flash('Message sent.', queue='info') return HTTPFound(location="/") if form.errors: request.session.flash('There are errors in your form.', queue='error') return {"renderer":FormRenderer(form)}
def view_signup(self): """ Register view for new users that aren't signed up yet """ username = get_param(self.request, 'username') email = get_param(self.request, 'email') password = u'' # Create form by using schemas with validations form = Form(self.request, schema=SignUpSchema, state=State(request=self.request)) if form.validate(): username = self.request.params['username'] password = self.request.params['password'] email = self.request.params['email'] get_resource('users', self.request).add(username, password, email) get_resource('groups', self.request).add(username, group_names['member']) get_resource('groups', self.request).add(username, u'u:%s' % username) self.message = msg['succeed_add_user'] + " " + username _dict = { 'url': self.request.application_url + '/signup', 'username': username, 'email': email, 'password': password, 'form': FormRenderer(form), 'params': self.request.params, 'message': self.message } return dict(self.base_dict.items() + _dict.items())
def view_user_edit(self): """ View for editing a single user """ form = Form(self.request, schema=UserEditSchema, state=State(request=self.request)) self.error_message = None if form.validate(): password = self.request.params['password'] if self.context.validate_password(password): if self.request.params['new_password']: password = self.request.params['new_password'] self.message = 'Successfully saved' email = self.request.params['email'] self.context.edit(password, email) else: self.error_message = msg['password_invalid'] _dict = { 'username': self.context.username, 'form': FormRenderer(form), 'email': self.context.email, 'message': self.message, 'error_message': self.error_message } return dict(self.base_dict.items() + _dict.items())
def view_blog_edit(self): form = Form(self.request, schema=BlogCreateSchema, state=State(request=self.request)) blogname = get_param(self.request, 'blogname', self.context.name) text = get_param(self.request, 'text', self.context.description) image_url = get_param(self.request, 'image_url', self.context.image_url) if form.validate(): self.context.name = blogname self.context.description = text self.context.image_url = image_url self.message = msg['saved'] cbs = [p for p in self.request.params.keys() if u'checkbox' in p] # check all the checkbox-parameters and # parse them for cb in cbs: item = self.request.params[cb] self.context.remove(item) self.message = msg['items_removed'] _dict = { 'form': FormRenderer(form), 'message': self.message, 'blogname': blogname, 'text': text, 'image_url': image_url } return dict(self.base_dict.items() + _dict.items())
def login_view(request): """ Render the login form. Display an empty login form or check the submited credentials with the ones from the database. Add a success flash message, an userid in the cookies and redirect to the home page if the credentials are goods. Add an error flash message and display again the login form if the credentials are wrong. :param request: a ``pyramid.request`` object """ _ = request.translate form = Form(request, schema=LoginForm) if 'form_submitted' in request.params and form.validate(): username = request.params['username'] password = request.params['password'] if AuthUser.check_password(username, password): auth_user = AuthUser.get_by_username(username) headers = remember(request, auth_user.user_id) request.session.flash(_(u"Successful login."), 'success') return HTTPFound(location=request.route_path('home'), headers=headers) else: request.session.flash(_(u"Check your login credentials!"), 'error') return dict(renderer=FormRenderer(form))
class SearchView(BaseView): def __init__(self, request): BaseView.__init__(self, request) self.form = Form(self.request, schema=SearchFormAsin()) @view_config(route_name='search_form', renderer='templates/results.mako') def finder(self): items = [] if self.request.POST: data = self._validate_input() query_params, can_be_executed = query_preparator.prepare_params(data) if can_be_executed: items = item_getter.execute_query(query_params) else: self.request.session.flash('Please provide less than 5 asins') return dict(form=FormRenderer(self.form), items=items) def _validate_input(self): self.form.validate() if self.form.errors: self.request.session.flash('Please provide asins') return self.form.data
def __call__(self): if self.user.permissions & Permission.NEWS != Permission.NEWS: raise HTTPForbidden( 'You are not authorized to create news articles.') self.breadcrumbs.add('News', self.request.route_url('news')) self.breadcrumbs.add('Create', self.request.route_url('news_create')) self.title = 'Create News Article' form = Form(self.request, schema=NewsSchema, defaults={ 'title': u'', 'content': u'' }) if 'submit' in self.request.POST and form.validate(): token = self.request.POST.get('_csrf') if token is None or token != self.request.session.get_csrf_token(): raise HTTPForbidden('CSRF token is invalid or missing.') article = News(title=self._validated(NewsSchema, form, 'title'), content=self._validated(NewsSchema, form, 'content'), submitTime=datetime.datetime.utcnow(), lastModified=datetime.datetime.utcnow(), ownerid=self.user.id, isDeleted=False) self.dbsession.add(article) self.dbsession.flush() return HTTPFound(location=self.request.route_url( 'news_article', articleid=article.id)) return self.finalize({'form': form})
def edit(request): settings = load_settings() my = MySetting() for setting in settings: if setting.valuex: my.__dict__[setting.name] = setting.valuex else: my.__dict__[setting.name] = setting.value form = Form(request, schema=SettingSchema, obj=my) if form.validate(): form.bind(my) # persist model somewhere... for setting in settings: if setting.name == "motion_id_prefix": update_setting(setting.name, my.motion_id_prefix) if setting.name == "admin_password": update_setting(setting.name, my.admin_password) if setting.name == "user_password": update_setting(setting.name, my.user_password) if setting.name == "mail_sender": update_setting(setting.name, my.mail_sender) if setting.name == "mail_smtppassword": update_setting(setting.name, my.mail_smtppassword) if setting.name == "mail_template": update_setting(setting.name, "", my.mail_template) return HTTPFound(location=route_path("setting_edit", request)) return dict(renderer=FormRenderer(form))
def user_add(request): form = Form(request, schema=RegistrationSchema) if "form.submitted" in request.POST and form.validate(): session = DBSession() username = form.data["username"] user = User(username=username, password=form.data["password"], name=form.data["name"], email=form.data["email"]) session.add(user) headers = remember(request, username) redirect_url = request.route_url("main") return HTTPFound(location=redirect_url, headers=headers) login_form = login_form_view(request) return { "form": FormRenderer(form), "toolbar": toolbar_view(request), "cloud": cloud_view(request), "latest": latest_view(request), "login_form": login_form, }
def password_edit_view(request): """ Render the change password form page. Seek the database for the user datas based on user_id used in the route. If the user did not exist then add an error flash message and redirect to the user list. If the user exist then render an empty password form. If the form is validated then change the user password in the database and add success flash message. If the form is not valid, then display again the form with validation errors. :param request: a ``pyramid.request`` object """ _ = request.translate user_id = request.matchdict['user_id'] user = AuthUser.get_by_id(user_id) if not user: request.session.flash(_(u"This user did not exist!"), 'error') return HTTPFound(location=request.route_path('tools.user_list')) form = Form(request, schema=UserPasswordForm, obj=user) if 'form_submitted' in request.params and form.validate(): form.bind(user) DBSession.add(user) request.session.flash(_(u"Password updated."), 'success') return HTTPFound(location=request.route_path('tools.user_list')) return dict(renderer=FormRenderer(form))
def index(self): tenant = None errors = None success = None tenantForm = None contactForm = None try: tenantService = TenantService() tenant = tenantService.GetTenantDetails(self.TenantId) tenantForm = Form(self.request, schema=TenantSchema, obj=tenant) contactForm = vForm( request=self.request, prefix="tenantcontact-", schema=ContactSchema, obj=tenant.Contacts[0] ) valid = tenantForm.validate() valid = contactForm.validate() and valid if valid: tenantForm.bind(tenant) contactForm.bind(tenant.Contacts[0]) tenant.UpdatedBy = self.UserId tenant.UpdatedOn = datetime.utcnow() if tenantService.SaveTenant(tenant): success = "Company details saved successfully!" else: errors = "Error while saving Company details. Please try later." except Exception, e: log.info(e) errors = e.message
def crime_add(self): """ Crimes list for classification :return: """ # Gera formulário form = Form( self.request, defaults={}, schema=crime_schema.CrimeSchema() ) if form.validate(): log.debug("Dados do formulário: ") # Tenta instanciar o formulário no objeto crime_obj = Crimes( category_name=form.data.get('category_name'), category_pretty_name=form.data.get('category_pretty_name'), description=form.data.get('description'), date=datetime.datetime.now(), default_token=form.data.get('default_token'), tokens=form.data.get('tokens'), color=form.data.get('color') ) # persist model somewhere... crime_obj.create_crimes() return HTTPFound(location="/crime") return dict( renderer=FormRenderer(form), action=self.request.route_url('crime_add') )
def concept_save_view(request): if "concept" in request.POST: form = Form(request, schema=ConceptAnswersSchema()) if form.validate(): answers = [] concept_answers = form.bind(models.ConceptAnswer()) concept = concept_answers.concept concept_answers = concept_answers.concept_answer for concept_answer in concept_answers: answer = models.ConceptAnswer() answer.concept = concept answer.concept_answer = concept_answer answers.append(answer) with transaction.manager: models.DBSession.add_all(answers) else: print form.all_errors() print "NOT VALIDATED" return "I saw it" form = Form(request, schema=ConceptSchema()) concept_model = None if form.validate(): concept = form.bind(models.Concept()) #with transaction.manager: # models.DBSession.add(concept) concept_model = models.DBSession.merge(concept) models.DBSession.flush() return HTTPFound(request.route_url("concept_edit_page", page="Concepts",\ concept_id=concept_model.id)) else: print "Failed"
def signup(request): form = Form(request, schema=SignupSchema()) if form.validate(): user = form.bind(User()) DBSession.add(user) request.session.flash(u'Now you can sign in', 'success') return HTTPFound(location=request.route_url('signin')) return _response_dict(request, renderer=FormRenderer(form))
def __call__(self): if Permission.FILE & self.user.permissions != Permission.FILE: raise HTTPForbidden('You are not authorized to edit files.') self.breadcrumbs.add('Archives', self.request.route_url('archives')) try: file = self.dbsession.query(File).filter( File.id == self.request.matchdict['fileid']).one() except: return HTTPNotFound('No file found.') if file.isDeleted: return HTTPNotFound('No file found.') self.breadcrumbs.add( file.name, self.request.route_url('archives_file', fileid=file.id)) self.breadcrumbs.add( 'Edit', self.request.route_url('archives_edit', fileid=file.id)) self.title = 'Editing "' + file.name + '"' form = Form(self.request, EditFileSchema, defaults={ 'filename': file.filename, 'fileDate': file.fileDate.strftime('%m/%d/%Y'), 'title': file.name, 'description': file.description }) if 'edit' in self.request.POST and form.validate(): token = self.request.POST.get('_csrf') if token is None or token != self.request.session.get_csrf_token(): raise HTTPForbidden('CSRF token is invalid or missing.') file.filename = self._validated(EditFileSchema, form, 'filename') file.name = self._validated(EditFileSchema, form, 'title') file.fileDate = form.data['fileDate'] or datetime.date.today() file.description = self._validated(EditFileSchema, form, 'description') if hasattr(self.request.POST['fileUpload'], 'file'): here = os.path.dirname(__file__) thisFile = self._validated(FileSchema, form, 'fileUpload').file open(os.path.join(here, os.path.pardir, 'data', 'archive', str(file.id)), 'wb').write(\ thisFile.read()) file.submitTime = datetime.datetime.utcnow() self.dbsession.add(file) self.dbsession.flush() return HTTPFound(location=self.request.route_url('archives_file', fileid=file.id)) elif 'delete' in self.request.POST and 'deleteCheck' in self.request.POST: token = self.request.POST.get('_csrf') if token is None or token != self.request.session.get_csrf_token(): raise HTTPForbidden('CSRF token is invalid or missing.') file.isDeleted = True self.dbsession.add(file) self.dbsession.flush() return HTTPFound(location=self.request.route_url('archives')) return self.finalize({'form': form, 'file': file})
def listplans(request): plans = DBSession.query(Plans).order_by(Plans.id).all() form = Form(request, schema=PlanSchema()) if 'form_submitted' in request.POST and form.validate(): plan = form.bind(Plans()) DBSession.add(plan) DBSession.flush() return HTTPFound(location=request.route_url('list_plans')) return dict(form=FormRenderer(form), plans=plans, title="List of plans")
def product(context, request): form = Form(request, ReviewSchema) if 'review.submitted' in request.POST and form.validate(): review = form.bind(Review()) context.add_review(review) return { 'customers': Root.get_instance().customers, 'form': FormRenderer(form) }
def create_pad(request): form = Form(request, schema=PadSchema()) if form.validate(): pad = form.bind(Pad()) pad.user = get_current_user(request) DBSession.add(pad) request.session.flash(u'Pad is successfully created', 'success') return HTTPFound(location=request.route_url('notes')) return _response_dict(request, renderer=FormRenderer(form), pad=False)
def visit_view(request): if not request.is_xhr: return {"Message": "Invalid request"} form = Form(request, schema=VisitSchema()) if form.validate(): visit = form.bind(Visit()) with transaction.manager: DBSession.add(visit)
def reg(self): title = 'Registration' usertypes = userTypes() states = get_states() msg = '' form = Form(self.request, schema=Registration) if 'form_submitted' in self.request.POST and form.validate(): try: resp = self.request.POST['g-recaptcha-response'] except: self.request.session.flash( 'danger; Failed captcha due to slow network') return HTTPFound(location=self.request.route_url('reg')) recaptcha_r = requests.post( recaptcha_endpoint, dict(secret=buddy_settings('recaptcha_secret'), response=resp)) rdata = recaptcha_r.json() if rdata: if not rdata['success']: msg = 'Failed recaptcha, please solve again' return dict(form=FormRenderer(form), msg=msg, title=title, usertypes=usertypes, states=states) user = form.bind(Users()) if 'ref_email' in self.request.session: referrer = Users.get_by_email( self.request.session['ref_email']) if referrer: user.parent_id = referrer.id with transaction.manager: DBSession.add(user) user.prefix = create_path(user.user_fullname, is_unique) DBSession.flush() timestamp = time.time() + 3600 hmac_key = hmac.new( '%s:%s:%d' % (str(user.id), 'r5$55g35%4#$:l3#24&', timestamp), user.email).hexdigest()[0:10] time_key = base64.urlsafe_b64encode('%d' % timestamp) email_hash = '%s%s' % (hmac_key, time_key) user_regmail(self.request, user.id, user.email, email_hash) headers = buddy_remember(self.request, user, event='R') self.session.flash( "success;You should be receiving an email with a link to activate your " "account within 10 minutes. Doing so will let you post properties/blog on this website." ) return HTTPFound(location=self.request.route_url('account'), headers=headers) return dict(form=FormRenderer(form), title=title, usertypes=usertypes, msg=msg, states=states)
def user_add(request): form = Form(request, schema=UserSchema) if form.validate(): add_user(form.data.get("name"), form.data.get("email"), form.data.get("vote_weight")) return HTTPFound(location=route_path("user_list", request)) return dict(renderer=FormRenderer(form))
def login_view(request): """ Perform a 'login' by getting the service document from a sword repository. """ templatePath = 'templates/login.pt' config = load_config(request) form = Form(request, schema=LoginSchema) field_list = [ ('username', ), ('password', ), ] session = request.session # validate the form in order to compute all errors valid_form = form.validate() request['errors'] = form.all_errors() # Check for successful form completion if 'form.submitted' in request.POST and valid_form: if form.data['anonymous']: login = AnonymousSession() else: login = auth(form.data['service_document_url'], form.data['username'], form.data['password']) if login is None: request['errors'] = [ "Invalid username or password. Please try again.", ] response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request) # The login details are persisted on the session. if TESTING: session['login'] = TestingSession() else: session['login'] = login return HTTPFound(location=request.route_url('choose')) elif 'login' in session: return HTTPFound(location=request.route_url('choose')) # If not signed in, go to login page response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request)
def return_slideshare_upload_form(request): check_login(request) session = request.session redirect_to_google_oauth = False form = Form(request, schema=ImporterChoiceSchema) response = {'form':FormRenderer(form)} username = session['login'].username if form.validate(): original_filename = session['original_filename'] slideshow_id = None if form.data['importer'] == 'slideshare': slideshow_id = upload_to_slideshare("saketkc", original_filename) session['slideshare_id'] = slideshow_id if form.data['importer'] == 'google': if session.has_key('slideshare_oauth'): # RETURNING USER redirect_to_google_oauth = False oauth_token = session['slideshare_oauth']["oauth_token"] oauth_secret = session['slideshare_oauth']["oauth_secret"] guploader = GooglePresentationUploader() guploader.authentincate_client_with_oauth2(oauth_token,oauth_secret) guploader.upload(original_filename) guploader.get_first_revision_feed() guploader.publish_presentation_on_web() resource_id = guploader.get_resource_id().split(':')[1] session['google-resource-id'] = resource_id print "UPLOADING TO GOOGLE" else: print "NEW USER" redirect_to_google_oauth = True session['original-file-path'] = original_filename uploaded_filename = session['uploaded_filename'] if slideshow_id is not None: slideshare_details = get_details(slideshow_id) cnxml = """\ <featured-links> <!-- WARNING! The 'featured-links' section is read only. Do not edit below. Changes to the links section in the source will not be saved. --> <link-group type="supplemental"> <link url="""+ "\"" + uploaded_filename + "\""+""" strength="3">Download the original slides in PPT format</link>""" if slideshow_id is not None: cnxml += """<link url="""+ "\"" + get_slideshow_download_url(slideshare_details) + "\"" +""" strength="2">SlideShare PPT Download Link</link>""" cnxml += """\ </link-group> <!-- WARNING! The 'featured-links' section is read only. Do not edit above. Changes to the links section in the source will not be saved. --> </featured-links>""" session['cnxml'] += cnxml if redirect_to_google_oauth: raise HTTPFound(location=request.route_url('google_oauth')) raise HTTPFound(location=request.route_url('enhance')) return {'form' : FormRenderer(form),'conversion_flag': False, 'oembed': False}
def test_all_errors_with_list(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" form = Form(request, SimpleFESchema) form.errors = [u"Name is missing"] self.assert_(form.all_errors() == [u"Name is missing"])
def __init__(self, request): def formencode_translator(x): if not isinstance(x, TranslationString): x = fe_tsf(x) return gettext(x, request) self.form = Form(request, state=State(_=formencode_translator, request=request)) self.renderer = CiocFormRenderer(self.form) self._defaults = None