def index(*args, **kwargs): if currentRequest.get().isDevServer or currentRequest.get( ).isSSLConnection: raise errors.Redirect("/vi/s/main.html") else: appVersion = app_identity.get_default_version_hostname() raise errors.Redirect("https://%s/vi/s/main.html" % appVersion)
def index(*args, **kwargs): from viur.core.render import isAdminAvailable, isViAvailable if not isAdminAvailable(): if isViAvailable(): # The admin is not available, the Vi however is, so redirect there raise errors.Redirect("/vi") raise errors.NotFound() if currentRequest.get().isDevServer or currentRequest.get().isSSLConnection: raise errors.Redirect("/admin/s/admin.html") else: appVersion = currentRequest.get().request.host raise errors.Redirect("https://%s/admin/s/admin.html" % appVersion)
def index(self, *args, **kwargs): """ Default, SEO-Friendly fallback for view and list. :param args: The first argument - if provided - is interpreted as seoKey. :param kwargs: Used for the fallback list. :return: The rendered entity or list. """ if args and args[0]: # We probably have a Database or SEO-Key here seoKey = str(args[0]).lower() skel = self.viewSkel().all(_excludeFromAccessLog=True).filter( "viur.viurActiveSeoKeys =", seoKey).getSkel() if skel: db.currentDbAccessLog.get(set()).add(skel["key"]) if not self.canView(skel): raise errors.Forbidden() seoUrl = utils.seoUrlToEntry(self.moduleName, skel) # Check whether this is the current seo-key, otherwise redirect to it if currentRequest.get().request.path != seoUrl: raise errors.Redirect(seoUrl, status=301) self.onView(skel) return self.render.view(skel) # This was unsuccessfully, we'll render a list instead if not kwargs: kwargs = self.getDefaultListParams() return self.list(kwargs)
def redirect(render, url): """ Jinja2 global: Redirect to another URL. :param url: URL to redirect to. :type url: str """ raise errors.Redirect(url)
def startProcessing(self, step, orderID): def setTokenTxn(key, token): order = db.Get(key) if not order: return order["paypal_token"] = urllib.unquote(token) db.Put(order) paypal = PayPal.PayPalHandler() key = db.Key(orderID) order = db.Get(key) if not order: return token = paypal.SetExpressCheckout("%.2f" % order["price"]) db.RunInTransaction(setTokenTxn, key, token) raise (errors.Redirect(paypal.getPayURL(token)))
def download(self, blobKey, fileName="", download="", sig="", *args, **kwargs): """ Download a file. :param blobKey: The unique blob key of the file. :type blobKey: str :param fileName: Optional filename to provide in the header. :type fileName: str :param download: Set header to attachment retrival, set explictly to "1" if download is wanted. :type download: str """ global credentials, bucket if not sig: raise errors.PreconditionFailed() # First, validate the signature, otherwise we don't need to proceed any further if not utils.hmacVerify(blobKey.encode("ASCII"), sig): raise errors.Forbidden() # Split the blobKey into the individual fields it should contain dlPath, validUntil = urlsafe_b64decode(blobKey).decode("UTF-8").split( "\0") if validUntil != "0" and datetime.strptime( validUntil, "%Y%m%d%H%M") < datetime.now(): raise errors.Gone() # Create a signed url and redirect the user if isinstance(credentials, ServiceAccountCredentials ): # We run locally with an service-account.json blob = bucket.get_blob(dlPath) if not blob: raise errors.NotFound() signed_url = blob.generate_signed_url(datetime.now() + timedelta(seconds=60)) else: # We are inside the appengine auth_request = requests.Request() signed_blob_path = bucket.blob(dlPath) expires_at_ms = datetime.now() + timedelta(seconds=60) signing_credentials = compute_engine.IDTokenCredentials( auth_request, "", service_account_email=credentials.service_account_email) signed_url = signed_blob_path.generate_signed_url( expires_at_ms, credentials=signing_credentials, version="v4") raise errors.Redirect(signed_url)
def download(self, blobKey, fileName="", download="", sig="", *args, **kwargs): """ Download a file. :param blobKey: The unique blob key of the file. :type blobKey: str :param fileName: Optional filename to provide in the header. :type fileName: str :param download: Set header to attachment retrival, set explictly to "1" if download is wanted. :type download: str """ if not sig: raise errors.PreconditionFailed() # if download == "1": # fname = "".join( # [c for c in fileName if c in string.ascii_lowercase + string.ascii_uppercase + string.digits + ".-_"]) # request.current.get().response.headers.add_header("Content-disposition", # ("attachment; filename=%s" % (fname)).encode("UTF-8")) # First, validate the signature, otherwise we don't need to proceed any further if not utils.hmacVerify(blobKey.encode("ASCII"), sig): raise errors.Forbidden() # Split the blobKey into the individual fields it should contain dlPath, validUntil = urlsafe_b64decode(blobKey).decode("UTF-8").split( "\0") if validUntil != "0" and datetime.strptime( validUntil, "%Y%m%d%H%M") < datetime.now(): raise errors.Gone() # Create a signed url and redirect the user blob = bucket.get_blob(dlPath) if not blob: raise errors.NotFound() signed_url = blob.generate_signed_url(datetime.now() + timedelta(seconds=60)) raise errors.Redirect(signed_url)
def checkout(self, step=None, key=None, skey=None, *args, **kwargs): """ Performs the checkout process trough the state machine provided by self.steps. :param step: The current step index, None for beginning a new checkout :param key: Key of the current checkout :param skey: Server security key :return: Returns the rendered template or throws redirection exceptions. """ myKindName = self.viewSkel().kindName if step is None: logging.info("Starting new checkout process") billObj = db.Entity(myKindName) billObj["idx"] = "0000000" for state in self.states: billObj["state_%s" % state] = "0" db.Put(billObj) key = str(billObj.key()) # Copy the Cart if "amountSkel" in dir(self): cart = session.current.get("cart_products") or {} s = self.amountSkel() products = [] for prod, atts in cart.items(): for i in range(0, atts["amount"]): products.append(str(prod)) s.fromClient({"product": products}) s.toDB() session.current["order_" + myKindName] = { "key": str(key), "completedSteps": [] } session.current.markChanged() raise errors.Redirect("?step=0&key=%s" % str(key)) elif key: try: orderKey = db.Key(key) step = int(step) assert (step >= 0) assert (step < len(self.steps)) except: raise errors.NotAcceptable() sessionInfo = session.current.get("order_" + myKindName) if not sessionInfo or not sessionInfo.get("key") == str(orderKey): raise errors.Unauthorized() if step in sessionInfo["completedSteps"]: session.current["order_" + myKindName]["completedSteps"] = [ x for x in sessionInfo["completedSteps"] if x < step ] session.current.markChanged() # Make sure that no steps can be skipped if step != 0 and not step - 1 in sessionInfo["completedSteps"]: raise errors.Redirect("?step=0&key=%s" % str(str(orderKey))) currentStep = self.steps[step] if "preHandler" in currentStep.keys(): try: if isinstance(currentStep["preHandler"], list): for handler in currentStep["preHandler"]: handler(self, step, str(orderKey), *args, **kwargs) else: currentStep["preHandler"](self, step, str(orderKey), refkwargs=kwargs, *args, **kwargs) except SkipStepException: session.current["order_" + myKindName]["completedSteps"].append(step) session.current.markChanged() raise errors.Redirect("?step=%s&key=%s" % (str(step + 1), str(orderKey))) except ReturnHtmlException as e: return (e.html) if "requiresSecurityKey" in currentStep and currentStep[ "requiresSecurityKey"]: if not securitykey.validate(skey): raise errors.PreconditionFailed() pass if "mainHandler" in currentStep: if currentStep["mainHandler"]["action"] == "edit": skel = self.getSkelByName( currentStep["mainHandler"]["skeleton"], str(orderKey)) skel.fromDB(str(orderKey)) if not len(kwargs.keys()) or not skel.fromClient(kwargs): return (self.render.edit( skel, tpl=currentStep["mainHandler"]["template"], step=step)) skel.toDB() if currentStep["mainHandler"]["action"] == "view": if not "complete" in kwargs or not kwargs[ "complete"] == u"1": skel = self.getSkelByName( currentStep["mainHandler"]["skeleton"], str(orderKey)) skel.fromDB(str(orderKey)) return (self.render.view( skel, tpl=currentStep["mainHandler"]["template"], step=step)) elif currentStep["mainHandler"]["action"] == "function": res = currentStep["mainHandler"]["function"](self, step, str(orderKey), *args, **kwargs) if res: return res if "postHandler" in currentStep: currentStep["postHandler"](self, step, str(orderKey), *args, **kwargs) session.current["order_" + myKindName]["completedSteps"].append(step) session.current.markChanged() logging.info("next ?step=%s&key=%s" % (str(step + 1), str(orderKey))) raise errors.Redirect("?step=%s&key=%s" % (str(step + 1), str(orderKey)))
prods[product]["amount"] = int(amt) else: if not amt: amt = 1 prods[product]["amount"] += int(amt) session.current["cart_products"] = prods session.current.markChanged() if async: return json.dumps({"cartentries": self.entryCount(), "cartsum": self.cartSum(), "added": int(amt)}) raise errors.Redirect("/%s/view" % self.moduleName) @exposed def view(self, *args, **kwargs): """ Views the current cart content. """ prods = session.current.get("cart_products") or {} if prods: items = self.productSkel().all().mergeExternalFilter({"key": list(prods.keys())}).fetch(limit=10) else: items = SkelList(self.productSkel) for skel in items:
def download(self, blobKey, fileName="", download="", sig="", *args, **kwargs): """ Download a file. :param blobKey: The unique blob key of the file. :type blobKey: str :param fileName: Optional filename to provide in the header. :type fileName: str :param download: Set header to attachment retrival, set explictly to "1" if download is wanted. :type download: str """ global credentials, bucket if not sig: # Check if the current user has the right to download *any* blob present in this application. # blobKey is then the path inside cloudstore - not a base64 encoded tuple usr = utils.getCurrentUser() if not usr: raise errors.Unauthorized() if "root" not in usr["access"] and "file-view" not in usr["access"]: raise errors.Forbidden() validUntil = "-1" # Prevent this from being cached down below blob = bucket.get_blob(blobKey) else: # We got an request including a signature (probably a guest or a user without file-view access) # First, validate the signature, otherwise we don't need to proceed any further if not utils.hmacVerify(blobKey.encode("ASCII"), sig): raise errors.Forbidden() # Split the blobKey into the individual fields it should contain dlPath, validUntil = urlsafe_b64decode(blobKey).decode( "UTF-8").split("\0") if validUntil != "0" and datetime.strptime( validUntil, "%Y%m%d%H%M") < datetime.now(): raise errors.Gone() blob = bucket.get_blob(dlPath) if not blob: raise errors.Gone() if download: fileName = sanitizeFileName(blob.name.split("/")[-1]) contentDisposition = "attachment; filename=%s" % fileName else: contentDisposition = None if isinstance(credentials, ServiceAccountCredentials ): # We run locally with an service-account.json expiresAt = datetime.now() + timedelta(seconds=60) signedUrl = blob.generate_signed_url( expiresAt, response_disposition=contentDisposition, version="v4") raise errors.Redirect(signedUrl) elif utils.isLocalDevelopmentServer: # No Service-Account to sign with - Serve everything directly response = utils.currentRequest.get().response response.headers["Content-Type"] = blob.content_type if contentDisposition: response.headers["Content-Disposition"] = contentDisposition return blob.download_as_bytes() else: # We are inside the appengine if validUntil == "0": # Its an indefinitely valid URL if blob.size < 5 * 1024 * 1024: # Less than 5 MB - Serve directly and push it into the ede caches response = utils.currentRequest.get().response response.headers["Content-Type"] = blob.content_type response.headers[ "Cache-Control"] = "public, max-age=604800" # 7 Days if contentDisposition: response.headers[ "Content-Disposition"] = contentDisposition return blob.download_as_bytes() # Default fallback - create a signed URL and redirect authRequest = requests.Request() expiresAt = datetime.now() + timedelta(seconds=60) signing_credentials = compute_engine.IDTokenCredentials( authRequest, "") signedUrl = blob.generate_signed_url( expiresAt, credentials=signing_credentials, response_disposition=contentDisposition, version="v4") raise errors.Redirect(signedUrl)
def login(self, skey="", token="", *args, **kwargs): # FIXME: Check if already logged in if not conf.get("viur.user.google.clientID"): raise errors.PreconditionFailed() if not skey or not token: request.current.get( ).response.headers["Content-Type"] = "text/html" # Fixme: Render with Jinja2? tplStr = open("server/template/vi_user_google_login.html", "r").read() tplStr = tplStr.replace("{{ clientID }}", conf["viur.user.google.clientID"]) return tplStr if not securitykey.validate(skey, useSessionKey=True): raise errors.PreconditionFailed() userInfo = id_token.verify_oauth2_token( token, requests.Request(), conf["viur.user.google.clientID"]) if userInfo['iss'] not in { 'accounts.google.com', 'https://accounts.google.com' }: raise ValueError('Wrong issuer.') # Token looks valid :) uid = userInfo['sub'] email = userInfo['email'] addSkel = skeletonByKind(self.userModule.addSkel().kindName ) # Ensure that we have the full skeleton userSkel = addSkel().all().filter("uid =", uid).getSkel() if not userSkel: # We'll try again - checking if there's already an user with that email userSkel = addSkel().all().filter("name.idx =", email.lower()).getSkel() if not userSkel: # Still no luck - it's a completely new user if not self.registrationEnabled: if userInfo.get("hd") and userInfo["hd"] in conf[ "viur.user.google.gsuiteDomains"]: print("User is from domain - adding account") else: logging.warning("Denying registration of %s", email) raise errors.Forbidden( "Registration for new users is disabled") userSkel = addSkel() # We'll add a new user userSkel["uid"] = uid userSkel["name"] = email isAdd = True else: isAdd = False now = datetime.datetime.now() if isAdd or (now - userSkel["lastlogin"]) > datetime.timedelta(minutes=30): # Conserve DB-Writes: Update the user max once in 30 Minutes userSkel["lastlogin"] = now #if users.is_current_user_admin(): # if not userSkel["access"]: # userSkel["access"] = [] # if not "root" in userSkel["access"]: # userSkel["access"].append("root") # userSkel["gaeadmin"] = True #else: # userSkel["gaeadmin"] = False assert userSkel.toDB() return self.userModule.continueAuthenticationFlow( self, (userSkel.kindName, userSkel["key"])) if users.get_current_user(): currentUser = users.get_current_user() uid = currentUser.user_id() raise errors.Redirect( users.create_login_url(self.modulePath + "/login"))
def startProcessing(self, step, orderID): raise errors.Redirect(self.getSofortURL(orderID))