Exemple #1
0
    def email_render_error(self, traceback=None):
        """ Uses the attributes of the session to send an email when a user's
        current view fails to render. """

        admins = settings.get("application", "admin_email").split(",")

        session_as_html = "<br/>".join(
            ["&ensp; %s -> %s" % (k, v) for k, v in self.session.iteritems()])

        M = mailSession()
        email_msg = html.meta.view_render_fail_email.safe_substitute(
            user_email=self.User.user["login"],
            user_id=self.User.user["_id"],
            exception=traceback,
            hostname=socket.gethostname(),
            error_time=datetime.now(),
            session_obj=session_as_html,
        )
        M.send(
            recipients=admins,
            html_msg=email_msg,
            subject="KDM-Manager Render Failure! [%s]" % socket.gethostname(),
            #            reply_to=self.User.user["login"],
        )
        self.logger.warn("[%s] Current view render failure email sent!" %
                         self.User)
Exemple #2
0
def initiate_password_reset():
    """ Attempts to start the mechanism for resetting a user's password.
    Unlike a lot of methods, this one handles the whole request processing and
    is very...self-contained. """

    # first, validate the post
    incoming_json = request.get_json()
    user_login = incoming_json.get('username', None)
    if user_login is None:
        return Response(
            response = "A valid user email address must be included in password reset requests!",
            status = 400
        )

    # normalize emails issue #501
    user_login = user_login.strip().lower()

    # next, validate the user
    user = utils.mdb.users.find_one({"login": user_login})
    if user is None:
        return Response(
            response = "'%s' is not a registered email address." % user_login,
            status = 404
        )

    # if the user looks good, set the code
    U = User(_id=user["_id"])
    user_code = U.set_recovery_code()

    # support for applications with their own URLs
    incoming_app_url = incoming_json.get('app_url', None)
    if incoming_app_url is not None:
        application_url = incoming_app_url
        parsed = urlparse.urlsplit(incoming_app_url)
        netloc = parsed.scheme + "://" + parsed.netloc
    else:
        netloc = utils.get_application_url()
        application_url = utils.get_application_url()

    # finally, send the email to the user
    try:
        tmp_file = os.path.join(utils.settings.get("api","cwd"), "html/password_recovery.html")
        msg = string.Template(file(tmp_file, "rb").read())
        msg = msg.safe_substitute(login=user_login, recovery_code=user_code, app_url=application_url, netloc=netloc)
        e = utils.mailSession()
        e.send(recipients=[user_login], html_msg=msg)
    except Exception as e:
        logger.error(e)
        raise

    # exit 200
    return utils.http_200
Exemple #3
0
    def report_error(self):
        """ Uses attributes of the session, including self.params, to create an
        error report email. """

        self.logger.debug("[%s] is entering an error report!" % self.User)
        admins = settings.get("application", "admin_email").split(",")

        M = mailSession()
        email_msg = html.meta.error_report_email.safe_substitute(
            user_email=self.User.user["login"],
            user_id=self.User.user["_id"],
            body=self.params["body"].value.replace("\n", "<br/>"))
        M.send(
            recipients=admins,
            html_msg=email_msg,
            subject="KDM-Manager Error Report",
            reply_to=self.User.user["login"],
        )
        self.logger.warn("[%s] Error report email sent!" % self.User)
Exemple #4
0
    def get_settlements(self, qualifier=None, return_type=None):
        """ By default, this returns all settlements created by the user. Use
        the qualifiers thus:

            'player' - returns all settlements where the user is a player or
                admin or whatever. This casts the widest possible net.
            'admin' - returns only the settlements where the user is an admin
                but is NOT the creator of the settlement.

        """

        if qualifier is None:
            settlements = utils.mdb.settlements.find({
                "$or": [
                    {
                        "created_by": self.user["_id"],
                        "removed": {
                            "$exists": False
                        },
                    },
                    {
                        "admins": {
                            "$in": [
                                self.user["login"],
                            ]
                        },
                        "removed": {
                            "$exists": False
                        },
                    },
                ]
            })
        elif qualifier == "player":
            settlement_id_set = set()

            survivors = self.get_survivors(qualifier="player")
            for s in survivors:
                settlement_id_set.add(s["settlement"])

            settlements_owned = self.get_settlements()
            for s in settlements_owned:
                settlement_id_set.add(s["_id"])
            settlements = utils.mdb.settlements.find({
                "_id": {
                    "$in": list(settlement_id_set)
                },
                "removed": {
                    "$exists": False
                }
            })
        elif qualifier == "admin":
            settlements = utils.mdb.settlements.find({
                "admins": {
                    "$in": [self.user["login"]]
                },
                "created_by": {
                    "$ne": self.user["_id"]
                },
                "removed": {
                    "$exists": False
                },
            })
        else:
            raise Exception("'%s' is not a valid qualifier for this method!" %
                            qualifier)

        # change settlements to a list so we can do python post-process
        settlements = list(settlements)

        # settlement age support/freemium wall
        # first, see if we even need to be here
        # MOVE ALL OF THIS OUT OF THIS METHOD ASAP
        sub_level = self.get_subscriber_level()
        if sub_level >= 1:
            pass
        else:
            #            self.logger.debug("%s Subscriber level is %s. Checking settlement asset ages..." % (self, sub_level))
            for s in settlements:
                asset_age = datetime.now() - s['created_on']
                older_than_cutoff = asset_age.days > settings.get(
                    'application', 'free_user_settlement_age_max')
                if older_than_cutoff and self.user['_id'] == s['created_by']:
                    self.logger.warn(
                        "%s settlement '%s' is more than %s days old!" %
                        (self, s['name'],
                         settings.get('application',
                                      'free_user_settlement_age_max')))
                    msg = utils.html_file_to_template(
                        'html/auto_remove_settlement.html')

                    # in case the admin panel hits it before the actual user
                    if not hasattr(request, 'User'):
                        request.User = utils.noUser()

                    msg = msg.safe_substitute(
                        settlement_name=s['name'],
                        settlement_age=asset_age.days,
                        settlement_dict=s,
                        user_email=request.User.login,
                        user_id=request.User._id,
                    )
                    e = utils.mailSession()
                    e.send(subject="Settlement auto-remove! [%s]" %
                           socket.getfqdn(),
                           recipients=settings.get('application',
                                                   'email_alerts').split(','),
                           html_msg=msg)
                    s['removed'] = datetime.now()
                    utils.mdb.settlements.save(s)
                    settlements.remove(s)

        #
        # now start handling returns
        #

        if return_type == int:
            return len(settlements)
        elif return_type == list:
            output = [s["_id"] for s in settlements]
            return output
        elif return_type == 'list_of_dicts':
            return settlements
        elif return_type == "asset_list":
            output = []
            for s in settlements:
                try:
                    S = Settlement(_id=s["_id"], normalize_on_init=False)
                    sheet = json.loads(S.serialize('dashboard'))
                    output.append(sheet)
                except Exception as e:
                    logger.error("Could not serialize %s" % s)
                    logger.exception(e)
                    raise

            return output

        return settlements