Ejemplo n.º 1
0
	def index(self, *args, **kwargs):
		if not self.canUse():
			raise errors.Forbidden() #Unauthorized

		skel = self.mailSkel()

		if len(kwargs) == 0:
			return self.render.add(skel=skel, failed=False)

		if not skel.fromClient(kwargs) or not "skey" in kwargs.keys():
			return self.render.add(skel=skel, failed=True)

		if not securitykey.validate(kwargs["skey"]):
			raise errors.PreconditionFailed()

		# Allow bones to perform outstanding "magic" operations before sending the mail
		for key, _bone in skel.items():
			if isinstance(_bone, baseBone):
				_bone.performMagic(skel.valuesCache, key, isAdd=True)

		# Get recipients
		rcpts = self.getRcpts(skel)

		# Get additional options for sendEMail
		opts = self.getOptions(skel)
		if not isinstance(opts, dict):
			opts = {}

		# Send the email!
		utils.sendEMail(rcpts, self.mailTemplate, skel, **opts)
		self.onItemAdded(skel)

		return self.render.addItemSuccess(skel)
Ejemplo n.º 2
0
    def sendWelcomeMail(self, key, initial):
        skel = self.viewSkel()
        assert skel.fromDB(key)

        skel["password"] = initial

        if request.current.get().isDevServer:
            logging.info("initial = %r", initial)

        utils.sendEMail(skel["name"], "user_welcome", skel)
Ejemplo n.º 3
0
    def pwrecover(self, authtoken=None, skey=None, *args, **kwargs):
        if authtoken:
            data = securitykey.validate(authtoken)
            if data and isinstance(data, dict) and "userKey" in data.keys(
            ) and "password" in data.keys():
                skel = self.userModule.editSkel()
                assert skel.fromDB(data["userKey"])
                skel["password"] = data["password"]
                skel.toDB()
                return self.userModule.render.view(
                    skel, self.passwordRecoverySuccessTemplate)
            else:
                return self.userModule.render.view(
                    None, self.passwordRecoveryInvalidTokenTemplate)
        else:
            skel = self.lostPasswordSkel()
            if len(kwargs) == 0 or not skel.fromClient(
                    kwargs) or not securitykey.validate(skey):
                return self.userModule.render.passwdRecover(
                    skel, tpl=self.passwordRecoveryTemplate)
            user = self.userModule.viewSkel().all().filter(
                "name.idx =", skel["name"].lower()).get()

            if not user or user[
                    "status"] < 10:  # Unknown user or locked account
                skel.errors["name"] = _("Unknown user")
                return self.userModule.render.passwdRecover(
                    skel, tpl=self.passwordRecoveryTemplate)
            try:
                if user["changedate"] > (datetime.datetime.now() -
                                         datetime.timedelta(days=1)):
                    # This user probably has already requested a password reset
                    # within the last 24 hrss
                    return self.userModule.render.view(
                        skel, self.passwordRecoveryAlreadySendTemplate)

            except AttributeError:  #Some newly generated user-objects dont have such a changedate yet
                pass
            user["changedate"] = datetime.datetime.now()
            db.Put(user)
            userSkel = self.userModule.viewSkel().ensureIsCloned()
            assert userSkel.fromDB(user.key())
            userSkel.skey = baseBone(descr="Skey")
            userSkel["skey"] = securitykey.create(60 * 60 * 24,
                                                  userKey=str(user.key()),
                                                  password=skel["password"])
            utils.sendEMail([userSkel["name"]],
                            self.userModule.passwordRecoveryMail, userSkel)
            return self.userModule.render.view(
                {}, self.passwordRecoveryInstuctionsSendTemplate)
Ejemplo n.º 4
0
    def sendNewsletter(self, key, userKey):
        skel = self.viewSkel().clone()
        if not skel.fromDB(key):
            logging.error("Newsletter does not exist")
            return

        userSkel = conf["viur.mainApp"].user.viewSkel()
        if not userSkel.fromDB(userKey):
            logging.error("Cannot find user %r", userKey)
            return

        skel.user = bones.userBone()
        skel.setBoneValue("user", userKey)

        utils.sendEMail(userSkel["name"], "newsletter", skel)

        logging.info("Sent newsletter successfully to %r", userSkel["name"])
