示例#1
0
def new_topics_email():
    print("Cron job: New topics daily email")

    # find all topics created in the last 24 hours
    yesterday_topics = db.query(Topic).filter(
        Topic.created > (datetime.datetime.now() -
                         datetime.timedelta(days=1))).all()

    print(yesterday_topics)

    # if no topics, finish the task without sending the email
    if not yesterday_topics:
        print("No new topics created yesterday, so no email will be sent.")
    else:
        # create an email message
        message = "Topics created yesterday:\n"

        for topic in yesterday_topics:
            message += "- {0}\n".format(
                topic.title)  # add every new topic title in the email message

        print(message)  # print message in the console

        users = db.query(User).all()  # get all users from the database

        for user in users:
            if user.email_address:  # if user has email address, send her/him an email
                send_email(receiver_email=user.email_address,
                           subject="See new topics at Ninja Tech Forum",
                           text=message)
示例#2
0
    def send_verification_code(cls, user):
        if not user:
            return False

        with client.context():
            # generate verification code
            code = secrets.token_hex()

            # store it in user
            user.verification_code = hashlib.sha256(
                str.encode(code)).hexdigest()
            user.verification_code_expiration = datetime.datetime.now(
            ) + datetime.timedelta(hours=24)
            user.put()

            url = request.url_root
            complete_url = url + "email-verification/" + code

            message_title = "Verify e-mail address - Moderately simple registration login"

            message_body = "Thank you for registering at our web app! Please verify your e-mail by " \
                           "clicking on the link below (you have 24 hours):\n" \
                           + complete_url + "\n"

        send_email(recipient_email=user.email,
                   email_template="emails/verification_code.html",
                   email_params={"email_url": complete_url},
                   email_subject=message_title,
                   non_html_message=message_body)

        return True
示例#3
0
    def send_verification_code(cls, user):
        if user:
            # generate verification code
            code = secrets.token_hex()

            # store it in user
            user.verification_code = hashlib.sha256(
                str.encode(code)).hexdigest()
            user.verification_code_expiration = datetime.datetime.now(
            ) + datetime.timedelta(hours=1)
            db.session.add(user)
            db.session.commit()

            url = request.url_root
            complete_url = url + "email-verification/" + code

            message_title = "Verify e-mail address - Moderately simple registration login"

            message_body = "Thank you for registering at our web app! Please verify your e-mail by clicking on the " \
                           "link below:\n" \
                           + complete_url + "\n"

            message_html = "<p>Thank you for registering at our web app! Please verify your e-mail by clicking on the" \
                           "link below:<br> " \
                           + "<a href='" + complete_url + "' target='_blank'>" + complete_url + "</a></p>"

            send_email(
                email_params={
                    "recipient_email": user.email,
                    "message_title": message_title,
                    "message_body": message_body,
                    "message_html": message_html
                })

            return True
示例#4
0
    def forgot_password_code(cls, user):
        if not user:
            return False

        with client.context():
            # generate confirmation code
            code = secrets.token_hex()

            # store it in user
            user.password_forgot_code = hashlib.sha256(
                str.encode(code)).hexdigest()
            user.password_forgot_code_expiration = datetime.datetime.now(
            ) + datetime.timedelta(hours=24)
            user.put()

            url = request.url_root
            complete_url = url + "forgot-password-confirmation/" + code

            message_title = "Forgot password confirmation - Moderately simple registration login"

            message_body = "You have requested to change your password at our app. Confirm this action by " \
                           "clicking on the link below (you have 24 hours):\n" \
                           + complete_url + "\n" + "\n\n If this was not you, please ignore this e-mail."

        send_email(recipient_email=user.email,
                   email_template="emails/change_password_code.html",
                   email_params={"email_url": complete_url},
                   email_subject=message_title,
                   non_html_message=message_body)

        return True
示例#5
0
    def send_magic_login_link(cls, email_address, locale="en"):
        # sanitize input
        email_address = bleach.clean(email_address, strip=True).lower()

        # generate magic link token
        token = secrets.token_hex()

        user = cls.get_user_by_email(email_address=email_address)

        with client.context():
            if user:
                user.magic_link_token_hash = hashlib.sha256(
                    str.encode(token)).hexdigest()
                user.magic_link_token_expired = datetime.datetime.now(
                ) + datetime.timedelta(hours=3)
                user.put()

                # send email with magic link to user
                send_email(
                    recipient_email=email_address,
                    email_template="emails/login_magic_link.html",
                    email_params={"magic_login_token": token},
                    email_subject=get_translation(
                        locale=locale,
                        translation_function="magic_link_email_subject"))

                return True, "Success"
            else:
                return False, "User with this email is not registered yet!"
示例#6
0
    def create(cls, text, author, topic):
        comment = cls(text=text, author=author, topic=topic)
        db.add(comment)
        db.commit()

        if topic.author.email_address:
            send_email(
                "Ktos skomentowal twoj post {}! Sprawdz to szybko".format(
                    topic.title), "Nowy komentarz", topic.author.email_address)

        return comment
