def post(self, slug): if self.request.user.is_anonymous() or not self.request.user.is_admin: return Unauthorized() page = SPage.get_by_key_name(slug) if page: form = SPageForm(page) else: form = SPageForm() if form.validate(self.request.form): try: SPage( key_name=slug, title=form["title"], meta_desc=form["meta_desc"], body=form["body"], body_html=markdown2html(form["body"]), ).put() self.request.notifications.success("Strona zapisana!") return redirect(self.request.base_url) except Exception, e: logging.exception("Static page save failed: " + str(e)) self.request.notifications.error("Zmian nie zapisano! Błąd zapisu.") return redirect(self.request.base_url)
def verify_email(self, sign, max_age=24 * 60 * 60): """ Verifies the email and redirects to home page. This is a method in addition to the activate method which activates the account in addition to verifying the email. """ try: unsigned = self._serializer.loads( self._signer.unsign(sign, max_age=max_age), salt='verification' ) except SignatureExpired: return self.build_response( 'The verification link has expired', redirect(url_for('nereid.website.home')), 400 ) except BadSignature: return self.build_response( 'The verification token is invalid!', redirect(url_for('nereid.website.home')), 400 ) else: if self.id == unsigned: self.email_verified = True self.save() return self.build_response( 'Your email has been verified!', redirect(url_for('nereid.website.home')), 200 ) else: return self.build_response( 'The verification token is invalid!', redirect(url_for('nereid.website.home')), 400 )
def add_to_cart(cls): """ Adds the given item to the cart if it exists or to a new cart The form is expected to have the following data is post quantity : decimal product : integer ID action : set (default), add Response: 'OK' if X-HTTPRequest Redirect to shopping cart if normal request """ form = AddtoCartForm(request.form) if request.method == "POST" and form.validate(): cart = cls.open_cart(create_order=True) action = request.values.get("action", "set") if form.quantity.data <= 0: flash(_("Be sensible! You can only add real quantities to cart")) return redirect(url_for("nereid.cart.view_cart")) cls._add_or_update(cart.sale.id, form.product.data, form.quantity.data, action) if action == "add": flash(_("The product has been added to your cart"), "info") else: flash(_("Your cart has been updated with the product"), "info") if request.is_xhr: return jsonify(message="OK") return redirect(url_for("nereid.cart.view_cart"))
def add(cls): """ Adds a contact mechanism to the party's contact mechanisms """ form = cls.get_form() if form.validate_on_submit(): cls.create( [ { "party": request.nereid_user.party.id, "type": form.type.data, "value": form.value.data, "comment": form.comment.data, } ] ) if request.is_xhr: return jsonify({"success": True}) return redirect(request.referrer) if request.is_xhr: return jsonify({"success": False}) else: for field, messages in form.errors: flash("<br>".join(messages), "Field %s" % field) return redirect(request.referrer)
def dinge_aendern(request): if request.method != 'POST': return redirect('/helfer') userid = request.session['userid'] new_email = request.form.get('email') new_mobile = request.form.get('mobile') want_shirt = request.form.get('want_participant_shirt') == "on" old_want_shirt = db.select('SELECT want_participant_shirt FROM person WHERE id=?', (userid,)) if len(old_want_shirt) != 1: ## this should never happen, if the @require_login works as expected ## (i.e. if you ever trigger this assertion, go fix @require_login) assert False old_want_shirt= old_want_shirt[0]['want_participant_shirt'] ## XXX: this feels redundant, but also sql-injection-exploitable if ## shortened too much.. if config.shirt_stuff_changeable: db.update('''UPDATE person SET email=?,mobile=?,want_participant_shirt=? WHERE id=?''', (new_email, new_mobile, want_shirt, userid)) else: db.update('''UPDATE person SET email=?,mobile=? WHERE id=?''', (new_email, new_mobile, userid)) return redirect('/helfer/%d' % (userid,))
def topic(request, id, slug=None): """Shows a topic.""" topic = Topic.query.eagerposts().get(id) # if the topic id does not exist or the topic is from a different # language, we abort with 404 early if topic is None or topic.locale != request.view_lang: raise NotFound() # make sure the slug is okay, otherwise redirect to the real one # to ensure URLs are unique. if slug is None or topic.slug != slug: return redirect(url_for(topic)) # deleted posts cannot be seen by people without privilegs if topic.is_deleted and not (request.user and request.user.is_moderator): raise Forbidden() # a form for the replies. form = ReplyForm(topic) if request.method == 'POST' and form.validate(): reply = form.create_reply() session.commit() request.flash(_(u'Your reply was posted.')) return redirect(url_for(reply)) # pull in the votes in a single query for all the posts related to the # topic so that we only have to fire the database once. if request.is_logged_in: request.user.pull_votes(topic.posts) return render_template('kb/topic.html', topic=topic, reply_form=form.as_widget())
def add_to_cart(cls): """ Adds the given item to the cart if it exists or to a new cart The form is expected to have the following data is post quantity : decimal product : integer ID action : set (default), add Response: 'OK' if X-HTTPRequest Redirect to shopping cart if normal request """ form = AddtoCartForm() if form.validate_on_submit(): cart = cls.open_cart(create_order=True) action = request.values.get('action', 'set') if form.quantity.data <= 0: flash( _('Be sensible! You can only add real quantities to cart')) return redirect(url_for('nereid.cart.view_cart')) cart._add_or_update(form.product.data, form.quantity.data, action) if action == 'add': flash(_('The product has been added to your cart'), 'info') else: flash(_('Your cart has been updated with the product'), 'info') if request.is_xhr: return jsonify(message='OK') return redirect(url_for('nereid.cart.view_cart'))
def add_to_cart(cls): """ Adds the given item to the cart if it exists or to a new cart The form is expected to have the following data is post quantity : decimal product : integer ID action : set (default), add Response: 'OK' if X-HTTPRequest Redirect to shopping cart if normal request """ form = AddtoCartForm() if form.validate_on_submit(): cart = cls.open_cart(create_order=True) action = request.values.get('action', 'set') if form.quantity.data <= 0: flash( _('Be sensible! You can only add real quantities to cart') ) return redirect(url_for('nereid.cart.view_cart')) cart._add_or_update( form.product.data, form.quantity.data, action ) if action == 'add': flash(_('The product has been added to your cart'), 'info') else: flash(_('Your cart has been updated with the product'), 'info') if request.is_xhr: return jsonify(message='OK') return redirect(url_for('nereid.cart.view_cart'))
def magic_login(self, sign, max_age=5 * 60): """ Let the user log in without password if the token is valid (less than 5 min old) """ try: unsigned = self._serializer.loads(self._signer.unsign( sign, max_age=max_age), salt='magic-login') except SignatureExpired: return self.build_response( 'This link has expired', redirect(url_for('nereid.checkout.sign_in')), 400) except BadSignature: return self.build_response( 'Invalid login link', redirect(url_for('nereid.checkout.sign_in')), 400) else: if not self.id == unsigned: current_app.logger.debug('Invalid link') abort(403) login_user(self.load_user(self.id)) # TODO: Set this used token as expired to prevent using # it more than once return self.build_response( 'You have been successfully logged in', redirect(url_for('nereid.website.home')), 200)
def application(request): try: adapter = predefined_urls.bind_to_environ(request.environ) endpoint, values = adapter.match() return handle_request(endpoint, request, **values) except NotFound: redir = find_redirect(request.path) if redir: return redirect(redir.new_path, code=redir.code) #print "Request path: " + request.path if request.path[-1] != '/': return redirect(request.path + '/', code=301) url_map = find_url_map(request.path) if url_map: return handle_request('pages.main', request, url_map) # Log this request in the 404 log and display not found page log_404(request) return handle_request('not_found.main', request) except: log_exception(request) return handle_request('exception.main', request) finally: session.remove()
def add(request, key=None, type=FILE): to = key # lame but it does the trick for now if type == FOLDER: form = FolderForm(request.form) else: form = FileForm(request.form) if request.method == "POST" and form.validate(): if len(form.slug.data) < 1: form.slug.data = slugify(form.name.data) if type == FOLDER: file = File.add(to=to,type=type, name=form.name.data, slug=form.slug.data, breadcrumb=form.breadcrumb.data, state=form.state.data, active=form.active.data, author=users.get_current_user(), updated=datetime.now()) elif type == FILE: file = request.files.get('file') data = db.Blob(file.read()) file = File.add(to=to,type=type, name=form.name.data, slug=form.slug.data, breadcrumb=form.breadcrumb.data, state=form.state.data, active=form.active.data, author=users.get_current_user(), updated=datetime.now(), content_type=file.content_type, data=data, size=len(data)) if form.save.data is True: return redirect(url_for('nut:files/list'), 301) if form.cont.data is True: return redirect(url_for('nut:files/edit', key=file.key()), 301) return render_template('app:files/form.html', form=form)
def application(request): try: adapter = predefined_urls.bind_to_environ(request.environ) endpoint, values = adapter.match() return handle_request(endpoint, request, **values) except NotFound: redir = find_redirect(request.path) if redir: return redirect(redir.new_path, code=redir.code) #print "Request path: " + request.path if request.path[-1] == '/': request_path = request.path.rstrip('/'); return redirect(request_path, code=301) url_map = find_url_map(request.path) if url_map: return handle_request('pages.main', request, url_map) # Log this request in the 404 log and display not found page if request.path not in [ "/wp-login.php", "/apple-touch-icon-precomposed.png", "/plus/mytag_js.php", "/apple-touch-icon-120x120-precomposed.png", "/apple-touch-icon-120x120.png", "/blog/wp-json/wp/v2/posts", "/blog/wp-json/wp/v2/users", "/ads.txt", "/plus/ad_js.php", "/apple-touch-icon-152x152-precomposed.png", "/apple-touch-icon-152x152.png", "/xmlrpc.php", "/utility/convert/data/config.inc.php", "/plus/download.php", "/config/AspCms_Config.asp", "/plus/mytag_j.php", "/plus/moon.php", "/data/img/css/xianf.ASP", "/bbs/utility/convert/data/config.inc.php", "/plus/bakup.hp", "/dxyylc/md5.aspx", "/plus/90sec.php", "/plus/laobiao.php", "/plus/e7xue.php", "/_s_/dyn/SessionState_ping", "/phpmyadmin", "/dxyylc/md5.php", "/browserconfig.xml", "/include/ckeditor/plugins/pagebreak/images/inCahe.php", "/include/code/mp.php", "/plus/mybak.php", "/install/m7lrv.php", "/weki.php", "/wordpress", "/wp", "/include/helperss/filter.helpear.php", "/templets/plus/sky.php", "/install/modurnlecscache.php", "/plus/xsvip.php", "/plus/myjs.php", "/include/data/fonts/uddatasql.php", "/plus/bakup.php", "/plus/av.php", "/data/cache/asd.php", "/lang/cn/system.php", "/data/data/index.php", "/sitemap/templates/met/SqlIn.asp", "/utility/convert/include/rom2823.php", "/xiaolei.php", "/data/conn/config.php", "/plus/mycak.php", "/plus/x.php", "/search.php", "/weki.asp", "/install/md5.php", "/Somnus/Somnus.asp", "/md5.asp", "/plus/read.php", "/plus/backup.php", "/plus/service.php", "/plus/spider.php", "/book/story_dod_hjkdsafon.php", "/plus/zdqd.php", "/data/s.asp", "/plus/90000.php" ]: log_404(request) return handle_request('not_found.main', request) except: log_exception(request) return handle_request('exception.main', request) finally: session.remove()
def login_box(request): from kay.auth import login next = unquote_plus(request.values.get("next")) owned_domain_hack = request.values.get("owned_domain_hack") message = "" form = LoginBoxForm() if request.method == "POST": if form.validate(request.form): result = login(request, user_name=form.data['user_name'], password=form.data['password']) if result: if owned_domain_hack == 'True': original_host_url = unquote_plus( request.values.get("original_host_url")) url = original_host_url[:-1] + url_for("auth/post_session") url += '?' + url_encode({ 'session_id': result.key().name(), 'next': next }) return redirect(url) else: return redirect(next) else: message = _("Failed to login.") return render_to_response("auth/loginform.html", { "form": form.as_widget(), "message": message })
def reset_with_token(token): try: password_reset_serializer = URLSafeTimedSerializer( app.config['SECRET_KEY']) email = password_reset_serializer.loads(token, salt='password-reset-salt', max_age=3600) except: flash('The password reset link is invalid or has expired.', 'error') return redirect(url_for('do_login')) form = PasswordForm(request.form) if request.method == "POST" and form.validate(): try: user = db.session.query(User).filter(User.email == email).first() except: flash('Invalid email address!', 'error') return redirect(url_for('do_login')) user.password = sha256_crypt.encrypt((str(form.password.data))) db.session.commit() flash('Your password has been updated!', 'success') return redirect(url_for('do_login')) return render_template('reset_password_with_token.html', form=form, token=token)
def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success', name=user)) else: user = request.args.get('nm') return redirect(url_for('success', name=user))
def passwort_aendern(request): if request.method != 'POST': return redirect('/helfer') old_pw = request.form.get('old_pw') new_first = request.form.get('new_first') new_second = request.form.get('new_second') if not check_login_credentials(request.session['username'], old_pw): error_long = u"Das alte Passwort, das du eingegeben hast, stimmt nicht. Du kannst dein Passwort auch bei einem Admin ändern lassen, frag am besten per Mail bei %s" % config.admin_email return render_template('error.xml', error_short=u"altes passwort falsch", error_long=error_long, session=request.session) if new_first != new_second: error_long = u"Die beiden neuen Passwörter sind nicht gleich. Du hast dich sehr wahrscheinlich vertippt. Du kannst dein Passwort auch bei einem Admin ändern lassen, frag am besten per Mail bei %s" % config.admin_email return render_template('error.xml', error_short=u"Neue Passwörter sind unterschiedlich", error_long=error_long, session=request.session) crypted = sha256_crypt.encrypt(new_first) db.update('UPDATE person SET password=? WHERE id=?', (crypted, request.session['userid'])) return redirect('/redirect/my_page')
def login_box(request): from kay.auth import login next = unquote_plus(request.values.get("next")) owned_domain_hack = request.values.get("owned_domain_hack") message = "" form = LoginBoxForm() if request.method == "POST": if form.validate(request.form): result = login(request, user_name=form.data['user_name'], password=form.data['password']) if result: if owned_domain_hack == 'True': original_host_url = unquote_plus( request.values.get("original_host_url")) url = original_host_url[:-1] + url_for("auth/post_session") url += '?' + url_encode({'session_id': result.key().name(), 'next': next}) return redirect(url) else: return redirect(next) else: message = _("Failed to login.") return render_to_response("auth/loginform.html", {"form": form.as_widget(), "message": message})
def login(request): from kay.auth import login if settings.AUTH_POST_LOGIN_SUCCESS_DEFAULT_URL: next = unquote_plus(request.values.get("next", settings.AUTH_POST_LOGIN_SUCCESS_DEFAULT_URL)) else: next = unquote_plus(request.values.get("next", "/")) owned_domain_hack = request.values.get("owned_domain_hack") message = "" form = LoginForm() if request.method == "POST": if form.validate(request.form): result = login(request, user_name=form.data['user_name'], password=form.data['password']) if result: if owned_domain_hack == 'True': original_host_url = unquote_plus( request.values.get("original_host_url")) url = original_host_url[:-1] + url_for("auth/post_session") url += '?' + url_encode({'session_id': result.key().name(), 'next': next}) return redirect(url) else: return redirect(next) else: message = _("Failed to login successfully with those credentials, try another or click the 'Forgot Password' link below.") return render_to_response("auth/loginform.html", {"form": form.as_widget(), "message": message})
def config_rss(): user = request.user if user.anon: flash("Du musst dich erst einloggen.") return redirect( url_for("pybble.login.do_login", next=url_for("pybble.rss.config_rss"))) form = RSSForm(request.form, prefix="rss") if request.method == 'POST' and form.validate(): user.feed_age = int(form.age.data) if form.new_id.data or not user.feed_pass: user.feed_pass = unicode(random_string(30)) flash(u"Gespeichert.", True) return redirect(url_for("pybble.views.mainpage")) elif request.method == 'GET': form.age.data = str(user.feed_age) new_feed = not user.has_trackers return render_template('rssconfig.html', form=form, title_trace=["RSS-Einstellungen"], new_feed=new_feed)
def vote(request, post): """Votes on a post.""" # TODO: this is currently also fired as GET if JavaScript is # not available. Not very nice. post = Post.query.get(post) if post is None: raise NotFound() # you cannot cast votes on deleted shit if post.is_deleted: message = _(u"You cannot vote on deleted posts.") if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) # otherwise val = request.args.get("val", 0, type=int) if val == 0: request.user.unvote(post) elif val == 1: # users cannot upvote on their own stuff if post.author == request.user: message = _(u"You cannot upvote your own post.") if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) # also some reputation is needed if not request.user.is_admin and request.user.reputation < settings.REPUTATION_MAP["UPVOTE"]: message = _(u"In order to upvote you " u"need at least %d reputation") % settings.REPUTATION_MAP["UPVOTE"] if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) request.user.upvote(post) elif val == -1: # users need some reputation to downvote. Keep in mind that # you *can* downvote yourself. if not request.user.is_admin and request.user.reputation < settings.REPUTATION_MAP["DOWNVOTE"]: message = ( _(u"In order to downvote you " u"need at least %d reputation") % settings.REPUTATION_MAP["DOWNVOTE"] ) if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) request.user.downvote(post) else: raise BadRequest() session.commit() # standard requests are answered with a redirect back if not request.is_xhr: return redirect(url_for(post)) # others get a re-rendered vote box box = get_macro("kb/_boxes.html", "render_vote_box") return json_response(html=box(post, request.user))
def do_logout(): if request.user.anon: flash(u'Du warst nicht eingeloggt', False) return redirect(request.args.get("next",None) or url_for("pybble.views.mainpage")) else: logged_out() flash(u'Du hast dich erfolgreich abgemeldet.', True) return redirect(url_for("pybble.views.mainpage"))
def order(request, order_key): order_obj = Order.get(order_key) if not order_obj: redirect(url_for('admin/orders_lists')) gifts = [] for gift in order_obj.items: gifts.append(OrderItem.get(gift)) return render_to_response('admin/order.html', {'order':order_obj, 'gifts':gifts})
def do_register(): try: form = RegistrationForm(request.form) if request.method == "POST" and form.validate(): print('validating was a success') username = form.username.data company_name = form.company_name.data email = form.email.data password = sha256_crypt.encrypt((str(form.password.data))) # check by username if a user is new or existent... user_exists = sqlsession.query(User).filter( User.username == username).first() # ... if it exists, notify the user if user_exists: error = "That username is already taken, please choose another" return render_template('register.html', form=form, error=error) # ..else, create the new user and company else: print('success, user does not exist yet') sqlsession.add(CompanyVN(company_name=company_name)) the_company = sqlsession.query(CompanyVN).order_by( CompanyVN.id.desc()).first() new_user = User(username=username, company_name=company_name, email=email, password=password, company_id=the_company.id) sqlsession.add(new_user) sqlsession.commit() # flash('thanks for registering') welcome_text = 'Hi, you created and account with us at https://interactivenarrator.science.uu.nl' send_email('Your account with Interactive Narrator', email, welcome_text) session['logged_in'] = True session['username'] = username if session['username'] == 'admin': return redirect(url_for('admin_dashboard')) else: return redirect(url_for('show_dash')) else: return render_template("register.html", form=form) except Exception as e: print('an exception occured', e) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) # make sure the session is reverted if an error occured sqlsession.rollback() error = 'Sorry, we could not register you' return render_template('register.html', form=form, error=error)
def add_to_cart(cls): """ Adds the given item to the cart if it exists or to a new cart The form is expected to have the following data is post quantity : decimal product : integer ID action : set (default), add Response: 'OK' if X-HTTPRequest Redirect to shopping cart if normal request """ Product = Pool().get('product.product') form = AddtoCartForm() if form.validate_on_submit(): cart = cls.open_cart(create_order=True) action = request.values.get('action', 'set') if form.quantity.data <= 0: message = _( 'Be sensible! You can only add real quantities to cart') if request.is_xhr: return jsonify(message=unicode(message)), 400 flash(message) return redirect(url_for('nereid.cart.view_cart')) if not Product(form.product.data).template.salable: message = _("This product is not for sale") if request.is_xhr: return jsonify(message=unicode(message)), 400 flash(message) return redirect(request.referrer) sale_line = cart.sale._add_or_update( form.product.data, form.quantity.data, action ) # Validate that product availability in inventory is not less than # warehouse quantity sale_line.validate_for_product_inventory() sale_line.save() if action == 'add': message = _('The product has been added to your cart') else: message = _('Your cart has been updated with the product') if request.is_xhr: return jsonify( message=unicode(message), line=sale_line.serialize(purpose='cart') ), 200 flash(message, 'info') return redirect(url_for('nereid.cart.view_cart'))
def get_quickmark(request, quickmark): print "quickmark=[" + quickmark +"]" if quickmark == '': return redirect('/static/browse.html') bm = tuple(app.db.get_bookmarks(quickmark = quickmark)) if not len(bm): raise NotFound return redirect(bm[0]['url'])
def redirector(request): if request.form.get('helfer_id'): return redirect('/helfer/' + request.form.get('helfer_id')) elif request.form.get('schicht_id'): return redirect('/schicht/' + request.form.get('schicht_id')) elif request.form.get('station_id'): return redirect('/station/' + request.form.get('station_id')) else: return redirect('/')
def add(request, key): """ add a new page to the set""" to = key # lame but it does the trick for now blocks = [] form = PageForm(request.form) add = BlockAddForm(request.form, prefix='_add') form.layout.choices = Layout.get_key_to_path() if request.method == 'POST': # some logic to find __block elements. for key in request.form: if key.startswith('__block:'): name = key.split('__',2)[1][6:] blocks.append((name, BlockForm(request.form, prefix='__block:%s__' % name))) if add.validate() and add.add.data is True: blocks.append((add.name.data, BlockForm(prefix='__block:%s__' % add.name.data))) add = BlockAddForm(prefix='_add') elif form.validate() and all([block.validate() for _, block in blocks]): name = form.name.data slug = form.slug.data breadcrumb = form.breadcrumb.data state = form.state.data active = form.active.data if len(slug) < 1: slug = slugify(name) author = users.get_current_user() updated = datetime.now() description = form.description.data keywords = form.keywords.data body = form.body.data content_type = form.content_type.data if form.layout.data == 'Layout:None': layout = None else: layout = Layout.get(form.layout.data.split(':',1)[1]) page = Node.add(to=to, name=name, slug=slug, breadcrumb=breadcrumb, updated=updated, author=author, body=body, description=description, keywords=keywords, layout=layout, content_type=content_type, state=state, active=active, type=PAGE) done = [] try: for name, block in blocks: b = Block(node=page, name=name, body=block.body.data) b.put() done.append(b) except: db.delete(done) Node.drop(page.get_key()) if form.save.data is True: return redirect(url_for('nut:pages/list_pages'), 301) if form.cont.data is True: return redirect(url_for('nut:pages/edit', key=page.get_key()), 301) return render_template('app:pages/form.html', form=form, add=add, blocks=blocks)
def add_to_cart(cls): """ Adds the given item to the cart if it exists or to a new cart The form is expected to have the following data is post quantity : decimal product : integer ID action : set (default), add Response: 'OK' if X-HTTPRequest Redirect to shopping cart if normal request """ Product = Pool().get('product.product') form = AddtoCartForm() if form.validate_on_submit(): cart = cls.open_cart(create_order=True) action = request.values.get('action', 'set') if form.quantity.data <= 0: message = _( 'Be sensible! You can only add real quantities to cart') if request.is_xhr: return jsonify(message=unicode(message)), 400 flash(message) return redirect(url_for('nereid.cart.view_cart')) if not Product(form.product.data).salable: message = _("This product is not for sale") if request.is_xhr: return jsonify(message=unicode(message)), 400 flash(message) return redirect(request.referrer) sale_line = cart.sale._add_or_update(form.product.data, form.quantity.data, action) # Validate that product availability in inventory is not less than # warehouse quantity sale_line.validate_for_product_inventory() sale_line.save() cart_updated.send(cart) if action == 'add': message = _('The product has been added to your cart') else: message = _('Your cart has been updated with the product') if request.is_xhr: return jsonify(message=unicode(message), line=sale_line.serialize(purpose='cart')), 200 flash(message, 'info') return redirect(url_for('nereid.cart.view_cart'))
def search_post(request): form=SearchForm(action=url_for('core/search_post')) words=None if request.method=='POST' and form.validate(request.form): words=form['words'].strip() words=words.replace('/',' ') if words is None: return redirect(url_for('core/index')) else: return redirect(url_for('core/search',words=words,list_per_page=24,page_index=0))
def inner(request, *args, **kwargs): if not request.user.activated: if request.user.is_anonymous(): if request.is_xhr: raise Forbidden else: return redirect(create_login_url(request.url)) return redirect(create_login_url(request.url)) else: return func(request, *args, **kwargs)
def index(): if user.is_authed(): return redirect(url_for("user_frontpage")) if institution.is_authed(): return redirect(url_for("institution_frontpage")) if admin.is_authed(): return Response("admin") response = Response() template_response("/pages/frontpage.mako", response) return response
def price_uplader(request): upload_files = get_uploads(request, 'file') if not len(upload_files): return redirect(url_for('admin/add_price')) blob_info = upload_files[0] bl = BlobInfo.get(blob_info.key()) filename = os.path.basename(bl.filename.replace('\\','/')) price = Price(name=filename, file_key=str(blob_info.key()), length=blob_info.size) price.put() return redirect(url_for('admin/prices'))
def deleteme(request): """ Remove the currently logged in user from our database and log them out. Privacy, you know? Don't request this casually :) """ if (not (request.user.is_anonymous())): logout = users.create_logout_url( "/" ) db.delete(Token.gql( "WHERE user = :1", str(request.user) ).get()) return redirect( logout ) else: return redirect( "/" )
def post(self): if self.form.validate(self.request.form): try: self.form.save() cache_set(self.request.user, 'gfcu', self.request.user.key().name()) self.request.notifications.success('Zmiany zapisane!') return redirect(url_for('gfcaccount/index')) except Exception, e: logging.exception('Account edit save failed: ' + str(e)) self.request.notifications.error('Zmian nie zapisano! Błąd zapisu, spróbuj później...') return redirect(url_for('gfcaccount/index'))
def add_folder(request): form = FolderForm(request.form) if request.method == 'POST' and form.validate(): layout = Layout.add(name=form.name.data, slug=slugify(form.name.data), author=users.get_current_user(), type=FOLDER) if form.save.data is True: return redirect(url_for('nut:layouts/list'), 301) if form.cont.data is True: return redirect(url_for('nut:layouts/edit', key=layout.get_key()), 301) return render_template('app:layouts/form.html', form=form)
def post(self): if self.form.validate(self.request.form): self.request.session['code'] = self.form['code'] self.request.session['message'] = self.form['message'] if self.request.user.is_anonymous(): callback = url_for('core/post', _external=True) return redirect(create_login_url(callback)) else: tweet = save_tweet(self.request) post_tweet(self.request, tweet) return redirect(url_for_tweet(tweet)) return self.get()
def unban_user(request, user): """Unbans a given user.""" user = User.query.filter_by(username=user).first() if user is None: raise NotFound() next = request.next_url or url_for('admin.bans') if not user.is_banned: request.flash(_(u'The user is not banned.')) return redirect(next) admin_utils.unban_user(user) request.flash(_(u'The user “%s” was successfully unbanned and notified.') % user.username) return redirect(next)
def user_delete(request, key): try: user = UserProfile.get(key) except BadKeyError: return redirect('admin/users') if user: ord_usr = OrderingUser.all().filter('register_user ='******'user ='******'admin/users')
def accept(request, post): """Accept a post as an answer.""" # TODO: this is currently also fired as GET if JavaScript is # not available. Not very nice. post = Post.query.get(post) if post is None: raise NotFound() # just for sanity. It makes no sense to accept the question # as answer. The UI does not allow that, so the user must have # tampered with the data here. if post.is_question: raise BadRequest() # likewise you cannot accept a deleted post as answer if post.is_deleted: message = _(u'You cannot accept deleted posts as answers') if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) topic = post.topic # if the post is already the accepted answer, we unaccept the # post as answer. if post.is_answer: if not request.user.can_unaccept_as_answer(post): message = _(u'You cannot unaccept this reply as an answer.') if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) topic.accept_answer(None, request.user) session.commit() if request.is_xhr: return json_response(accepted=False) return redirect(url_for(post)) # otherwise we try to accept the post as answer. if not request.user.can_accept_as_answer(post): message = _(u'You cannot accept this reply as answer.') if request.is_xhr: return json_response(message=message, error=True) request.flash(message, error=True) return redirect(url_for(post)) topic.accept_answer(post, request.user) session.commit() if request.is_xhr: return json_response(accepted=True) return redirect(url_for(post))
def login(cls): """ Simple login based on the email and password Required post data see :class:LoginForm """ login_form = LoginForm(request.form) if not request.is_guest_user and request.args.get('next'): return redirect(request.args['next']) if request.method == 'POST' and login_form.validate(): NereidUser = Pool().get('nereid.user') user = NereidUser.authenticate( login_form.email.data, login_form.password.data ) # Result can be the following: # 1 - Browse record of User (successful login) # 2 - None - Login failure without message # 3 - Any other false value (no message is shown. useful if you # want to handle the message shown to user) if user: # NOTE: Translators leave %s as such flash(_("You are now logged in. Welcome %(name)s", name=user.display_name)) if login_user(user, remember=login_form.remember.data): if request.is_xhr: return jsonify({ 'success': True, 'user': user.serialize(), }) else: return redirect( request.values.get( 'next', url_for('nereid.website.home') ) ) else: flash(_("Your account has not been activated yet!")) elif user is None: flash(_("Invalid login credentials")) failed_login.send(form=login_form) if request.is_xhr: rv = jsonify(message="Bad credentials") rv.status_code = 401 return rv return render_template('login.jinja', login_form=login_form)
def reset_password(request, email=None, key=None): """Resets the password if possible.""" auth = get_auth_system() if not auth.can_reset_password: raise NotFound() form = ResetPasswordForm() new_password = None # if the user is logged in, he goes straight back to the overview # page. Why would a user that is logged in (and does not anywhere # see a link to that page) reset the password? Of course that does # not give us anything security wise because he just has to logout. if request.is_logged_in: return redirect(url_for('kb.overview')) # we came back from the link in the mail, try to reset the password if email is not None: for user in User.query.filter_by(email=email).all(): if user.password_reset_key == key: break else: request.flash(_(u'The password-reset key expired or the link ' u'was invalid.'), error=True) return redirect(url_for('core.reset_password')) new_password = user.set_random_password() session.commit() # otherwise validate the form elif request.method == 'POST' and form.validate(request.form): user = form.user reset_url = url_for('core.reset_password', email=user.email, key=user.password_reset_key, _external=True) send_email( _(u'Reset Password'), render_template('mails/reset_password.txt', user=user, reset_url=reset_url), user.email) request.flash( _(u'A mail with a link to reset the password ' u'was sent to “%s”') % user.email) return redirect(url_for('kb.overview')) return render_template('core/reset_password.html', form=form.as_widget(), new_password=new_password)
def marketplace_login(request, domain): next_url_key = NEXT_URL_KEY_FORMAT % domain def auth_callback(user): set_gaema_user(domain, user) next_url = request.cookies.get(next_url_key, "/") if get_gaema_user(domain): return redirect(next_url) auth_instance = GoogleMarketPlaceAuth(request, domain) if auth_instance.is_callback(): auth_instance.get_authenticated_user(auth_callback) return redirect(next_url) oauth_scope = getattr(settings, 'GAEMA_OAUTH_SCOPE', None) auth_instance.authorize_redirect(oauth_scope)
def touch(request, game_id): game = get_by_key_name_or_404(Game, game_id) # TODO: validation if request.method == 'POST': game.touch(int(request.form['x']), int(request.form['y'])) game.put() return redirect('/game/%s/' % game_id)
def login(self): opts = ForemanOptions.get_options() if self.validate_form(LoginForm()): user = User.get_user_with_username( self.form_result['username'].lower()) if user is not None: if user.validated is False: return self.return_response('pages', 'login.html', validated=False, company=opts.company, department=opts.department) else: # successful login self.request.session['userid'] = self.request.session.get( 'userid', user.id) if 'redirect' in self.request.args: return redirect(self.request.args['redirect']) else: return self.index() else: # should not happen that you get a valid form but invalid user return self.return_500() else: return self.return_response('pages', 'login.html', errors=self.form_error, company=opts.company, department=opts.department)
def send_magic_login_link(cls, email): """ Send a magic login email to the user """ EmailQueue = Pool().get('email.queue') try: nereid_user, = cls.search([ ('email', '=', email.lower()), ('company', '=', current_website.company.id), ]) except ValueError: # This email was not found so, let user know about this message = "No user with email %s was found!" % email current_app.logger.debug(message) else: message = "Please check your mail and follow the link" email_message = render_email( config.get('email', 'from'), email, _('Magic Signin Link'), text_template='emails/magic-login-text.jinja', html_template='emails/magic-login-html.jinja', nereid_user=nereid_user) EmailQueue.queue_mail(config.get('email', 'from'), email, email_message.as_string()) return cls.build_response(message, redirect(url_for('nereid.website.home')), 200)
def login(): error = None if request.method == 'POST': email = request.form['email'] pw = request.form['pw'] conn = mysql.connect(host='localhost', user='******', passwd='admin', db='python', charset='utf8') cursor = conn.cursor() query = "SELECT user_name FROM user_table WHERE user_email = %s AND user_pw = %s" value = (email, pw) cursor.execute("set names utf8") cursor.execute(query, value) data = (cursor.fetchall()) cursor.close() conn.close() for row in data: data = row[0] if data: print 'login success' return redirect(url_for('success', name=data)) else: error = 'Invalid input data detected!' #return redirect(url_for('success', name=user)) return render_template('python_login.html', error=error)
def change_password(cls): """ Changes the password .. tip:: On changing the password, the user is logged out and the login page is thrown at the user """ form = ChangePasswordForm() if request.method == 'POST' and form.validate(): if current_user.match_password(form.old_password.data): cls.write([current_user], {'password': form.password.data}) logout_user() return cls.build_response( 'Your password has been successfully changed! ' 'Please login again', redirect(url_for('nereid.website.login')), 200) else: return cls.build_response( 'The current password you entered is invalid', render_template('change-password.jinja', change_password_form=form), 400) if form.errors and (request.is_xhr or request.is_json): return jsonify(errors=form.errors), 400 return render_template('change-password.jinja', change_password_form=form)
def logout(cls): "Log the user out" logout_user() flash( _('You have been logged out successfully. Thanks for visiting us')) return redirect( request.args.get('next', url_for('nereid.website.home')))
def index(req, res): if sessionManager.user is None: return redirect('/signin') print(f'{sessionManager.user.username} is logged in') res.set_data('Index') return res
def activate(self, sign, max_age=24 * 60 * 60): """A web request handler for activation of the user account. This method verifies the email and if it succeeds, activates the account. If your workflow requires a manual approval of every account, override this to not activate an account, or make a no op out of this method. If all what you require is verification of email, `verify_email` method could be used. """ try: unsigned = self._serializer.loads( self._signer.unsign(sign, max_age=max_age), salt='activation' ) except SignatureExpired: flash(_("The activation link has expired")) except BadSignature: flash(_("The activation token is invalid!")) else: if self.id == unsigned: self.active = True self.email_verified = True self.save() flash(_('Your account has been activated. Please login now.')) else: flash(_('Invalid Activation Code')) return redirect(url_for('nereid.website.login'))
def deco_func(*args, **kwargs): u_no = current_user.user_no if hasattr(current_user, 'user_no') else '' if str(u_no) == '1': return f(*args, **kwargs) else: flash("관리자 로그인이 필요합니다.") return redirect(url_for('admin_view.admin_main'))
def handle_post(self, request, primary_key=None): """Return a :class:`werkzeug.Response` object after handling the POST call. :param request: The incoming Request object. :param primary_key: The primary_key of the ORM model to retrieve """ if primary_key: print 'pirmary_key' resource = self._session.query(self.cls).get(primary_key) form = self.form(request.form, obj=resource) if form.validate(): form.populate_obj(resource) resource = self._session.merge(resource) self._session.commit() else: print 'cls' resource = self.cls() form = self.form(request.form, obj=resource) form.populate_obj(resource) self._session.add(resource) self._session.commit() return redirect(resource.url())
def inner(request, *args, **kwargs): if request.user.is_anonymous(): if request.is_xhr: return Forbidden() else: return redirect(create_login_url(request.url)) return func(request, *args, **kwargs)
def change_password(cls): """ Changes the password .. tip:: On changing the password, the user is logged out and the login page is thrown at the user """ form = ChangePasswordForm(request.form) if request.method == 'POST' and form.validate(): if request.nereid_user.match_password(form.old_password.data): cls.write( [request.nereid_user], {'password': form.password.data} ) flash( _('Your password has been successfully changed! ' 'Please login again') ) logout_user() return redirect(url_for('nereid.website.login')) else: flash(_("The current password you entered is invalid")) return render_template( 'change-password.jinja', change_password_form=form )
def sign_document_from_mail(self, id, token): sign_request = request.env['sign.request'].sudo().browse(id) if not sign_request: return http.request.render('sign.deleted_sign_request') current_request_item = sign_request.request_item_ids.filtered(lambda r: r.access_token == token) current_request_item.access_via_link = True return werkzeug.redirect('/sign/document/%s/%s' % (id, token))
def reset_account(cls): """ Reset the password for the user. .. tip:: This does NOT reset the password, but just creates an activation code and sends the link to the email of the user. If the user uses the link, he can change his password. """ form = ResetAccountForm() if form.validate_on_submit(): try: nereid_user, = cls.search([ ('email', '=', form.email.data), ('company', '=', request.nereid_website.company.id), ]) except ValueError: return cls.build_response( 'Invalid email address', render_template('reset-password.jinja'), 400 ) nereid_user.send_reset_email() return cls.build_response( 'An email has been sent to your account for resetting' ' your credentials', redirect(url_for('nereid.website.login')), 200 ) elif form.errors: if request.is_xhr or request.is_json: return jsonify(error=form.errors), 400 flash(_('Invalid email address.')) return render_template('reset-password.jinja')
def delete_from_cart(cls, line): """ Delete a line from the cart. The required argument in POST is: line_id : ID of the line Response: 'OK' if X-HTTPRequest else redirect to shopping cart """ SaleLine = Pool().get('sale.line') cart = cls.open_cart() if not cart.sale: abort(404) try: sale_line, = SaleLine.search([ ('id', '=', line), ('sale', '=', cart.sale.id), ]) except ValueError: message = 'Looks like the item is already deleted.' else: SaleLine.delete([sale_line]) message = 'The order item has been successfully removed.' cart_updated.send(cart) flash(_(message)) if request.is_xhr: return jsonify(message=message) return redirect(url_for('nereid.cart.view_cart'))