def confirmation_recieved(token): """ Confirmation and account creation page :param token: Email token """ global email email = "".join(email) try: urlSerializer.loads(token, salt="email-confirm", max_age=3600 / 2) user_datastore.remove_role_from_user(User.lookup(email), 'unverified') user_datastore.add_role_to_user(User.lookup(email), "verified") user_datastore.commit() unverlog.removeContent(email, 'r+') alert.setAlert('success', 'Email Verified') return redirect(url_for(".homePage")) except SignatureExpired: notice_user = User.lookup(email) notice_msg = Message('Account Validation Warning', recipients=[notice_user.email]) notice_msg.html = automatedMail( notice_user.name, f''' We regret to inform you that your account may expire at around 0 to 1 hour due to confirmation token have expired. <br> Contact support if you want to make sure that your account won't automatically be deleted at: {url_for('.contact_us')} (<i>Notice:</i> <b>Support may be offline at any given time and may not reply fast enough. If this is the case and the 0 to 1 hour period is up then create an account again at:</b><a href="{url_for(".registerPage")}">Register</a>"). ''') mail.send(notice_msg) return redirect(url_for(".homePage"))
def login_user(token, user): """ Logs in user """ from ProjectsWebsite.database.models import User session["_id"] = login_manager._session_identifier_generator() session["_user_id"] = user.identity session["_e-recipient"] = b64encode(bytes(user.username, encoding="utf-8")) session["_fresh"] = True session["token"] = b64encode(bytes(token, encoding="utf-8")) User.activate(user.username) return True
def resetRequestRecieved(token, email): """ Redirects to Reset Form link after validating token """ try: urlSerializer.loads(token, salt="forgot-pass", max_age=300) form = forgotForm() if request.method == 'POST': email = str(email).replace("%40", '@') replacementPassword = guard.hash_password( form.confirm_new_password.data) user = User.lookup(email) if not guard.authenticate(user, form.confirm_new_password.data): user.password = replacementPassword db.session.commit() alert.setAlert('success', 'Password has been Successfully reset.') else: alert.setAlert( 'warning', 'The Requested Password matches your current password.') return redirect(url_for('loginPage')) else: return render_template("public/forgotrecieved.html", form=form, token=token, email=email) except SignatureExpired: alert.setAlert('error', 1) return redirect(url_for(".loginPage"))
def initialForgotPage(): """ forgot password page. """ form = forgotRequestForm() if request.method == "POST": recipient_email = form.email.data user = User.lookup(form.email.data) if isinstance(user, type(None)): if recipient_email != '' and form.submit.data == True: alert.setAlert('warning', f"No Account found under {recipient_email}.") return redirect(url_for(".loginPage")) elif recipient_email == '' and form.back_button.data: return redirect(url_for('.loginPage')) if not form.submit.data and form.back_button.data: return redirect(url_for('loginPage')) reset_token = urlSerializer.dumps(recipient_email, salt="forgot-pass") reset_url = 'http://127.0.0.1:5000' + url_for( "resetRequestRecieved", token=reset_token, email=recipient_email) reset_msg = Message('Reset Password', recipients=[recipient_email]) reset_msg.html = automatedMail( user.name, f'''You have requested to reset your password. Follow the link below to reset your password. <br> Reset Password: {reset_url}''') mail.send(reset_msg) alert.setAlert('success', 'Reset Password Email has been sent.') return redirect(url_for('.homePage')) else: return render_template("public/forgot.html", field=form)
def logout_user(): """ Logs out user if user is logged in """ from ProjectsWebsite.database.models import User if "_user_id" in session: if "_e-recipient" in session: user_email = b64decode(session["_e-recipient"]) user_email = str(user_email, encoding="utf-8") User.deactivate(user_email) for key in list(session.keys()): session.pop(key, None) if "_permanent" in session: session.pop("_permanent", None) if "_fresh" in session: session.pop("_fresh", None) return True
def _get_user(): from ProjectsWebsite.database.models import User, AnonymousUser if "_user_id" not in session: if hasattr(g, "_cached_user"): del (g._cached_user) return AnonymousUser if not hasattr(g, "_cached_user"): try: setattr(g, "_cached_user", User.identify(session["_user_id"])) except: session.clear() return AnonymousUser return g._cached_user
def checkExpireRegistrationCodes(): rprint( "[black][Scheduler Thread][/black][bold green]Commencing token check[/bold green]" ) from ProjectsWebsite.views import urlSerializer from ProjectsWebsite.database.models import user_datastore, User with open(f"{current_app.static_folder}\\unverified\\unverified-log.txt", 'r+', encoding="utf-8") as f: lines = f.readlines() f.close() if lines == []: return None for line in lines: user = line[line.find("(") + 1:line.rfind(")")] parenthesis_length = len(user) + 3 token = line[parenthesis_length:] try: urlSerializer.loads(token, salt="email-confirm", max_age=3600 / 2) except SignatureExpired: lines.remove(line) expired_user = User.lookup(user) expired_msg = Message("Account Deleted", recipients=[user]) expired_msg.html = automatedMail( expired_user.name, f''' Your current account in MyProjects has not been verified and your verification link has expired. You must <a href="{url_for("main_app.registerPage")}">register</a> again if you want to have an account in MyProject.''' ) mail.send(expired_msg) user_datastore.delete_user(user) user_datastore.commit() f.writelines(lines) f.close() except Exception as e: raise OperationError( "urlSerializer args or kwargs caused the current operation to fail.", "itsdangerous.URLSafeTimedSerializer") from e else: for line in lines: f.writelines(line) f.close()
def adminAccountsUserManagement(user, page): name_error = ""; email_error = ""; password_error = ""; active_error = ""; blacklist_error = ""; add_role_error = "" page: int = page pages = 3 user = str(user).replace('%20', ' ') user_info = User.lookup_by_name(user) URL = generate_err_request_url(in_admin_acc_edit_page=True, account_name=user) scrapeError = partial(_scrapeError, URL, 'p', auth=True) info_forms, search_form, role_form, delete_role_forms = (AccountManegementForms.adminUserInfoForm(), AccountManegementForms.tableSearchForm(), AccountManegementForms.roleForm(), AccountManegementForms.roleForm.deleteRoleTableForms()) article_info = Article.query.filter(Article.author.like(user)).paginate(page, pages, error_out=False) if request.method == "POST": if info_forms.name.data and info_forms.name.validate(info_forms): user_info.name = info_forms.name.data user = info_forms.name.data elif not info_forms.name.validate(info_forms) and info_forms.name.data: name_error = scrapeError(('id', 'name-err-p'), info_forms.name.errors) elif info_forms.email.data and info_forms.email.validate(info_forms): user_info.email = info_forms.email.data elif not info_forms.email.validate(info_forms) and info_forms.email.data: email_error = scrapeError(('id', 'email-err-p'), info_forms.email.data) elif info_forms.password.data and info_forms.password.validate(info_forms): user_info.password = guard.hash_password(info_forms.password.data) elif not info_forms.password.validate(info_forms) and info_forms.password.data: password_error = scrapeError(('id', 'pwd-err-p'), info_forms.password.errors) elif info_forms.active.data and info_forms.active.validate(info_forms): if info_forms.active.data == "False": data = False logout_user() else: data = True user_info.active = data db.session.commit() elif not info_forms.active.validate(info_forms) and info_forms.active.data: active_error = scrapeError(('id', 'active-status-err-p'), info_forms.active.errors) elif info_forms.blacklist.data and info_forms.blacklist.validate(info_forms): if info_forms.blacklist.data == "False": data = False else: data = True user_info.blacklisted = data db.session.commit() elif not info_forms.blacklist.validate(info_forms) and info_forms.blacklist.data: blacklist_error = scrapeError(('id', 'blacklist-status-err-p'), info_forms.blacklist.errors) elif role_form.delete_all.data: for role in user_info.roles: if role not in ('admin', 'verified', 'unverified'): user_datastore.remove_role_from_user(user_info, role) user_datastore.commit() elif role_form.add_role.data and role_form.add_role.validate(role_form): user_datastore.add_role_to_user(user_info, role_form.add_role.data) user_datastore.commit() elif not role_form.add_role.validate(role_form) and role_form.add_role.data: add_role_error = scrapeError(('id', 'add-role-err-p'), role_form.add_role.errors) elif delete_role_forms.member_field.data: user_datastore.remove_role_from_user(user, "member") user_datastore.commit() elif delete_role_forms.verified_field.data: user_datastore.remove_role_from_user(user, "verified") user_datastore.commit() elif delete_role_forms.unverified_field.data: user_datastore.remove_role_from_user(user, "unverified") user_datastore.commit() elif delete_role_forms.editor_field.data: user_datastore.remove_role_from_user(user, "editor") return render_template("private/admin/accountsuser.html", user=user_info, article_info=article_info, search_form=search_form, info_forms=info_forms, role_form=role_form, delete_role_forms=delete_role_forms, name_error=name_error, email_error=email_error, pwd_error=password_error, active_error=active_error, blacklist_error=blacklist_error, add_role_error=add_role_error) else: return render_template("private/admin/accountsuser.html", user=user_info, article_info=article_info, search_form=search_form, info_forms=info_forms, role_form=role_form, delete_role_forms=delete_role_forms)
def load_user(user_id): """ Gets the User """ return User.identify(int(user_id))