def login_post(): if request.method == 'POST': form = LoginForm(request.form) if form.validate_on_submit(): user = db.session\ .query(User)\ .filter_by(user_name=form.user_name.data)\ .first() if user is not None: if User.decryptpassword(pwdhash=user.password_hash, password=form.password_hash.data): if user.locked == 0: user.fails = 0 db.session.add(user) db.session.commit() login_user(user) current_user.is_authenticated() current_user.is_active() return redirect(url_for('index')) else: return redirect(url_for('users.account_locked')) else: x = user.fails y = x + 1 user.fails = y db.session.add(user) db.session.commit() if int(user.fails) >= 5: user.locked = 1 db.session.add(user) db.session.commit() return redirect(url_for('users.account_locked')) else: flash("Please retry user name or password.", category="danger") return redirect(url_for('users.login')) else: flash("Please retry user name or password", category="danger") return redirect(url_for('users.login')) else: flash("Please retry user name or password.", category="danger") return redirect(url_for('users.login')) else: flash("Incorrect form.", category="danger") return redirect(url_for('index'))
def case2(id_input): if request.method == 'GET': data = {} if current_user.is_active(): this_scenario = current_user.scenarios.filter_by(id=id_input).first() data['id'] = id_input data['data'] = this_scenario.data data['isBaseCase'] = this_scenario.is_base data['name'] = this_scenario.name data['income_items'] = this_scenario.income_items data['basic_expenses'] = this_scenario.basic_expenses data['misc_expenses'] = this_scenario.misc_expenses data['debt_accounts'] = this_scenario.debt_accounts data['cash_accounts'] = this_scenario.cash_accounts return jsonify(**data),200 if request.method == 'PUT': data = {} for item in request.json: value = request.json[item] if item != 'data': print item,value data.update({item:value}) #print data s = build_demo7.build_demo7_data(data) if current_user.is_active(): #print data['id'] this_scenario = current_user.scenarios.filter_by(id=data['id']).first() #print this_scenario this_scenario.data = s this_scenario.name = data['name'] this_scenario.income_items = data['income_items'] this_scenario.basic_expenses = data['basic_expenses'] this_scenario.misc_expenses = data['misc_expenses'] this_scenario.debt_accounts = data['debt_accounts'] this_scenario.cash_accounts = data['cash_accounts'] db.session.add(this_scenario) db.session.commit() return json.dumps({'data':s}),200 if request.method == 'DELETE': #delete the object with corresponding id. return 200 status print 'DELETED CASE NUMBER ',id_input if current_user.is_active(): this_scenario = current_user.scenarios.filter_by(id=id_input).first() db.session.delete(this_scenario) db.session.commit() return '200'
def login(): error = None form = LoginForm() if current_user.is_active(): return redirect(url_for('landing_blueprint.index')) else: if request.method == 'POST': if form.validate_on_submit(): user = User.query.filter_by( username=request.form['username']).first() if user.role_id == 3: if user is not None and check_password_hash( user.password, request.form['password']): login_user(user) flash('You are now logged in!') # Get current user's friend requests and number of requests to display in badges received_friend_requests, sent_friend_requests = get_friend_requests( current_user.id) num_received_requests = len(received_friend_requests) num_sent_requests = len(sent_friend_requests) num_total_requests = num_received_requests + num_sent_requests # Use a nested dictionary for session["current_user"] to store more than just user_id session["current_user"] = { "first_name": current_user.first_name, "id": current_user.id, "num_received_requests": num_received_requests, "num_sent_requests": num_sent_requests, "num_total_requests": num_total_requests } if user.first_login == True: user.first_login = False db.session.add(user) db.session.commit() return redirect( url_for('auth_blueprint.edit', username=request.form['username'])) return redirect( url_for('auth_blueprint.home', name=request.form['username'])) elif user.role_id == 1: if user is not None and check_password_hash( user.password, request.form['password']): login_user(user) flash('You are now logged in!') return redirect( url_for('auth_blueprint.addash', name=request.form['username'])) else: return redirect(url_for('landing_blueprint.index')) else: error = 'Invalid username or password' return render_template('users/signin.html', form=form, error=error) else: error = 'Invalid username or password' return render_template('users/signin.html', form=form, error=error)
def register(): form = RegisterForm() Role.insert_roles() if current_user.is_active(): return redirect(url_for('landing_blueprint.index')) else: if form.validate_on_submit(): user = User(username=request.form['username'], email=request.form['email'], password=request.form['password'], role_id=3) db.session.add(user) db.session.commit() # Add same info to session for new user as per /login route session["current_user"] = { "first_name": user.first_name, "id": user.id, "num_received_requests": 0, "num_sent_requests": 0, "num_total_requests": 0 } flash('Log In') return redirect(url_for('auth_blueprint.login')) return render_template('users/registration.html', form=form)
def cancelar(id): if current_user.is_active() and current_user.session_over(): current_user.reset_token usuario = db.child('users').child(current_user.localId).get(current_user.idToken) usuario = dict(usuario.val()) despesa = db.child('despesas').child(id).get(current_user.idToken) despesa = dict(despesa.val()) pode_cancelar = (usuario['departamento'] == despesa['departamento'] or usuario['email'] == despesa['criado_por']) if pode_cancelar and despesa['status'] != '7': despesa['status'] = '7' try: despesa['modificado_por'] = current_user.email despesa['data_ult_alt'] = datetime.now().strftime('%d/%m/%Y') db.child('despesas').child(id).update(despesa, current_user.idToken) send_mail(despesa, current_user) except Exception as e: mensagem = 'Não foi possível atualizar essa despesa.' print(e) flash(mensagem) return redirect(url_for('despesas.listar'))
def on_identity_loaded(sender, identity): # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, 'user_id'): identity.provides.add(UserNeed(current_user.user_id)) # Assuming the User model has a list of roles, update the # identity with the roles that the user provides if hasattr(current_user, 'roles'): for role in current_user.roles: identity.provides.add(RoleNeed(role.name)) # Add Active/Pledge Roles if hasattr(current_user, 'active_member') and current_user.active_member is not None: identity.provides.add(RoleNeed("Active")) if hasattr(current_user, 'pledge_member') and current_user.pledge_member is not None: identity.provides.add(RoleNeed("Pledge")) # Add Member Role for all logged in users if current_user.is_active(): identity.provides.add(RoleNeed("Member"))
def post_deployment_file(username, deployment_id): deployment = db.Deployment.find_one({'_id':deployment_id}) user = db.User.find_one( {'username' : username } ) if not (deployment and user and deployment.user_id == user._id and (current_user.is_admin() or current_user == user)): raise StandardError("Unauthorized") # @TODO better response via ajax? retval = [] for name, f in request.files.iteritems(): if not name.startswith('file-'): continue safe_filename = f.filename # @TODO out_name = os.path.join(deployment.deployment_dir, safe_filename) with open(out_name, 'w') as of: f.save(of) retval.append((safe_filename, datetime.utcnow())) editable = current_user and current_user.is_active() and (current_user.is_admin() or current_user == user) return render_template("_deployment_files.html", files=retval, editable=editable)
def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.login() response = self.client.get('/logout', follow_redirects=True) self.assertIn(b'You were logged out. Bye!', response.data) self.assertFalse(current_user.is_active())
def post_deployment_file(username, deployment_id): deployment = db.Deployment.find_one({'_id': deployment_id}) user = db.User.find_one({'username': username}) if not (deployment and user and deployment.user_id == user._id and (current_user.is_admin() or current_user == user)): raise StandardError("Unauthorized") # @TODO better response via ajax? retval = [] for name, f in request.files.iteritems(): if not name.startswith('file-'): continue safe_filename = f.filename # @TODO out_name = os.path.join(deployment.full_path, safe_filename) with open(out_name, 'w') as of: f.save(of) retval.append((safe_filename, datetime.utcnow())) editable = current_user and current_user.is_active() and ( current_user.is_admin() or current_user == user) return render_template("_deployment_files.html", files=retval, editable=editable)
def test_reset_forgotten_password_valid_token_correct_login(self): # Ensure user can confirm account with valid token. with self.client: self.client.post('/forgot-password/', data=dict(email='*****@*****.**', ), follow_redirects=True) token = generate_confirmation_token('*****@*****.**') response = self.client.get('/password-reset/' + token + "/", follow_redirects=True) self.assertTemplateUsed('forgot_password_change.html') self.assertIn(b'Reset Password', response.data) response = self.client.post('/password-reset/' + token + "/", data=dict(password="******", confirm="new-password"), follow_redirects=True) self.assertIn(b'Successful password updated!', response.data) self.assertTemplateUsed('index.html') self.assertTrue(current_user.is_authenticated) self.client.get('/logout/') self.assertFalse(current_user.is_authenticated) response = self.client.post('/login/', data=dict( email="*****@*****.**", password="******"), follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTrue(current_user.email == "*****@*****.**") self.assertTrue(current_user.is_active()) self.assertTrue(current_user.is_authenticated) self.assertTemplateUsed('index.html')
def delete_deployment_files(username, deployment_id): deployment = db.Deployment.find_one({'_id': deployment_id}) user = db.User.find_one({'username': username}) if deployment is None: # @TODO better response via ajax? raise StandardError("Unauthorized") if user is None: # @TODO better response via ajax? raise StandardError("Unauthorized") if not (current_user and current_user.is_active() and (current_user.is_admin() or current_user == user)): # @TODO better response via ajax? raise StandardError("Unauthorized") if not (deployment and user and (current_user.is_admin() or user._id == deployment.user_id)): # @TODO better response via ajax? raise StandardError("Unauthorized") for name in request.json['files']: file_name = os.path.join(deployment.full_path, name) os.unlink(file_name) return ""
def delete_deployment(username, deployment_id): deployment = db.Deployment.find_one({'_id': deployment_id}) user = db.User.find_one({'username': username}) if deployment is None: flash("Permission denied", 'danger') return redirect( url_for("show_deployment", username=username, deployment_id=deployment_id)) if user is None: flash("Permission denied", 'danger') return redirect( url_for("show_deployment", username=username, deployment_id=deployment_id)) if not (current_user and current_user.is_active() and (current_user.is_admin() or current_user == user)): flash("Permission denied", 'danger') return redirect( url_for("show_deployment", username=username, deployment_id=deployment_id)) queue.enqueue_call(func=tasks.delete_deployment, args=(deployment_id, ), timeout=30) flash("Deployment queued for deletion", 'success') return redirect(url_for("list_user_deployments", username=username))
def criar(): if current_user.is_active() and current_user.session_over(): current_user.reset_token() if verify_dba(current_user): return redirect(url_for('despesas.listar')) form = UserForm() if form.validate_on_submit(): uid = form.uid.data usuario = { 'nome': form.nome.data, 'sobrenome': form.sobrenome.data, 'email': form.email.data, 'departamento': form.departamento.data, 'RD': form.representante.data, 'DBA': form.dba.data, 'Diretor': form.diretor.data } try: db.child('users').child(uid).update(usuario, current_user.idToken) return redirect(url_for('users.listar')) except Exception as e: mensagem = 'Não foi possível incluir este usuário.' print(e) flash(mensagem) return redirect(url_for('users.criar')) return render_template('users/criar.html', form=form)
def show_deployment(username, deployment_id): user = db.User.find_one({'username': username}) deployment = db.Deployment.find_one({'_id': deployment_id}) files = [] for dirpath, dirnames, filenames in os.walk(deployment.full_path): for f in filenames: if f in ["deployment.json", "wmoid.txt", "completed.txt" ] or f.endswith(".md5"): continue files.append((f, datetime.utcfromtimestamp( os.path.getmtime(os.path.join(dirpath, f))))) files = sorted(files, lambda a, b: cmp(b[1], a[1])) kwargs = {} form = DeploymentForm(obj=deployment) if current_user and current_user.is_active() and (current_user.is_admin() or current_user == user): kwargs['editable'] = True if current_user.is_admin() or current_user == user: kwargs['admin'] = True return render_template('show_deployment.html', username=username, form=form, deployment=deployment, files=files, **kwargs)
def register(): if current_user.is_active(): flash('You cannot register for an account while logged in.', 'danger') return redirect(url_for('index')) if app.config['REGISTRATIONS_OPEN'] is False: flash('Registrations are closed.', 'danger') return redirect(url_for('index')) form = RegisterForm() if form.validate_on_submit(): u = User(form.username.data, form.password.data, form.email.data, form.name.data) db.session.add(u) db.session.commit() if len(User.query.all()) == 1: u.admin = True db.session.add(u) db.session.commit() flash('As first user, you are automatically set as admin.', 'info') flash('Registered successfully', 'success') login_user(u) return redirect(url_for('index')) return render_template('register.html', form=form)
def demo7(): if current_user.is_active(): scenarios_query = current_user.scenarios.all() base_id = None other_ids = [] new_data = None if scenarios_query == []: data_exists = False data = { 'name':'Base Case', 'isBaseCase': True, 'income_items': {u'Salary': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}}, 'basic_expenses': {u'TV/Internet': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}, u'Food': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}, u'Housing': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}, u'Utilities': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}, u'Phone': {u'frequency': u'monthly', u'type': u'flatline', u'value':u'0'}, u'Gym': {u'frequency': u'monthly', u'type': u'flatline', u'value': u'0'}}, 'misc_expenses': {}, 'cash_accounts': {u'Checking': {u'rate': u'0', u'balance': u'0'}, u'Savings': {u'rate': u'0', u'balance': u'0'}, u'Investment': {u'rate': u'0', u'balance': u'0'}}, 'debt_accounts': {u'Credit Card': {u'rate': u'0', u'balance': u'0', u'payment': u'0'}, u'Student': {u'rate': u'0', u'balance': u'0', u'payment': u'0'}} } new_data = build_demo7.build_demo7_data(data) new_data = json.dumps(new_data) else: for scenario in scenarios_query: if scenario.is_base: base_id = scenario.id else: other_ids.append(scenario.id) data_exists = True return render_template('demo7.html',data_exists=data_exists,new_data=new_data, base_id=base_id, other_ids=other_ids) else: return redirect(url_for('login'))
def login(): if current_user.is_authenticated() and current_user.is_active(): print("User is active") return redirect(url_for('home.home')) if request.method == "POST": email = request.form['email'] password = request.form['password'] db_doc = getUsersTable().get_item(Key={'email': email}) next_url = request.args.get('next') if not is_safe_url(next_url): return abort(400) if 'Item' in db_doc and pass_check(password, db_doc['Item']['password']): login_user(User(db_doc['Item'])) return redirect(next_url or url_for('home.home')) else: flash("Your email or password is incorrect.", "danger") return redirect(url_for("login.login")) return render_template("login.html")
def skyward_page(): if not current_user.is_active(): return redirect("/profile?error=no_data") data = page_data("skyward") data.update(current_user.sky_data) data["url"] = "https://skyward.iscorp.com/scripts/wsisa.dll/WService={0}/sfhome01.w".format(current_user.service) return render_template("skyward.html.j2", **data)
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.username == "test": return True return False
def wrapped(*args, **kwargs): if not current_user.is_authenticated: return dict(message="login") if not current_user.is_active(): return dict(message="wait") return f(*args, **kwargs)
def login(): if current_user is not None and current_user.is_active(): return redirect(url_for('index')) form = LoginForm() if request.method == 'POST' and form.validate_on_submit(): login_user(form.user, remember=form.remember_me.data) return redirect(request.args.get("next") or url_for("index")) return render_template('login.html', title='Login', login_form=form)
def test_logout(self): with self.client: self.client.post('/login', data=dict(username="******", password="******"), follow_redirects=True) response = self.client.get('/logout', follow_redirects=True) self.assertIn(b'You were logged out', response.data) self.assertFalse(current_user.is_active())
def is_available(cls, username): blog = cls.query.filter_by(username=username).first() available = blog is None if current_user.is_active() and not available: # It's available if the user asking owns it available = current_user.id == blog.id # But not if it's been added to reserved list return available and not username in RESERVED_SLUGS
def test_user_registeration(self): with self.client: response = self.client.post('/register', \ data=dict(username="******", email="*****@*****.**", password="******", confirm="michael"), \ follow_redirects=True) self.assertIn(b'Your HIT', response.data) self.assertTrue(current_user.name == "Michael") self.assertTrue(current_user.is_active())
def test_logout(self): with self.client: self.client.post('/login', data=dict(username='******', password='******'), follow_redirects=True) response = self.client.get('/logout', follow_redirects=True) self.assertIn(b'You were just logged out', response.data) self.assertFalse(current_user.is_active())
def activate(token): if current_user.is_active(): flash(u'Вы уже подтвердили регистрацию', 'info') return redirect(url_for('index')) elif current_user.check_token(token): flash(u'Вы подтвердили регистрацию', 'success') return redirect(url_for('auth.login')) else: abort(404)
def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.login() self.assertIn(b'Welcome', response.data) self.assertIn(b'Logout', response.data) self.assertTrue(current_user.email == "*****@*****.**") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
def test_login_correct_credentials(self): with self.client: response = self.client.post('/login', data=dict(username='******', password='******'), follow_redirects=True) self.assertIn(b'You were just logged in', response.data) self.assertTrue(current_user.name == 'admin') self.assertTrue(current_user.is_active())
def demo(): if current_user.is_active(): all_users = User.query.all() available_shifts = Shift.query.all() posted_shifts = current_user.shifts_posted claimed_shifts = current_user.shifts_claimed return render_template('demo.html', all_users=all_users,available_shifts=available_shifts,posted_shifts=posted_shifts,claimed_shifts=claimed_shifts) else: return redirect(url_for('login'))
def test_correct_login(self): with self.client: response = self.client.post('/login', data=dict(username="******", password="******"), follow_redirects=True) self.assertIn(b'You were logged in', response.data) self.assertTrue(current_user.name == "admin") self.assertTrue(current_user.is_active())
def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post('/login', data=dict(email="*****@*****.**", password="******"), follow_redirects=True) response = self.client.get('/logout', follow_redirects=True) self.assertIn(b'You were logged out. Bye!', response.data) self.assertFalse(current_user.is_active())
def index(): if current_user is None or not current_user.is_active(): return landing_page() posts = current_user.posts_followed() user_projects = Project.query.filter_by( created_by_id=current_user.id).limit( config.PAGE_POSTS_MAX) # @UndefinedVariable return render_template('news_feed.html', posts=posts, projects=user_projects)
def decorated_view(*args, **kwargs): if current_app.login_manager._login_disabled: return func(*args, **kwargs) elif not current_user.is_authenticated() or not current_user.is_active( ): flash( 'To access this page, your application has first to be reviewed.' ) return redirect_back() return func(*args, **kwargs)
def profile(): if request.method == 'POST' and current_user.is_active(): user = current_user (error, success) = user.update_profile(request.form) if success is True: user.save() flash("Success!", "success") else: flash(error, "error") return render_template("views/profile.html", user=current_user)
def test_user_registration(self): with self.client: response = self.client.post( '/register', data=dict(username="******", email="*****@*****.**", password="******", confirm="testerpass"), follow_redirects=True ) self.assertIn(b'Watchlist', response.data) self.assertTrue(current_user.name == "tester") self.assertTrue(current_user.is_active())
def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( '/login', data=dict(email="*****@*****.**", password="******"), follow_redirects=True ) response = self.client.get('/logout', follow_redirects=True) self.assertIn(b'You were logged out. Bye!', response.data) self.assertFalse(current_user.is_active())
def test_user_registration(self): with self.client: response = self.client.post('/register', data=dict(username='******', email='*****@*****.**', password='******', confirm='testing'), follow_redirects=True) self.assertIn(b'Welcome to Flask', response.data) self.assertTrue(current_user.name == 'testing') self.assertTrue(current_user.is_active())
def test_user_registeration(self): with self.client: #tester = app.test_client(self) response = self.client.post( '/register/', data=dict(username="******",email="*****@*****.**", password="******", confirm="somchai"), follow_redirects = True ) self.assertIn(b'Welcome to Flask!', response.data) self.assertTrue(current_user.name == "somchai") self.assertTrue(current_user.is_active())
def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( '/register', data=dict(username="******", email='*****@*****.**', password="******", confirm="testing"), follow_redirects=True ) self.assertIn(b'Welcome', response.data) self.assertTrue(current_user.username == "tester") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
def test_user_registration(self): with self.client: response = self.client.post('/register', data=dict(username="******", email="*****@*****.**", password="******", confirm="adminadmin"), follow_redirects=True) self.assertIn(b'Welcome to Flask!', response.data) self.assertTrue(current_user.name == "admin") self.assertTrue(current_user.is_active()) user = User.query.filter_by(email='*****@*****.**').first() self.assertTrue(str(user) == '<name - admin>')
def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( '/login', data=dict(username='******', password='******'), follow_redirects=True ) self.assertIn(b'Welcome', response.data) self.assertIn(b'Logout', response.data) self.assertIn(b'Members', response.data) self.assertTrue(current_user.username == 'ad@min') self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200)
def demo3(): if current_user.is_active(): scenarios_query = current_user.scenarios.all() if scenarios_query == []: scenarios = None data_exists = False else: scenarios = [] for scenario in scenarios_query: scenarios.append(scenario.data) data_exists = True return render_template('demo3.html',data_exists=data_exists,s=scenarios) else: return redirect(url_for('login'))
def edit_sheet(owner, name): sheet = db.sheets.find_one({'name':name, 'owner':owner}) if not sheet or ('public' in sheet and not sheet['public'] and current_user.username != owner): #temporary old sheets migration if owner == 'unknow': sheet = db.sheets.find_one({'name':name, 'owner':{'$exists':False}}) if sheet: if current_user.is_active(): sheet['public'] = True sheet['owner'] = current_user.username else: return redirect(url_for('index')) else: #temporary ends return redirect(url_for('index')) if request.method == 'POST': cheat_sheet_pre = request.form.to_dict() cheat_sheet = {} #default inmutable values cheat_sheet['name'] = sheet['name'] cheat_sheet['owner'] = sheet['owner'] cheat_sheet['public'] = sheet['public'] if 'public' in sheet else True #changes cheat_sheet['description'] = cheat_sheet_pre['description'] if current_user.username == sheet['owner']: cheat_sheet['public'] = 'public' in cheat_sheet_pre index = 1 variables = {} while ('key%d' % index) in cheat_sheet_pre: variables[cheat_sheet_pre['key%d' % index]] = cheat_sheet_pre['value%d' % index] index += 1; cheat_sheet['variables'] = variables db.sheets.update({'name':name, 'owner':owner}, cheat_sheet) #temporary old sheet migration if owner == 'unknow': db.sheets.update({'name':name, 'owner':{'$exists':False}}, cheat_sheet) #temporary ends return redirect(url_for('view_sheet', owner=cheat_sheet['owner'], name=cheat_sheet['name'])) return render_template('edit.html', sheet = sheet)
def login(): if current_user.is_active(): flash("Already logged in", 'warning') return redirect(request.args.get("next") or url_for("index")) form = LoginForm() if form.validate_on_submit(): user = User.authenticate(form.username.data, form.password.data) if not user: flash("Failed", 'danger') return redirect(url_for("login")) login_user(user) flash("Logged in successfully", 'success') return redirect(request.args.get("next") or url_for("index")) response = make_response(render_template("login.html", form=form)) return response
def demo6(): if current_user.is_active(): scenarios_query = current_user.scenarios.all() base_id = None other_ids = [] if scenarios_query == []: data_exists = False else: for scenario in scenarios_query: if scenario.is_base: base_id = scenario.id else: other_ids.append(scenario.id) data_exists = True return render_template('demo6.html',data_exists=data_exists, base_id=base_id, other_ids=other_ids) else: return redirect(url_for('login'))
def test_valid_login(self): user = User(name='Test', email='*****@*****.**', password='******', role='user', active=True) db.session.add(user) db.session.commit() with self.client: response = self.client.post(self.url, data={ 'email': '*****@*****.**', 'password': '******' }) self.assertRedirects(response, '/') self.assertTrue(current_user.is_active()) self.assertTrue(current_user.is_authenticated()) self.assertFalse(current_user.is_anonymous())
def view_sheet(owner, name): sheet = db.sheets.find_one({'name':name, 'owner':owner}) if not sheet or ('public' in sheet and not sheet['public'] and current_user.username != owner): #temporary old sheets migration if owner == 'unknow': sheet = db.sheets.find_one({'name':name, 'owner':{'$exists':False}}) if sheet: if current_user.is_active(): sheet['public'] = True sheet['owner'] = 'unknow' return render_template('view.html', sheet = sheet) #temporary ends return redirect(url_for('index')) return render_template('view.html', sheet = sheet)
def vote_thank_you(): """ Display the thank you page. :return: Render the thank you page. """ if not current_user.is_active(): logger.add_log(20, 'Voter {0} finished voting. Accessing thank you page.'.format(current_user.id) ) return render_template('{0}/thank-you.html'.format(Settings.get_property_value('current_template'))) logger.add_log(20, 'Someone attempted to visit the thank you. Not sure if it was a voter, admin, or someone anonymous.' ) return redirect('/')
def delete_deployment(username, deployment_id): deployment = db.Deployment.find_one({'_id': deployment_id}) user = db.User.find_one({'username': username}) if deployment is None: flash("Permission denied", 'danger') return redirect(url_for("show_deployment", username=username, deployment_id=deployment_id)) if user is None: flash("Permission denied", 'danger') return redirect(url_for("show_deployment", username=username, deployment_id=deployment_id)) if not (current_user and current_user.is_active() and (current_user.is_admin() or current_user == user)): flash("Permission denied", 'danger') return redirect(url_for("show_deployment", username=username, deployment_id=deployment_id)) queue.enqueue_call(func=tasks.delete_deployment, args=(deployment_id,), timeout=30) flash("Deployment queued for deletion", 'success') return redirect(url_for("list_user_deployments", username=username))
def list_user_deployments(username): user = db.User.find_one( {'username' : username } ) deployments = list(db.Deployment.find( { 'user_id' : user._id } )) kwargs = {} if current_user and current_user.is_active() and (current_user.is_admin() or current_user == user): # Permission to edit form = NewDeploymentForm() kwargs['form'] = form for m in deployments: if not os.path.exists(m.deployment_dir): # wat continue m.updated = datetime.utcfromtimestamp(os.path.getmtime(m.deployment_dir)) deployments = sorted(deployments, lambda a, b: cmp(b.updated, a.updated)) return render_template('user_deployments.html', username=username, deployments=deployments, **kwargs)
def submit_demo2(): income = {} basic_expenses = {} debt_expenses = {} misc_expenses = {} debt_balances = {} cash_balances = {} rates = {} print request.form for item in request.form: print item, request.form[item] if request.form[item] == '' or request.form[item] == None: item_value = 0 else: item_value = request.form[item].replace(",", "") prefix = item[:3] if prefix == "in_": income.update({item[3:]: item_value}) elif prefix == "be_": basic_expenses.update({item[3:]: item_value}) elif prefix == "de_": debt_expenses.update({item[3:]: item_value}) elif prefix == "me_": misc_expenses.update({item[3:]: item_value}) elif prefix == "ba_": debt_balances.update({item[3:]: item_value}) elif prefix == "cb_": cash_balances.update({item[3:]: item_value}) elif prefix == "ra_": rates.update({item[3:]: float(item_value)/100.0}) print rates s = build_ss_in_python.build_ss(income, basic_expenses, debt_expenses, misc_expenses, debt_balances, cash_balances, rates) print s if current_user.is_active(): current_user.data = s db.session.add(current_user) db.session.commit() return redirect(url_for('demo2_output'))
def show_deployment(username, deployment_id): user = db.User.find_one( {'username' : username } ) deployment = db.Deployment.find_one({'_id':deployment_id}) files = [] for dirpath, dirnames, filenames in os.walk(deployment.deployment_dir): for f in filenames: if f in ["deployment.json", "wmoid.txt", "completed.txt"] or f.endswith(".md5"): continue files.append((f, datetime.utcfromtimestamp(os.path.getmtime(os.path.join(dirpath, f))))) files = sorted(files, lambda a,b: cmp(b[1], a[1])) kwargs = {} form = DeploymentForm(obj=deployment) if current_user and current_user.is_active() and (current_user.is_admin() or current_user == user): kwargs['editable'] = True if current_user.is_admin(): kwargs['admin'] = True return render_template('show_deployment.html', username=username, form=form, deployment=deployment, files=files, **kwargs)
def case(): if request.method == 'POST': data = {} for item in request.json: value = request.json[item] if item != 'data': print item,value data.update({item:value}) #print data s = build_demo7.build_demo7_data(data) if current_user.is_active(): new_scenario = Scenario(s, data['name'], data['income_items'], data['basic_expenses'], data['misc_expenses'], data['debt_accounts'], data['cash_accounts']) if data['isBaseCase']: new_scenario.is_base = True current_user.scenarios.append(new_scenario) db.session.add(current_user) db.session.flush() this_id = new_scenario.id db.session.commit() data.update({'id':this_id,'data':s}) return json.dumps(data),200
def app_index(): """ Index page of the whole app. This page will show different looks depending on the current user state. :return: Render the appropriate template depending on the user status. """ login_form = LoginForm() logger.add_log(20, 'Accessing index page.' ) if current_user.is_authenticated: logger.add_log(20, 'Current user is authenticated. Displaying voting page.') if current_user.role != 'voter': logger.add_log(20, 'Logged in user is an admin. Redirecting to the admin panel.' ) return redirect('/admin') elif current_user.is_active(): logger.add_log(20, 'Logged in user is a voter. Displaying the voting page.' ) return render_template('{0}/voting.html'.format(Settings.get_property_value('current_template')), voting_form=generate_voting_form(), link_handler=generate_js_script() ) logger.add_log(20, 'Current visitor is anonymous or inactive. Might need to say "Who you? You ain\'t my n***a."' ) # TODO: Make the index template. return render_template('{0}/index.html'.format(Settings.get_property_value('current_template')), form=login_form )
def submit_demo3(): names = {0:''} income = {0:{}} basic_expenses = {0:{}} debt_expenses = {0:{}} misc_expenses = {0:{}} debt_balances = {0:{}} cash_balances = {0:{}} rates = {0:{}} print request.form scenarios = [] for item in request.form: print item, request.form[item] if request.form[item] == '' or request.form[item] == None: item_value = 0 else: item_value = request.form[item].replace(",", "") prefix = item[:3] item_name = item[3:-2] scenario = int(item[-1]) if scenario not in scenarios: names.update({scenario:''}) income.update({scenario:{}}) basic_expenses.update({scenario:{}}) debt_expenses.update({scenario:{}}) misc_expenses.update({scenario:{}}) debt_balances.update({scenario:{}}) cash_balances.update({scenario:{}}) rates.update({scenario:{}}) scenarios.append(scenario) if prefix == "na_": names[scenario] = item_value elif prefix == "in_": income[scenario].update({item_name: item_value}) elif prefix == "be_": basic_expenses[scenario].update({item_name: item_value}) elif prefix == "de_": debt_expenses[scenario].update({item_name: item_value}) elif prefix == "me_": misc_expenses[scenario].update({item_name: item_value}) elif prefix == "ba_": debt_balances[scenario].update({item_name: item_value}) elif prefix == "cb_": cash_balances[scenario].update({item_name: item_value}) elif prefix == "ra_": rates[scenario].update({item_name: float(item_value)/100.0}) #print rates #scenario_count = len(scenarios) print 'cash_balances: \n',cash_balances print 'rates: \n',rates d = build_demo3.build_demo3_data(names, income, basic_expenses, debt_expenses, misc_expenses, debt_balances, cash_balances, rates, scenarios) if current_user.is_active(): #remove existing scenarios scenarios_query = current_user.scenarios.all() for scenario in scenarios_query: db.session.delete(scenario) for scenario in range(0,len(scenarios)): #for scenario in range(0,1): new_scenario = Scenario(d[scenario]) if scenario == 0: new_scenario.is_base = True current_user.scenarios.append(new_scenario) #current_user.data = d[0] db.session.add(current_user) db.session.commit() return redirect(url_for('demo3_output_detail'))