def change_password(): user = None if current_user.is_authenticated(): if not login_fresh(): return login_manager.needs_refresh() user = current_user elif 'activation_key' in request.values and 'email' in request.values: activation_key = request.values['activation_key'] email = request.values['email'] user = User.query.filter_by(activation_key=activation_key) \ .filter_by(email=email).first() if user is None: abort(403) form = ChangePasswordForm(activation_key=user.activation_key) if form.validate_on_submit(): user.password = form.password.data user.activation_key = None db.session.add(user) db.session.commit() flash(_("Your password has been changed, please log in again"), "success") return redirect(url_for("frontend.login")) return render_template("frontend/change_password.html", form=form)
def homepage(): """Renders the homepage.""" build_list = list( models.Build.query .filter_by(public=True) .order_by(models.Build.created.desc()) .limit(1000)) if current_user.is_authenticated(): if not login_fresh(): logging.debug('User needs a fresh token') abort(login.needs_refresh()) auth.claim_invitations(current_user) # List builds you own first, followed by public ones. # TODO: Cache this list db.session.add(current_user) build_list = list( current_user.builds .order_by(models.Build.created.desc()) .limit(1000)) + build_list return _render_template_with_defaults( 'home.html', build_list=build_list)
def change_password(): user = None if current_user.is_authenticated(): if not login_fresh(): return login_manager.needs_refresh() user = current_user elif 'activation_key' in request.values and 'email' in request.values: activation_key = request.values['activation_key'] email = request.values['email'] user = User.query.filter_by(activation_key=activation_key) \ .filter_by(email=email).first() if user is None: abort(403) form = ChangePasswordForm(activation_key=user.activation_key) if form.validate_on_submit(): user.password = form.password.data user.activation_key = None db.session.add(user) db.session.commit() flash(_("Your password has been changed, please log in again"), "success") return redirect(url_for("frontend.login")) return render_template("change_password.html", form=form)
def login(): if current_user is not None and current_user.is_authenticated() and login_fresh(): return redirect_next() else: form = LoginForm(request.form) if request.method == 'POST' and form.validate(): try: authenticate(username=form.email.data, password=form.password.data) # Set session timeout session.permanent = True app.permanent_session_lifetime = app.config.get('SESSION_TIMEOUT', timedelta(minutes=30)) flash('Welcome Back!', 'info') # Because shit can break session['_fresh'] = True session.update() if request.args.get('next'): return redirect_next() else: return redirect(url_for('user.profile')) except: app.logger.info('Invalid login attempt for username %s' % form.email.data) flash('Invalid username/password', 'error') return redirect(url_for('auth.login', next=request.args.get('next', '/'))) context = { 'title': 'Login', 'description': 'Login form for BreezeMinder.com to access Breeze cards and MARTA reminders', 'form': form } return render_template('auth/login.html', **context)
def inner(*args, **kwargs): if not current_user.is_authenticated(): return login_manager.unauthorized() if not login_fresh(): return login_manager.needs_refresh() if should_update_email(): return redirect_update_email() return method(*args, **kwargs)
def inner(*args, **kwargs): if not current_user.is_authenticated(): return login_manager.unauthorized() if not current_user.is_admin: flash(_("Only admin can view this page!"), 'danger') return redirect(url_for('index')) if not login_fresh(): return login_manager.needs_refresh() return method(*args, **kwargs)
def delete_post_get(id): post = session.query(Post).filter(Post.id == id).one() if int(current_user.get_id()) == post.author.id and login_fresh(): return render_template('delete.html', post=post ) else: flash('You cannot delete posts which you did not author. Login as {} to delete "{}"'.format(post.author.name,post.title), 'danger') return redirect(url_for('posts'))
def homepage(): """Renders the homepage.""" if current_user.is_authenticated(): if not login_fresh(): logging.debug('User needs a fresh token') abort(login.needs_refresh()) auth.claim_invitations(current_user) build_list = operations.UserOps(current_user.get_id()).get_builds() return render_template('home.html', build_list=build_list)
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. """ build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) if not build_id: logging.debug('Build ID in param_name=%r was missing', param_name) abort(400) ops = operations.UserOps(current_user.get_id()) build, user_is_owner = ops.owns_build(build_id) if not build: logging.debug('Could not find build_id=%r', build_id) abort(404) if current_user.is_authenticated() and not user_is_owner: # Assume the user should be able to access the build but can't because # the cache is out of date. This forces the cache to repopulate, any # outstanding user invitations to be completed, hopefully resulting in # the user having access to the build. ops.evict() claim_invitations(current_user) build, user_is_owner = ops.owns_build(build_id) if not user_is_owner: if current_user.is_authenticated() and current_user.superuser: pass elif request.method != 'GET': logging.debug('No way to log in user via modifying request') abort(403) elif build.public: pass elif current_user.is_authenticated(): logging.debug('User does not have access to this build') abort(flask.Response('You cannot access this build', 403)) else: logging.debug('Redirecting user to login to get build access') abort(login.unauthorized()) elif not login_fresh(): logging.debug('User login is old; forcing refresh') abort(login.needs_refresh()) return build
def login(): if login_fresh(): return redirect(url_for("admin.main")) form = LoginForm() if form.validate_on_submit(): user = User.objects(username=form.username.data).first() if user is not None and user.verify_password(form.password.data): session["username"] = user.username login_user(user, form.remember) return redirect(url_for("admin.main")) flash(u"用户名或密码错误", 'danger') return render_template("login.html", form=form)
def reauth(): """ Reauthenticates a user """ if not login_fresh(): form = ReauthForm(request.form) if form.validate_on_submit(): confirm_login() flash(("Reauthenticated"), "success") return redirect(request.args.get("next") or url_for("user.profile")) return render_template("auth/reauth.html", form=form) return redirect(request.args.get("next") or url_for("user.profile", username=current_user.username))
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. """ build_id = (request.args.get(param_name, type=int) or request.form.get(param_name, type=int) or request.json[param_name]) if not build_id: logging.debug('Build ID in param_name=%r was missing', param_name) abort(400) ops = operations.UserOps(current_user.get_id()) build, user_is_owner = ops.owns_build(build_id) if not build: logging.debug('Could not find build_id=%r', build_id) abort(404) if current_user.is_authenticated() and not user_is_owner: # Assume the user should be able to access the build but can't because # the cache is out of date. This forces the cache to repopulate, any # outstanding user invitations to be completed, hopefully resulting in # the user having access to the build. ops.evict() claim_invitations(current_user) build, user_is_owner = ops.owns_build(build_id) if not user_is_owner: if current_user.is_authenticated() and current_user.superuser: pass elif build.public: pass elif request.method != 'GET': logging.debug('No way to log in user via modifying request') abort(403) elif current_user.is_authenticated(): logging.debug('User does not have access to this build') abort(flask.Response('You cannot access this build', 403)) else: logging.debug('Redirecting user to login to get build access') abort(login.unauthorized()) elif not login_fresh(): logging.debug('User login is old; forcing refresh') abort(login.needs_refresh()) return build
def sign_in(): if current_user and current_user.is_authenticated: return redirect(url_for('main.choose_service')) form = LoginForm() if form.validate_on_submit(): user = user_api_client.get_user_by_email_or_none(form.email_address.data) user = _get_and_verify_user(user, form.password.data) if user and user.state == 'pending': flash("You haven't verified your email or mobile number yet.") return redirect(url_for('main.sign_in')) if user and session.get('invited_user'): invited_user = session.get('invited_user') if user.email_address != invited_user['email_address']: flash("You can't accept an invite for another person.") session.pop('invited_user', None) abort(403) else: invite_api_client.accept_invite(invited_user['service'], invited_user['id']) if user: # Remember me login if not login_fresh() and \ not current_user.is_anonymous and \ current_user.id == user.id and \ user.is_active: confirm_login() services = service_api_client.get_services({'user_id': str(user.id)}).get('data', []) if (len(services) == 1): return redirect(url_for('main.service_dashboard', service_id=services[0]['id'])) else: return redirect(url_for('main.choose_service')) session['user_details'] = {"email": user.email_address, "id": user.id} if user.is_active: user_api_client.send_verify_code(user.id, 'sms', user.mobile_number) if request.args.get('next'): return redirect(url_for('.two_factor', next=request.args.get('next'))) else: return redirect(url_for('.two_factor')) # Vague error message for login in case of user not known, locked, inactive or password not verified flash(Markup(( "The email address or password you entered is incorrect." " <a href={password_reset}>Forgot your password</a>?" ).format(password_reset=url_for('.forgot_password')) )) return render_template('views/signin.html', form=form)
def homepage(): """Renders the homepage.""" if current_user.is_authenticated(): if not login_fresh(): logging.debug('User needs a fresh token') abort(login.needs_refresh()) auth.claim_invitations(current_user) build_list = operations.UserOps(current_user.get_id()).get_builds() return render_template( 'home.html', build_list=build_list, show_video_and_promo_text=app.config['SHOW_VIDEO_AND_PROMO_TEXT'])
def homepage(): """Renders the homepage.""" if current_user.is_authenticated(): if not login_fresh(): logging.debug('User needs a fresh token') abort(login.needs_refresh()) auth.claim_invitations(current_user) build_list = operations.UserOps(current_user.get_id()).get_builds() return render_template( 'home.html', build_list=build_list)
def reauthenticate(): # This isn't wrapped with login_required because it wouldn't make sense # to require a login to access the reauthenticate page. Instead, the # following if statement takes its place. if not current_user.is_authenticated or login_fresh(): return redirect(url_for('main.index')) form = ReauthenticationForm() if form.validate_on_submit(): if verify_password(current_user, form.password.data): confirm_login() LogEvent.reauthenticate(current_user) return form.redirect('main.index') flash_it(AuthMessages.INVALID_PASSWORD) return render_template('auth/reauthenticate.html', form=form)
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. """ build_id = ( request.args.get(param_name, type=int) or request.form.get(param_name, type=int)) if not build_id: logging.debug('Build ID in param_name=%r was missing', param_name) abort(400) build = models.Build.query.get(build_id) if not build: logging.debug('Could not find build_id=%r', build_id) abort(404) user_is_owner = False if current_user.is_authenticated(): user_is_owner = build.is_owned_by(current_user.id) if not user_is_owner: claim_invitations(current_user) user_is_owner = build.is_owned_by(current_user.id) if not user_is_owner: if request.method != 'GET': logging.debug('No way to log in user via modifying request') abort(403) elif build.public: pass elif current_user.is_authenticated() and current_user.superuser: pass elif current_user.is_authenticated(): logging.debug('User does not have access to this build') abort(flask.Response('You cannot access this build', 403)) else: logging.debug('Redirecting user to login to get build access') abort(login.unauthorized()) elif not login_fresh(): logging.debug('User login is old; forcing refresh') abort(login.needs_refresh()) return build
def reauth(): """ Reauthenticates a user """ if not login_fresh(): form = ReauthForm(request.form) if form.validate_on_submit(): confirm_login() flash(("Reauthenticated"), "success") return redirect( request.args.get("next") or url_for("user.profile")) return render_template("auth/reauth.html", form=form) return redirect( request.args.get("next") or url_for("user.profile", username=current_user.username))
def change_password(): user = None email = None if 'activation_key' in request.values and 'email' in request.values: activation_key = request.values['activation_key'] email = request.values['email'] session['activation_key'] = activation_key session['email'] = email user = User.query.filter_by(activation_key=activation_key) \ .filter_by(email=email).first() elif current_user.is_authenticated(): if not login_fresh(): return login_manager.needs_refresh() user = current_user else: if 'email' and 'activation_key' in session: email = session['email'] activation_key = session['activation_key'] user = User.query.filter_by(activation_key=activation_key) \ .filter_by(email=email).first() if not user: abort(403) form = ChangePasswordForm(activation_key=user.activation_key) if form.validate_on_submit(): user.password = form.password.data user.activation_key = None db.session.add(user) db.session.commit() session.pop('email', None) session.pop('activation_code', None) if current_user.is_authenticated(): flash(_(u"Your password has been changed, please log in again"), #Your password has been changed, please log in again "success") return redirect(url_for("user.index", email=email)) else: flash(_(u"Your password has been changed, please log in again"), #Your password has been changed, please log in again "success") return redirect(url_for("frontend.login", email=email)) return render_template("change_password.html", newtaskform = TaskForm(), form=form)
def join_get(id=None): c = campaign.get(id) if c is None: return "Unknown campaign.", 404 timestamp_ms = calendar.timegm(c.end.timetuple()) * 1000 _campaign = dict(id=c.id, amount=c.amount, end=timestamp_ms, name=c.name, suggestedContribution=c.suggested_contribution, contributionRequired=string_to_bool(c.suggested_contribution_required)) context = dict(campaign=_campaign, stripe_publishable_key=app.config.get('STRIPE_PUBLIC_KEY'), loggedIn=not current_user.is_anonymous(), success_response="""{"name": "%s", "date": 0, "charge": {"initial": "0", "final": "0"}, "fees": []}""" % c.name) context['require_login'] = not login_fresh() return render_template('pool/join.html', **context)
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. """ build_id = request.args.get(param_name, type=int) or request.form.get(param_name, type=int) if not build_id: logging.debug("Build ID in param_name=%r was missing", param_name) abort(400) build = models.Build.query.get(build_id) if not build: logging.debug("Could not find build_id=%r", build_id) abort(404) user_is_owner = False if current_user.is_authenticated(): user_is_owner = build.owners.filter_by(id=current_user.get_id()).first() if not user_is_owner: if request.method != "GET": logging.debug("No way to log in user via modifying request") abort(403) elif build.public: pass elif current_user.is_authenticated() and current_user.superuser: pass elif current_user.is_authenticated(): logging.debug("User does not have access to this build") abort(flask.Response("You cannot access this build", 403)) else: logging.debug("Redirecting user to login to get build access") abort(login.unauthorized()) elif not login_fresh(): logging.debug("User login is old; forcing refresh") abort(login.needs_refresh()) return build
def reauth(): """ User re authentication view """ app.logger.debug('User reauth') form = ReauthForm(next=request.args.get('next', None)) #if the login is fresh there is no need to re-authenticate if login_fresh(): return redirect(generate_redirect_url(next_=form.next.data)) if form.validate_on_submit(): user, authenticated = authenticate(current_user.get_username(), form.password.data) if user and authenticated: user.set_last_signon() confirm_login() return redirect(generate_redirect_url(next_=form.next.data)) else: flash('Sorry, invalid login parameters', 'error') return render_template('reauth.html', form=form)
def join_get(id=None): c = campaign.get(id) if c is None: return "Unknown campaign.", 404 timestamp_ms = calendar.timegm(c.end.timetuple()) * 1000 _campaign = dict(id=c.id, amount=c.amount, end=timestamp_ms, name=c.name, suggestedContribution=c.suggested_contribution, contributionRequired=string_to_bool( c.suggested_contribution_required)) context = dict( campaign=_campaign, stripe_publishable_key=app.config.get('STRIPE_PUBLIC_KEY'), loggedIn=not current_user.is_anonymous(), success_response= """{"name": "%s", "date": 0, "charge": {"initial": "0", "final": "0"}, "fees": []}""" % c.name) context['require_login'] = not login_fresh() return render_template('pool/join.html', **context)
def login(): if g.user is not None and g.user.is_authenticated() and login_fresh(): return redirect(url_for('index')) else: form = LoginForm() if form.validate_on_submit(): username = User.query.filter_by(username=form.username.data).first() # TODO - make username matching case-insensitive if not username or not username.verify_password(form.password.data): flash("That username and password combination do not match our records. Please try again.") else: remember_me = form.remember_me.data login_user(username, remember=remember_me) flash("Logged in successfully. Welcome, %s!" % username.username) return redirect(url_for('index')) else: flash_errors(form) return render_template( 'login.html', form=form )
def test_login_user_not_fresh(self): with self.app.test_request_context(): result = login_user(notch, fresh=False) self.assertTrue(result) self.assertEqual(current_user.name, u'Notch') self.assertIs(login_fresh(), False)
def is_fresh(): return unicode(login_fresh())
def is_authenticated(self): # To handle remember me token renewal if not login_fresh(): return False return super(User, self).is_authenticated