def test_is_authenticated(self): """This method tests the functionality of the is_authenticated method. """ # TEST ENV SETUP # make sure the valid account is logged in first before trying to logout with the account connect(*VALID_ZV_CONNECTION) # test authentication for valid tg->zv connection # should return True and the zv_user the tg user is auth'd as assert is_authenticated(VALID_TG_ID) == True # test authentication for invalid tg->zv connection # should return False and None since tg user not auth'd assert is_authenticated(INVALID_TG_ID) == False
def get_account(): if not authentication.is_authenticated(flask.session): return redirect_to_login() authorization = authentication.get_authorization_header( flask.session['macaroon_root'], flask.session['macaroon_discharge']) headers = { 'X-Ubuntu-Series': '16', 'X-Ubuntu-Architecture': 'amd64', 'Authorization': authorization } url = 'https://dashboard.snapcraft.io/dev/api/account' response = requests.request(url=url, method='GET', headers=headers) verified_response = authentication.verify_response(response, flask.session, url, '/account', '/login') if verified_response is not None: if verified_response['redirect'] is None: response.raise_for_status() return flask.redirect(verified_response.redirect) context = {'account': response.json()} return flask.render_template('account.html', **context)
def forgot_password(): '''This function return forgot pass page and send email. Methods: GET: it returns the forgot pass page Post: it send email to the user by calling the send email ''' if is_authenticated(): return redirect(url_for('login')) form = ForgotPassForm() if form.validate_on_submit(): uemail = form.email.data.lower() utype = int(form.user_type.data) model = UserModel if utype == 1 else AdminModel is_valid_email = email_valid(uemail, model) if not is_valid_email: flash('Email Address Does not exists.', "emailNotUnique") else: user = model.query.filter_by(email=uemail).first() send_email = send_reset_mail(utype, user) if send_email: flash("Passwrod Reset Link send to your email", category="addSuccess") return redirect(url_for('login')) return render_template("authentication/forgot_pass.html", form = form)
def get_account(): if not authentication.is_authenticated(flask.session): return redirect_to_login() authorization = authentication.get_authorization_header( flask.session['macaroon_root'], flask.session['macaroon_discharge']) headers = { 'X-Ubuntu-Series': '16', 'X-Ubuntu-Architecture': 'amd64', 'Authorization': authorization } url = 'https://dashboard.snapcraft.io/dev/api/account' response = requests.request(url=url, method='GET', headers=headers) verified_response = authentication.verify_response(response, flask.session, url, '/account', '/login') if verified_response is not None: if verified_response['redirect'] is None: return response.raise_for_status else: return flask.redirect(verified_response.redirect) print('HTTP/1.1 {} {}'.format(response.status_code, response.reason)) user_snaps = response.json() return flask.render_template('account.html', user_snaps=user_snaps['snaps']['16'], user=flask.session['openid'])
def reset_password(utype,token): '''This function reset user password. Methods: ------- GET: it returns the reset password page POST: it reset password parameters: ---------- utype: the type of the user normal user or admin token: the token of the user ''' if is_authenticated(): return redirect(url_for('login')) model = AdminModel if utype == "admin" else UserModel data = model.verify_reset_token(token) #verify the token if data is None or data['user_type'] != utype: # the data['user_type'] != utype means if someone manually change the # usertype in form. so first check with the type in the token flash("Invalid or expird token", category="loginError") return redirect(url_for("forgot_password")) form = ResetPassForm() if form.validate_on_submit(): data['user'].password = pbkdf2_sha256.hash(form.new_password.data) db.session.commit() flash("Password Changed", category="addSuccess") return redirect(url_for('login')) return render_template("authentication/reset_pass.html", pass_form=form, token = token, utype=utype)
def admin_list(): """This function load users and return users list template.""" if not is_authenticated() or not is_admin(): return redirect(url_for('login')) users = load_users_admins(AdminModel) return render_template("admin/admin_list.html", users=users)
def email_is_unique(model, email, ftype): """This function query the table to check the email is unique or not. It is shared by both users and admins. for admins when they add new user or another admin. And for users when the update their profile info. parameters: ---------- model: model -- The model in whihc it has to search form email: str -- The value of email to be checked ftype: string -- Specify it checks for update or adding Return: boolean """ if not is_authenticated(): return redirect(url_for('login')) if ftype == 'add': row = model.query.filter_by(email=email).first() else: # now check email to be unique in all rows except the current one rows = model.query.filter_by(email=email).all() for row in rows: if row.id != current_user().id: return False row = None if row is not None: return False else: return True
def register_admin(): """This function load register admin page and add new admin. Return Page: if the request is get request Add new record: if the reqeuest if post request and form is validatad """ if not is_authenticated() or not is_admin() or not is_supper(): return redirect(url_for('login')) form = AdminRegisterForm() if request.method == "GET": return render_template("admin/register_admin.html", form = form) else: if form.validate(): if not email_is_unique(AdminModel, form.email.data, "add"): flash("email already taken", category="emailNotUnique") return render_template("admin/register_admin.html", form = form) else: admin = AdminModel(form.name.data, form.email.data.lower(), form.password.data) db.session.add(admin) db.session.commit() flash("Admin Created", category="addSuccess") return redirect(url_for('register_admin')) else: return render_template("admin/register_admin.html", form = form)
def change_password(): """This function change both users and amins password. It is accessable by both users and admin that is why we first access the is_admin() to check if it is an admin or not. """ if not is_authenticated(): return redirect(url_for('login')) admin = is_admin() form = AdminUpdateForm() if admin else UserUpdateForm() pass_form = changePasswordForm() redirect_page_url = "admin/edit_profile_admin.html" if admin \ else "edit_profile.html" redirect_url = "admin_manage_profile" if admin else "profile" user = current_user() if pass_form.validate(): if not verify_password(pass_form.old_password.data): flash("Invalid Password", category="old_pass_incorect") return render_template(redirect_page_url, form=form, pass_form=pass_form ) else: user.password = pbkdf2_sha256.hash(pass_form.new_password.data) db.session.commit() flash("Password Changed", category="addSuccess") return redirect(url_for(redirect_url)) else: return render_template(redirect_page_url, form=form, pass_form=pass_form )
def register(): """This function add new user. It can be accessed using two http methods. If the method is GET it ruturns the user registration form else it adds the user to database. """ if not is_authenticated() or not is_admin(): return redirect(url_for('login')) form = UserRegisterForm() if request.method == "GET": return render_template("admin/register.html", form = form) else: if form.validate(): if not email_is_unique(UserModel, form.email.data, "add"): flash("email already taken", category="emailNotUnique") return render_template("admin/register.html", form = form) else: user = UserModel(form.name.data, form.address.data, form.email.data.lower(), form.password.data) db.session.add(user) db.session.commit() flash("User Created", category="addSuccess") return redirect(url_for('register')) else: return render_template("admin/register.html", form = form)
def check_balance(): """This function call the generate reciept function for current balance.""" # redirct if user is already authenticated if not is_authenticated() or is_admin(): return redirect(url_for('login')) Recipt.balance_reciept() return redirect(request.referrer)
def delete_users(): """This function delete users""" if not is_authenticated() or not is_admin(): return redirect(url_for('login')) id = request.form.get("id") user = UserModel.query.get(id) db.session.delete(user) db.session.commit() flash("Recored Deleted", category="addSuccess") return redirect(request.referrer)
def login(): if authentication.is_authenticated(flask.session): return flask.redirect(oid.get_next_url()) root = authentication.request_macaroon() openid_macaroon = MacaroonRequest( caveat_id=authentication.get_caveat_id(root)) flask.session['macaroon_root'] = root return oid.try_login('https://login.ubuntu.com', ask_for=['email', 'nickname'], ask_for_optional=['fullname'], extensions=[openid_macaroon])
def about(msg): log_command_info('/about', msg) output_string = '' if is_authenticated(msg.chat.id): for k, v in KNOWN_COMMANDS.items(): output_string += '• {} :{}\n'.format(k, v) else: for k, v in NO_AUTH_KNOWN_COMMANDS.items(): output_string += '• {} :{}\n'.format(k, v) bot.send_message(msg.chat.id, "HepiR - v{}\nLately, I've been, I've been thinking\nI want you to be happier, I want you to use Zevere!~\n\nI understand the follow commands:\n{}\n...and I echo all regular messages you send to me so you will never be lonely ;).".format(VERSION, output_string), parse_mode="Markdown") return
def delete_admins(): """This function delete admiins. only by super admins. """ if not is_authenticated() or not is_admin() or not is_supper(): return redirect(url_for('admin_list')) id = request.form.get("id") user = AdminModel.query.get(id) if user.is_supper: return redirect(request.referrer) db.session.delete(user) db.session.commit() flash("Recored Deleted", category="addSuccess") return redirect(request.referrer)
def verify_password(password): """This function check the user password by hashing them parameters: ---------- password: the user typed password Return: Boolean """ if not is_authenticated(): return redirect(url_for('login')) user = current_user() result = pbkdf2_sha256.verify(password, user.password) return result
def enforce_authentication(msg): print('Inside enforce_authentication') # check if authenticated if is_authenticated(msg.chat.id): print('\ttg_id {} is authenticated!'.format(msg.chat.id)) # continues execution of attempted action return else: print('\ttg_id {} is not authenticated!'.format(msg.chat.id)) # terminate further execution of the attempted action bot.send_message( msg.chat.id, 'You are not logged into Zevere. Please login at {} and use the Login Widget provided on the Profile page after logging in :)!' .format(COHERENT_ROOT_URL)) raise Exception
def deposit_money(): """This function deposit money if the user is normal user.""" # redirct if user is already authenticated if not is_authenticated() or is_admin(): return redirect(url_for('login')) form = DepositMoneyForm() if request.method == "GET": return render_template("deposit.html", form=form) else: if form.validate(): current_user().balance += int(form.amount.data) db.session.commit() flash("Seccessfully Deposited", category="addSuccess") if form.reciept.data: Recipt.deposit_reciept(current_user().balance, form.amount.data) return redirect(url_for('deposit_money')) else: return render_template("deposit.html", form=form)
def send_reset_mail(utype, user): '''This function send reset password link''' if is_authenticated(): return redirect(url_for('login')) token = user.get_reset_token() user_type = "user" if utype == 1 else "admin" msg = Message("Password Reset Link", sender="*****@*****.**", recipients=[user.email] ) msg.html = f'''<div class="grey-bg container pt-4"> <div style = 'background: #f2f2f2; padding: 12px;'> <h4 style="text-align:center">Banking System</h4> </div> <hr> <div style="margin-top:30px; background: #fdfdfd; padding: 12px; border-radius: 8px;"> Hi <strong>{ user.name }</strong> <p class="pt-2"> You have recently requested to reset your password for Banking System. Click Button Bellow To Reset Your Password. </p> <div class="text-center"> <a href="{url_for('reset_password', utype=user_type, token=token, _external=True)}" class="btn btn-outline-primary btn-sm"> <button style="padding:6px; cursor:pointer">Reset Password </button> </a> </div> <hr> <p style="margin-top:30px"> If you did not request the reset password so please ignore this message. </p> <p> Regards. <br> <strong class="d-block">Banking System</strong> </p> </div> </div>''' mail.send(msg) return True
def profile(): """This function edit normal user profile.""" # redirct if user is already authenticated if not is_authenticated() or is_admin(): return redirect(url_for('login')) form = UserUpdateForm() pass_form = changePasswordForm() user = current_user() if request.method == "GET": form.name.data = user.name form.address.data = user.address form.email.data = user.email return render_template("edit_profile.html", form = form, \ pass_form = pass_form) else: if form.validate(): if not email_is_unique(UserModel, form.email.data, 'update'): flash("email already taken", category="emailNotUnique") return render_template("edit_profile.html", form=form, pass_form=pass_form) if verify_password(form.password_verify.data): user.name = form.name.data user.address = form.address.data user.email = form.email.data.lower() db.session.commit() flash("User Updated", category="addSuccess") return redirect(url_for('profile')) else: flash("Invalid Password", category="passwordIncorrect") return render_template("edit_profile.html", form=form, pass_form=pass_form) else: return render_template("edit_profile.html", form = form, \ pass_form = pass_form)
def admin_manage_profile(): """This function return edit form in get reques and update info in post.""" if not is_authenticated() or not is_admin(): return redirect(url_for('login')) form = AdminUpdateForm() pass_form = changePasswordForm() if request.method == "GET": form.name.data = current_user().name if current_user() else "" form.email.data = current_user().email if current_user() else "" return render_template("admin/edit_profile_admin.html", form=form, pass_form=pass_form ) else: if form.validate(): if not email_is_unique(AdminModel, form.email.data, 'update'): flash("email already taken", category="emailNotUnique") return render_template("admin/edit_profile_admin.html", form=form, pass_form=pass_form ) if verify_password(form.password_verify.data): user = current_user() user.name = form.name.data user.email = form.email.data.lower() db.session.commit() flash("Admin Updated", category="addSuccess") return redirect(url_for('admin_manage_profile')) else: flash("Invalid Password", category="passwordIncorrect") return render_template("admin/edit_profile_admin.html", form=form, pass_form=pass_form ) else: return render_template("admin/edit_profile_admin.html", form=form, pass_form=pass_form )
def index(): """This function returns index page if user is a normal user.""" # redirct if user is already authenticated if not is_authenticated() or is_admin(): return redirect(url_for('login')) return render_template("index.html")
def is_user_logged_in(*args, **kwargs): if not authentication.is_authenticated(flask.session): return redirect_to_login() return func(*args, **kwargs)
def logout(): if authentication.is_authenticated(flask.session): authentication.empty_session(flask.session) return flask.redirect('/')
def get_snap(snap_name): if not authentication.is_authenticated(flask.session): return redirect_to_login() authorization = authentication.get_authorization_header( flask.session['macaroon_root'], flask.session['macaroon_discharge']) headers = { 'X-Ubuntu-Series': '16', 'X-Ubuntu-Architecture': 'amd64', 'Authorization': authorization } url = 'https://api.snapcraft.io/api/v1/snaps/details/{}'.format(snap_name) response = requests.request(url=url, method='GET', headers=headers) verified_response = authentication.verify_response( response, flask.session, url, '/snaps/{}'.format(snap_name), '/login') if verified_response is not None: if verified_response['redirect'] is None: response.raise_for_status() return flask.redirect(verified_response.redirect) details = response.json() snap_id = details['snap_id'] url = 'https://dashboard.snapcraft.io/dev/api/snaps/metrics' yesterday = datetime.datetime.today() - datetime.timedelta(days=1) month_ago = yesterday - datetime.timedelta(days=30) data = { "filters": [ { "metric_name": "installed_base_by_channel", "snap_id": snap_id, "start": month_ago.strftime('%Y-%m-%d'), "end": yesterday.strftime('%Y-%m-%d') }, { "metric_name": "installed_base_by_operating_system", "snap_id": snap_id, "start": month_ago.strftime('%Y-%m-%d'), "end": yesterday.strftime('%Y-%m-%d') }, { "metric_name": "installed_base_by_version", "snap_id": snap_id, "start": month_ago.strftime('%Y-%m-%d'), "end": yesterday.strftime('%Y-%m-%d') }, ] } response = requests.request(url=url, method='POST', json=data, headers=headers) metrics = response.json() context = { 'details': details, 'metrics': metrics, } return flask.render_template('details.html', **context)
def homepage(): context = {} if authentication.is_authenticated(flask.session): context['connected'] = True return flask.render_template('index.html', **context)