Ejemplo n.º 5
0
    def add(self, *args, **kwargs):
        """
			Allows guests to register a new account if self.registrationEnabled is set to true

			.. seealso:: :func:`addSkel`, :func:`onItemAdded`, :func:`canAdd`

			:returns: The rendered, added object of the entry, eventually with error hints.

			:raises: :exc:`server.errors.Unauthorized`, if the current user does not have the required permissions.
			:raises: :exc:`server.errors.PreconditionFailed`, if the *skey* could not be verified.
		"""
        if "skey" in kwargs:
            skey = kwargs["skey"]
        else:
            skey = ""
        if not self.canAdd():
            raise errors.Unauthorized()
        skel = self.addSkel()
        if (len(kwargs) == 0  # no data supplied
                or skey == ""  # no skey supplied
                or not request.current.get().
                isPostRequest  # bail out if not using POST-method
                or not skel.fromClient(
                    kwargs)  # failure on reading into the bones
                or ("bounce" in list(kwargs.keys())
                    and kwargs["bounce"] == "1")):  # review before adding
            # render the skeleton in the version it could as far as it could be read.
            return self.userModule.render.add(skel)
        if not securitykey.validate(skey):
            raise errors.PreconditionFailed()
        skel.toDB()
        if self.registrationEmailVerificationRequired and str(
                skel["status"]) == "1":
            # The user will have to verify his email-address. Create an skey and send it to his address
            skey = securitykey.create(duration=60 * 60 * 24 * 7,
                                      userKey=str(skel["key"]),
                                      name=skel["name"])
            skel.skey = baseBone(descr="Skey")
            skel["skey"] = skey
            utils.sendEMail([skel["name"]],
                            self.userModule.verifyEmailAddressMail, skel)
        self.userModule.onItemAdded(
            skel)  # Call onItemAdded on our parent user module
        return self.userModule.render.addItemSuccess(skel)
Ejemplo n.º 6
0
def processChunk(module, compact, cursor, allCount=0, notify=None):
    """
		Processes 100 Entries and calls the next batch
	"""
    Skel = skeletonByKind(module)
    if not Skel:
        logging.error("TaskUpdateSearchIndex: Invalid module")
        return
    query = Skel().all().cursor(cursor)
    count = 0
    for key in query.run(25, keysOnly=True):
        count += 1
        try:
            skel = Skel()
            skel.fromDB(str(key))
            if compact == "YES":
                raise NotImplementedError(
                )  #FIXME: This deletes the __currentKey__ property..
                skel.delete()
            skel.refresh()
            skel.toDB(clearUpdateTag=True)
        except Exception as e:
            logging.error("Updating %s failed" % str(key))
            logging.exception(e)
            raise
    newCursor = query.getCursor()
    logging.info("END processChunk %s, %d records refreshed" % (module, count))
    if count and newCursor and newCursor.urlsafe() != cursor:
        # Start processing of the next chunk
        processChunk(module, compact, newCursor.urlsafe(), allCount + count,
                     notify)
    else:
        try:
            if notify:
                txt = (
                    "Subject: Rebuild search index finished for %s\n\n" +
                    "ViUR finished to rebuild the search index for module %s.\n"
                    + "%d records updated in total on this kind.") % (
                        module, module, allCount)
                utils.sendEMail([notify], txt, None)
        except:  #OverQuota, whatever
            pass
Ejemplo n.º 7
0
    def watch(self, *args, **kwargs):
        q = self.editSkel().all()
        extractId = re.compile("id=(\d+)")

        for skel in q.fetch(limit=99):
            # First of all, check for recipients.
            # If there's nobody interested, a fetch is not required.
            q = conf["viur.mainApp"].user.viewSkel().all()
            q.mergeExternalFilter({"segelflugde.dest.key": skel["key"]})

            recipients = []
            for userSkel in q.fetch(limit=99):
                recipients.append(userSkel["name"])

            if not recipients:
                logging.debug("Nobody interested in %r", skel["name"])
                continue

            logging.debug("%d recipients for %r found", len(recipients),
                          skel["name"])

            # Ok then fetch the category from the site
            content = requests.get(
                "https://www.segelflug.de/osclass/index.php?page=search&sCategory="
                + skel["category"]).content
            soup = BeautifulSoup(content, "html.parser")

            result = []
            new = []
            for offer in soup.find_all("div", {"class": "listing-attr"}):
                title = offer.find("h4").getText()
                link = offer.find("a")["href"]
                price = offer.find("span", {
                    "class": "currency-value"
                }).getText()

                id = extractId.search(link).group(1)
                result.append(id)

                if id in (skel["seen"] or []):
                    continue

                new.append({"title": title, "link": link, "price": price})

            if new:
                logging.debug("%d new items found", len(new))

                logging.debug("Sending E-Mail")
                utils.sendEMail("viur@%s.appspotmail.com" %
                                app_identity.get_application_id(),
                                "segelflugde", {
                                    "name": skel["name"],
                                    "items": new
                                },
                                bcc=recipients)

                logging.debug("Updating seen results")
                helpers.setStatus(skel["key"], {"seen": result})

                logging.debug("Successfully reported %d new items in %r",
                              len(new), skel["name"])
            else:
                logging.debug("No new entries in category %r", skel["name"])