示例#7
0
    def create(cls, text, author, topic):
        comment = cls(text=text, author=author, topic=topic)
        db.add(comment)
        db.commit()

        # only send of topic author has her/his email in the database
        if topic.author.email:
            send_email(receiver_email=topic.author.email, subject="New comment for your topic!",
                       text="Your topic {} has a new comment.".format(topic.title))

        return comment
    def create(cls, text, author, topic):
        comment = cls(text=text, author=author, topic=topic)
        db.add(comment)
        db.commit()

        if topic.author.email_address:
            send_email(receiver_email=topic.author.email_address,
                       subject="New comment for your topic!",
                       text="Your topic {} has a new comment.".format(
                           topic.title))

        return comment
 def _send_test_result(self, result_statistics, report_file):
     if result_statistics:
         email_setting = dict(
             self._config["email_sender"],
             **self._config["email_receiver"][self._config["profile"]])
         email_content = result_statistics
         email_subject = "%s - %s - Auto Test Result" % (
             self._config["project"], self._config["environment"])
         print(f"Send email: {email_subject}")
         send_email(email_content,
                    email_subject,
                    email_setting,
                    filename=report_file)
示例#10
0
文件: auth.py 项目: ruth-gra/ruth-gra
def signup():
    if request.method == "GET":
        return render_template("auth/signup.html")

    elif request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        email_address = request.form.get("email-address")
        repeat = request.form.get("repeat")

        if password != repeat:
            return "Passwords do not match! Go back and try again."

        user = User(username=username,
                    password_hash=hashlib.sha256(
                        password.encode()).hexdigest(),
                    session_token=str(uuid.uuid4()),
                    email_address=email_address,
                    verification_token=str(uuid.uuid4()))
        db.add(user)  # add to the transaction (user is not yet in a database)
        db.commit(
        )  # commit the transaction into the database (user is now added in the database)

        # verification email message
        subject = "Verify your email address"
        domain = "{}.herokuapp.com".format(
            os.getenv("HEROKU_APP_NAME"
                      ))  # TODO: set HEROKU_APP_NAME config var on Heroku!
        print("Domain: " + str(domain))
        text = "Hi! Click on this link to verify your email address: {0}/verify-email/{1}".format(
            domain, user.verification_token)

        # send verification email
        send_email(receiver_email=user.email_address,
                   subject=subject,
                   text=text)

        # save user's session token into a cookie
        response = make_response(redirect(url_for('topic.index')))
        response.set_cookie(
            "session_token", user.session_token
        )  # you might want to set httponly=True on production

        return response
示例#11
0
    def user_change_own_email(cls, user, new_email_address, locale="en"):
        # this method is for users only to change their own email addresses
        with client.context():
            new_email_address = bleach.clean(
                new_email_address, strip=True).lower()  # sanitize input

            if user.email_address != new_email_address:  # new email must not equal to old one
                # check if user with this email address already exists
                existing_user = cls.query(
                    cls.email_address == new_email_address).get()

                if existing_user:
                    # if user with this email already exists, then terminate the whole change email operation
                    return False, "User with this email address already exists"
                else:
                    # generate magic link token (needs to include the new email address)
                    token = "{0}-n1nj4-{1}".format(secrets.token_hex(),
                                                   new_email_address)

                    user.change_email_token_hash = hashlib.sha256(
                        str.encode(token)).hexdigest()
                    user.change_email_token_expired = datetime.datetime.now(
                    ) + datetime.timedelta(hours=3)
                    user.put()

                    # send email with magic link to user
                    subject = get_translation(
                        locale=locale,
                        translation_function="change_email_link_email_subject")
                    send_email(recipient_email=new_email_address,
                               email_template="emails/change_email_link.html",
                               email_params={
                                   "change_email_token": token,
                                   "new_email_address": new_email_address
                               },
                               email_subject=subject.format(
                                   new_email_address=new_email_address))

                    return True, "Success"
            else:
                return False, "You have entered the same email address as your existing one."
示例#12
0
    def change_password_code_confirmation(cls, code):
        if not code:
            return False

        with client.context():
            email_ready = False

            # verify verification code
            code_hash = hashlib.sha256(str.encode(code)).hexdigest()

            user = cls.query(cls.password_change_code == code_hash).get()

            if not user:
                return False, "That confirmation code is not valid."

            if user.password_change_code_expiration > datetime.datetime.now():
                user.password_change_code = ""
                user.password_change_code_expiration = datetime.datetime.min
                user.put()

                new_password_hash = user.new_password
                url = request.url_root

                message_title = "Your password has been changed - Moderately simple registration login"

                message_body = "Your password has been successfully changed! Thank you, you can now login with " \
                               "the link below:\n" + url + "\n\n If this was not you, please contact us immediately."

                email_ready = True

        if email_ready:
            send_email(recipient_email=user.email,
                       email_template="emails/password_changed.html",
                       email_params={"email_url": url},
                       email_subject=message_title,
                       non_html_message=message_body)
            return True, user, new_password_hash, "Success"
        else:
            return False, "That confirmation code is not valid."
示例#13
0
def signup():
    if request.method == "GET":
        return render_template("auth/signup.html")

    elif request.method == "POST":
        username = request.form.get("username")
        email = request.form.get("email-address")
        password = request.form.get("password")
        repeat = request.form.get("repeat")

        if password != repeat:
            return "Passwords don't match! Go back and try again."

        username_taken = db.query(User).filter_by(username=username).first()
        if username_taken:
            return "This username is already taken. Please choose another one."

        password_hash = hashlib.sha256(password.encode()).hexdigest()
        verification_token = str(uuid.uuid4())

        user = User.create(username=username,
                           email=email,
                           password_hash=password_hash,
                           verification_token=verification_token)

        subject = "Welcome to the Ninja Tech Forum"
        domain = "{0}.herokuapp.com".format(os.getenv("HEROKU_APP_NAME"))
        text = "Hi! Click on this link to verify your email address: {0}/verify-email/{1}"\
            .format(domain, verification_token)

        send_email(receiver_email=email, subject=subject, text=text)

        response = make_response(redirect(url_for('topic.index')))
        response.set_cookie("session_token",
                            user.session_token,
                            httponly=True,
                            samesite='Strict')

        return response
示例#14
0
    def verify_verification_code(cls, code):
        if not code:
            return False

        with client.context():
            email_ready = False

            # verify verification code
            code_hash = hashlib.sha256(str.encode(code)).hexdigest()

            user = cls.query(cls.verification_code == code_hash).get()

            if not user:
                return False, "That verification code is not valid."

            if user.verification_code_expiration > datetime.datetime.now():
                user.verification_code = ""
                user.verification_code_expiration = datetime.datetime.min
                user.put()

                url = request.url_root

                message_title = "E-mail address confirmed - Moderately simple registration login"

                message_body = "Your e-mail has been confirmed! Thank you, you can now login with " \
                               "the link below:\n" + url + "\n"

                email_ready = True

        if email_ready:
            send_email(recipient_email=user.email,
                       email_template="emails/verification_success.html",
                       email_params={"email_url": url},
                       email_subject=message_title,
                       non_html_message=message_body)
            return True, "Success"
        else:
            return False, "That verification code is not valid."
示例#15
0
    def change_password_code(cls, user, new_password):
        if not user:
            return False

        with client.context():
            # generate confirmation code
            code = secrets.token_hex()

            # store it in user
            user.password_change_code = hashlib.sha256(
                str.encode(code)).hexdigest()
            user.password_change_code_expiration = datetime.datetime.now(
            ) + datetime.timedelta(hours=24)

            # store new password in temporary user field
            hashed = bcrypt.hashpw(new_password.encode('utf8'),
                                   bcrypt.gensalt())
            password_hash = hashed.decode('utf8')
            user.new_password = password_hash

            user.put()

            url = request.url_root
            complete_url = url + "change-password-confirmation/" + code

            message_title = "Change password confirmation - Moderately simple registration login"

            message_body = "You have requested to change your password at our app. Confirm this action by " \
                           "clicking on the link below (you have 24 hours):\n" \
                           + complete_url + "\n" + "\n\n If this was not you, please contact us immediately."

        send_email(recipient_email=user.email,
                   email_template="emails/change_password_code.html",
                   email_params={"email_url": complete_url},
                   email_subject=message_title,
                   non_html_message=message_body)

        return True
示例#16
0
    def verify_verification_code(cls, code):
        if code:
            # verify verification code
            code_hash = hashlib.sha256(str.encode(code)).hexdigest()

            user = cls.query.filter_by(verification_code=code_hash).first()

            if not user:
                return False, "That verification code is not valid."

            if user.verification_code_expiration > datetime.datetime.now():
                user.verification_code = ""
                user.verification_code_expiration = datetime.datetime.min
                db.session.add(user)
                db.session.commit()

                url = request.url_root

                message_title = "E-mail address confirmed - Moderately simple registration login"

                message_body = "Your e-mail has been confirmed! Thank you, you can now login with the link below:\n" \
                               + url + "\n"

                message_html = "<p>Your e-mail has been confirmed! Thank you, you can now login with the link below:" \
                               "<br><a href='" + url + "' target='_blank'>" + url + "</a></p>"

                send_email(
                    email_params={
                        "recipient_email": user.email,
                        "message_title": message_title,
                        "message_body": message_body,
                        "message_html": message_html
                    })

                return True, "Success"
            else:
                return False, "That verification code is not valid."
示例#17
0
    def forgot_password_success(cls, user):
        if not user:
            return False

        with client.context():
            # delete temporary fields
            user.password_forgot_code = ""
            user.password_forgot_code_expiration = datetime.datetime.min
            user.put()

            url = request.url_root

            message_title = "Your password has been changed - Moderately simple registration login"

            message_body = "Your password has been successfully changed! Thank you, you can now login with " \
                           "the link below:\n" + url + "\n\n If this was not you, please contact us immediately."

        send_email(recipient_email=user.email,
                   email_template="emails/password_changed.html",
                   email_params={"email_url": url},
                   email_subject=message_title,
                   non_html_message=message_body)

        return True