def test_user(): ''' this part is used to test the session working or not ''' print current_user.is_authenticated() print current_user.name return str(current_user.is_authenticated()) + current_user.email
def send_static_file(self, filename): protected_templates = ['partials/dashboard.html', 'partials/onboarding/stick.html'] print current_user.is_authenticated() # Get user from session if current_user.is_authenticated() or filename not in protected_templates: return super(SecuredStaticFlask, self).send_static_file(filename) else: return redirect('/static/partials/login.html')
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.is_authenticated(): return True '''if current_user.has_role('admin'): return True''' return False
def send_static_file(self, filename): protected_templates = [ 'partials/dashboard.html', 'partials/onboarding/stick.html' ] print current_user.is_authenticated() # Get user from session if current_user.is_authenticated( ) or filename not in protected_templates: return super(SecuredStaticFlask, self).send_static_file(filename) else: return redirect('/static/partials/login.html')
def committees(): """ Page through all available committees. """ committees = load_from_api('v2/committees', return_everything=True, fields=['id', 'name', 'premium', 'ad_hoc', 'house'])['results'] nat = { 'name': 'National Assembly', 'committees': [] } ncp = { 'name': 'National Council of Provinces', 'committees': [] } jnt = { 'name': 'Joint Committees', 'committees': [] } adhoc_committees = OrderedDict((('nat', nat), ('ncp', ncp), ('jnt', jnt))) reg_committees = deepcopy(adhoc_committees) committees_type = None for committee in committees: if committee['ad_hoc'] is True: committees_type = adhoc_committees else: committees_type = reg_committees if current_user.is_authenticated(): user_following = current_user.following # Check if user is following committee if current_user.is_authenticated() and committee['id'] in [ufc.id for ufc in user_following]: committee['followed'] = True if committee['house']: if committee['house']['id'] is Committee.NATIONAL_ASSEMBLY: committees_type['nat']['committees'].append(committee) elif committee['house']['id'] is Committee.NAT_COUNCIL_OF_PROV: committees_type['ncp']['committees'].append(committee) elif committee['house']['id'] is Committee.JOINT_COMMITTEE: committees_type['jnt']['committees'].append(committee) return render_template( 'committee_list.html', reg_committees=reg_committees, adhoc_committees=adhoc_committees )
def google_analytics_oauth(): print 'inside connect/google-analytics' google_analytics_callback_url = current_app.config.get('GOOGLE_ANALYTICS_CALLBACK_URL') google_analytics_client_id = current_app.config.get('GOOGLE_ANALYTICS_CLIENT_ID') if not current_user.is_authenticated(): print 'not logged in' return redirect(url_for('index')) username = current_user.email GA_API = GoogleAnalyticsAPI(username) print 'got google analytics API' if GA_API.credentials: print 'inside GA_API.credentials if' expires_on = GA_API.credentials.token_expiry current_time = datetime.datetime.now() # if credentials have not expired if expires_on > current_time: print GA_API.credentials.as_dict() # you shouldn't have hit this link print "you have credentials for GA" return jsonify(status=200, credentials=True) else: print "credentials expired, start oauth process" # start OAuth process redirect_url = GA_API.step_one(google_analytics_callback_url, google_analytics_client_id) return jsonify(redirect_url=redirect_url, status=100) else: print "start oauth process" # start OAuth process redirect_url = GA_API.step_one(google_analytics_callback_url, google_analytics_client_id) return jsonify(redirect_url=redirect_url, status=100)
def before_request(): if current_user.is_authenticated(): current_user.ping() if not current_user.is_anonymous(): g.user = current_user else: g.user = None
def bookmarks(): if current_user.is_authenticated(): events = current_user.bookmarked return render_template('events/collection.jade', events=events, title='Your bookmarks', empty_msg='You haven\'t bookmarked anything!') else: flash('You need to be logged in') return redirect(url_for('security.login'))
def watching(): if current_user.is_authenticated(): events = models.Event.query.join(models.Event.stories).filter(models.Event.stories.any(models.Story.id.in_([story.id for story in current_user.watching]))).all() return render_template('events/collection.jade', events=events, title='The latest from stories you\'re watching', empty_msg='You aren\'t watching any stories!') else: flash('You need to be logged in') return redirect(url_for('security.login'))
def is_shared_by_current_user(self): if current_user and current_user.is_authenticated(): review_shared = ReviewShare.query.filter_by( review_id=self.id, user_id=current_user.id).first() if review_shared: return True return False
def ensure_https_authenticated_users(): # Force authenticated users to use https if (not current_app.config.get('TESTING', False) and current_app.config.get('USE_SSL', False) and current_user.is_authenticated() and not request.is_secure): return redirect(request.url.replace('http://', 'https://'))
def track_pageview(path=None, ignore_bots=True): """ User Google Analytics to track this pageview. """ from pmg import app ga_id = app.config.get('GOOGLE_ANALYTICS_ID') if not ga_id: return False user_agent = request.user_agent.string if ignore_bots and BOTS_RE.search(user_agent): return False path = path or request.path user_id = current_user.id if current_user.is_authenticated() else None client_id = request.cookies.get('_ga') if client_id: # GA1.2.1760224793.1424413995 client_id = client_id.split('.', 2)[-1] tracker = Tracker.create(ga_id, user_id=user_id, client_id=client_id) tracker.send('pageview', path, uip=request.access_route[0], referrer=request.referrer or '', userAgent=user_agent) return True
def login(): if current_user.is_authenticated(): return redirect('/') return render_template('login.html', content='Login Page', form=LoginForm())
def root(): if current_user.has_role("admin"): return redirect(url_for("admin")) if current_user.is_authenticated(): return redirect(url_for("edit")) else: return redirect(url_for_security("login"))
def func(): if current_user.is_authenticated(): for role in roles: if not current_user.has_role(role): return False return True return False
def check_recaptcha(data, *args, **kwargs): if current_user.is_authenticated(): if 'g-recaptcha-response' in data: del data['g-recaptcha-response'] return # TODO: return if the user comes from a verified source if 'review_request_id' in data and 'review_request_token' in data: review_request = models.ReviewRequest.query.filter_by( id=data.get('review_request_id')).first() if review_request and review_request.token == data.get( 'review_request_token'): if 'g-recaptcha-response' in data: del data['g-recaptcha-response'] return recaptcha = data.get('g-recaptcha-response') if not recaptcha: raise ProcessingException( description=ExceptionMessages.MISSING_PARAM.format( param='g-recaptcha-response'), code=401) r = requests.post(current_app.config.get("RECAPTCHA_URL"), data={ 'secret': current_app.config.get("RECAPTCHA_SECRET"), 'response': recaptcha, 'remoteip': request.remote_addr }) if not (r and r.status_code == 200 and r.json()): raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL, code=401) if not r.json().get('success'): raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL, code=401) del data['g-recaptcha-response']
def check_if_user_exists(data, *args, **kwargs): if current_user.is_authenticated(): data["user_id"] = current_user.id return user_name = data.get('user_name') user_email = data.get('user_email') user_legacy_email = None if 'user_legacy_email' in data: user_legacy_email = data.get('user_legacy_email') del data['user_legacy_email'] if not user_name: raise ProcessingException(description=ExceptionMessages.MISSING_PARAM.format(param='user_name'), code=401) if not user_email: raise ProcessingException(description=ExceptionMessages.MISSING_PARAM.format(param='user_email'), code=401) user, is_new = models.User.get_or_create_by_email(email=user_email, role_name=Constants.REVIEWER_ROLE, user_legacy_email=user_legacy_email, name=user_name) if not is_new: # TODO maybe display a passwd field if user is not new? raise ProcessingException(description=ExceptionMessages.USER_EXISTS % user_email, code=401) db.session.add(user) db.session.commit() login_user(user) if 'user_name' in data: del data['user_name'] del data['user_email'] data['user_id'] = user.id
def check_recaptcha(data, *args, **kwargs): if current_user.is_authenticated(): if 'g-recaptcha-response' in data: del data['g-recaptcha-response'] return # TODO: return if the user comes from a verified source if 'review_request_id' in data and 'review_request_token' in data: review_request = models.ReviewRequest.query.filter_by(id=data.get('review_request_id')).first() if review_request and review_request.token == data.get('review_request_token'): if 'g-recaptcha-response' in data: del data['g-recaptcha-response'] return recaptcha = data.get('g-recaptcha-response') if not recaptcha: raise ProcessingException(description=ExceptionMessages.MISSING_PARAM.format(param='g-recaptcha-response'), code=401) r = requests.post(current_app.config.get("RECAPTCHA_URL"), data={ 'secret': current_app.config.get("RECAPTCHA_SECRET"), 'response': recaptcha, 'remoteip': request.remote_addr }) if not (r and r.status_code == 200 and r.json()): raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL, code=401) if not r.json().get('success'): raise ProcessingException(description=ExceptionMessages.CAPTCHA_FAIL, code=401) del data['g-recaptcha-response']
def user_create(): # redirect home if already authenticated if current_user.is_authenticated(): return redirect(url_for('home')) if request.method == 'GET': # return user_create.html page return render_template('user_create.min.html') if request.method == 'POST': email = request.form['email'] password = request.form['password'] # check if user exist user = users.User.query.filter_by(email=email).first() if not user is None: url = url_for("login") next = request.args.get("next") or '' if next != '': url = url + u"?next=" + next error = u"כתובת דואר אלקטרוני זו כבר בשימוש. <a href='" + url + u"'>התחבר</a>" return render_template('user_create.min.html', error=error) # create user and fetch it users.create(email, password) user = users.User.query.filter_by(email=email).first() # login and validate the user... login_user(user) return redirect(request.args.get("next") or url_for("home"))
def is_reported_by_current_user(self): if current_user and current_user.is_authenticated(): review_report = ReviewReport.query.filter_by( review_id=self.id, user_id=current_user.id).first() if review_report: return True return False
def is_accessible(self): try: role = models.Role.objects.get(name='admin') except models.Role.DoesNotExist: return False return (current_user.is_authenticated() and current_user.has_role(role))
def index_category(category, page=1): category = Category.query\ .filter_by(url=category)\ .first_or_404() categories = Category.query\ .order_by(Category.order)\ .all() roles = computed_user_roles() user_string_id = 'ANONYMOUS' if current_user.is_authenticated(): user_string_id = current_user.string_id posts_category = Post.query\ .filter_by(status='published')\ .join(Category)\ .join(PostRating)\ .filter(Category.url == category.url) \ .filter(Category.roles.any(Role.id.in_(roles))) \ .order_by(desc(PostRating.hot))\ .paginate(page, per_page=20)\ return render_template( 'posts/index.html', title='index_category', categories=categories, category_url=category.url, # used for caching index category=category, user_string_id=user_string_id, page=str(page), posts=posts_category)
class Shop(db.Model, Repopulatable): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) description = db.Column(db.String) domain = db.Column(db.String) image_url = db.Column(db.String) active = db.Column(db.Boolean, default=True) automatically_approve_reviews = db.Column(db.Boolean, default=True) access_user = db.Column(db.String) access_token = db.Column(db.String) products_imported = db.Column(db.Boolean, default=False) owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), default=current_user.id if current_user and current_user.is_authenticated() else None) owner = db.relationship("User", backref=db.backref("shops")) platform_id = db.Column(db.Integer, db.ForeignKey('platform.id')) platform = db.relationship("Platform", backref=db.backref("platform")) def __repr__(self): return '<Shop %r>' % self.name
def index_category(category, page=1): category = Category.query.filter_by(url=category).first_or_404() categories = Category.query.all() # posts = query_posts_category(category.url, page) user_string_id = "ANONYMOUS" if current_user.is_authenticated(): user_string_id = current_user.string_id posts = ( Post.query.filter_by(status="published") .join(Category) .join(PostRating) .filter(Category.url == category.url) .order_by(desc(PostRating.hot)) .paginate(page, per_page=20) ) return render_template( "posts/index.html", title="index_category", categories=categories, category_url=category.url, # used for caching index category=category, user_string_id=user_string_id, page=str(page), posts=posts, )
def check_for_admin(*args, **kw): if request.path.startswith('/admin/'): if current_user.is_authenticated(): if not current_user.is_admin(): return redirect(url_for('main.login')) else: return redirect(url_for('main.login'))
def needs_login(**kwargs): if not current_user.is_authenticated(): nex = kwargs.get( 'next', request.values.get( 'next', url_for('quokka.modules.accounts.profile_edit'))) return redirect(url_for_security('login', next=nex))
def edit_user(user_id): is_reviewer = current_user.has_role('reviewer') user = user_datastore.get_user(user_id) if (not current_user.is_authenticated()) or (user.id != current_user.id and not is_reviewer): return current_app.login_manager.unauthorized() form = forms.UserEditForm(request.form, user) form.roles.choices = [(role.name, role.name.capitalize()) for role in user_datastore.role_model.objects()] if not current_user.has_role('admin'): del form.roles if form.validate_on_submit(): user.email = form.email.data if form.password.data: user.password = form.password.data if current_user.has_role('admin'): user.roles = [ user_datastore.find_role(role) for role in form.roles.data ] user.save() flash('User updated successfully.', 'success') if current_user.has_role('admin'): form.roles.data = [role.name for role in user.roles] return render_template('edit_user.html', form=form)
def view_application(application_id, is_review=False): is_reviewer = current_user.has_role('reviewer') application = models.Application.objects.with_id(application_id) if not application: flash('No application with that id could be found.', 'error') return redirect('dashboard') if (not current_user.is_authenticated()) or (application.submitter.id != current_user.id and not is_reviewer): return current_app.login_manager.unauthorized() date = (application.submit_date if application.is_submitted else application.id.generation_time) files = [] for course_app in application.course_applications: if course_app.uploaded_content: for f in course_app.uploaded_content: files.append({'name': f.name, 'url': url_for('download_file', file=f._id)}) return render_template('view_application.html', name=application.submitter.name, date=date.strftime('%Y-%m-%d') if date else 'No date available', files=files, formatted=utils.serialize_application_to_html(application, is_review=is_review) )
def edit_user(user_id): is_reviewer = current_user.has_role('reviewer') user = user_datastore.get_user(user_id) if (not current_user.is_authenticated()) or (user.id != current_user.id and not is_reviewer): return current_app.login_manager.unauthorized() form = forms.UserEditForm(request.form, user) form.roles.choices = [(role.name, role.name.capitalize()) for role in user_datastore.role_model.objects()] if not current_user.has_role('admin'): del form.roles if form.validate_on_submit(): user.email = form.email.data if form.password.data: user.password = form.password.data if current_user.has_role('admin'): user.roles = [user_datastore.find_role(role) for role in form.roles.data] user.save() flash('User updated successfully.', 'success') if current_user.has_role('admin'): form.roles.data = [role.name for role in user.roles] return render_template('edit_user.html', form=form)
def register(login_failed=False, **kwargs): if current_user.is_authenticated(): return redirect(request.referrer or '/') form = RegisterForm() ds = get_extension('security', app=current_app).datastore if form.validate_on_submit(): user = ds.create_user( fullname=form.fullname.data, email=form.email.data, password=form.password.data) ds.commit() login_user(user) ds.commit() flash('Account created successfully', 'info') return index(show_modal='profile') if form.errors: show_modal = 'signup' else: show_modal = None return index(register_form=form, show_modal=show_modal)
def register(provider_id=None): if current_user.is_authenticated(): return redirect(request.referrer or '/') if provider_id: provider = get_provider_or_404(provider_id) connection_values = session.pop('failed_login_connection', None) else: provider = None connection_values = None app.logger.debug("Attemption to register with connection_values: %s" % repr(connection_values)) if connection_values is not None: ds = app.security.datastore fake_email = connection_values['provider_user_id'] + "*****@*****.**" user = ds.create_user(email=fake_email, password="******") ds.commit() connection_values['user_id'] = user.id connect_handler(connection_values, provider) login_user(user) ds.commit() flash('Account created successfully', 'info') return redirect(url_for('index')) return abort(404)
def user_create(): # redirect home if already authenticated if current_user.is_authenticated(): return redirect(url_for('home')) if request.method == 'GET': # return user_create.html page return render_template('user_create.min.html') if request.method == 'POST': email = request.form['email'] password = request.form['password'] # check if user exist user = users.User.query.filter_by(email=email).first() if not user is None: url = url_for("login") next = request.args.get("next") or '' if next!='': url = url + u"?next="+next error = u"כתובת דואר אלקטרוני זו כבר בשימוש. <a href='"+url+u"'>התחבר</a>" return render_template('user_create.min.html', error=error) # create user and fetch it users.create(email, password) user = users.User.query.filter_by(email=email).first() # login and validate the user... login_user(user) return redirect(request.args.get("next") or url_for("home"))
def view_application(application_id, is_review=False): is_reviewer = current_user.has_role('reviewer') application = models.Application.objects.with_id(application_id) if not application: flash('No application with that id could be found.', 'error') return redirect('dashboard') if (not current_user.is_authenticated()) or ( application.submitter.id != current_user.id and not is_reviewer): return current_app.login_manager.unauthorized() date = (application.submit_date if application.is_submitted else application.id.generation_time) files = [] for course_app in application.course_applications: if course_app.uploaded_content: for f in course_app.uploaded_content: files.append({ 'name': f.name, 'url': url_for('download_file', file=f._id) }) return render_template( 'view_application.html', name=application.submitter.name, date=date.strftime('%Y-%m-%d') if date else 'No date available', files=files, formatted=utils.serialize_application_to_html(application, is_review=is_review))
def dashboard(): """ """ if not current_user.is_authenticated(): return render_template('public.html', logged_in=False) else: return render_template('public.html', logged_in=True)
def user_rating(self): if current_user.is_authenticated(): return UserPostRating.query\ .filter_by(post_id=self.id, user_id=current_user.id)\ .first() else: return False
def index(): if current_user.is_authenticated(): logged_in = True return redirect(url_for('dashboard')) else: logged_in = False return render_template('public.html', logged_in=logged_in)
def get_megamenu(): user_following = None recent_meetings = None user_follows_committees = False if current_user.is_authenticated(): user_following = sorted(current_user.following, key=lambda cte: cte.name)[:20] if user_following: user_follows_committees = True recent_meetings = current_user.get_followed_committee_meetings( ).limit(10) if not user_following: user_following = Committee.query.filter( Committee.id.in_(Committee.POPULAR_COMMITTEES)).all() if not recent_meetings: recent_meetings = CommitteeMeeting.query\ .filter(CommitteeMeeting.committee_id.in_(Committee.POPULAR_COMMITTEES))\ .order_by(desc(CommitteeMeeting.date))\ .limit(10) return { 'user_follows_committees': user_follows_committees, 'user_following': user_following, 'recent_meetings': recent_meetings, }
def view(category, uuid, slug=None): post_id = decode_id(uuid) post = Post.query.get_or_404(post_id) categories = Category.query.all() user_string_id = 'ANONYMOUS' if current_user.is_authenticated(): user_string_id = current_user.string_id # Aggressive redirect if the URL does not have a slug if not slug: return redirect(url_for('posts.view', category=category, uuid=uuid, slug=post.slug)) #post.comments.sort(key=lambda comment: comment.confidence, reverse=True) oembed = None # If the content is a link, we try to pass it through micawber to do # some nice embedding if post.post_type_id == 1: try: oembed = registry.request(post.content) # Keep in mind that oembed can be of different types: # - photo # - video # - link # - etc except (ProviderNotFoundException, ProviderException): # If the link is not an OEmbed provider, we move on pass else: # For any other error (e.g. video was unpublished) we also pass pass form = CommentForm() if current_user.is_anonymous(): current_user.is_owner = False elif current_user.is_authenticated() and post.user.id == current_user.id: current_user.is_owner = True return render_template('posts/view.html', title='view', post=post, oembed=oembed, form=form, categories=categories, user_string_id=user_string_id, picture=post.thumbnail('m'))
def view(category, uuid, slug=None): post_id = decode_id(uuid) post = Post.query.get_or_404(post_id) post.check_permissions() categories = Category.query.all() user_string_id = 'ANONYMOUS' if current_user.is_authenticated(): user_string_id = current_user.string_id # Aggressive redirect if the URL does not have a slug if not slug: return redirect( url_for('posts.view', category=category, uuid=uuid, slug=post.slug)) oembed = None # If the content is a link, we try to pass it through micawber to do # some nice embedding if post.post_type_id == 1: try: oembed = registry.request(post.content) # Keep in mind that oembed can be of different types: # - photo # - video # - link # - etc except (ProviderNotFoundException, ProviderException): # If the link is not an OEmbed provider, we move on pass else: # For any other error (e.g. video was unpublished) we also pass pass form = CommentForm() if current_user.is_anonymous(): current_user.is_owner = False elif current_user.is_authenticated() and post.user.id == current_user.id: current_user.is_owner = True return render_template('posts/view.html', title='view', post=post, oembed=oembed, form=form, categories=categories, user_string_id=user_string_id, picture=post.thumbnail('m'))
def get(self, **kwargs): users = User.query.all() for user in users: print user.as_dict() return make_response(json.dumps(user.as_dict())) if not current_user.is_authenticated(): return jsonify(message='Unauthorized', status_code=200)
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.has_role(Constants.ADMIN_ROLE): return True return False
def user_remove_committee_alert(committee_id): if current_user.is_authenticated() and request.method == 'POST': current_user.committee_alerts.remove(Committee.query.get(committee_id)) db.session.commit() ga_event('user', 'remove-alert', 'cte-alert-box') flash("We won't send you email alerts for this committee.", 'warning') return redirect(request.headers.get('referer', '/'))
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.has_role('superuser'): return True return False
def get(self, **kwargs): if not current_user.is_authenticated(): return jsonify(message='Unauthorized', status_code=400) args = parser.parse_args() print current_user username = current_user.email hypotheses = HypothesisDAO(username).get_user_hypotheses() return jsonify(status=200, hypotheses = hypotheses,onboarded=current_user.onboarded)
def before_first(): """ Create a permanent session Track new login for authenticated users """ session.permanent = True if current_user.is_authenticated(): current_user.current_login_at = datetime.utcnow() db.session.commit()
def logout(): """View function which handles a logout request.""" if current_user.is_authenticated(): logout_user() return redirect(request.args.get('next', None) or url_for('user.index'))
def user_committee_alert(committee_id): if current_user.is_authenticated() and request.method == 'POST': current_user.committee_alerts.append(Committee.query.get(committee_id)) db.session.commit() ga_event('user', 'add-alert', 'cte-alert-box') flash("We'll send you email alerts for updates on this committee.", 'success') return redirect(request.values.get('next', '/'))
def make_redis_cache_key(cache_prefix, category=''): user_id = 'ANONYMOUS' if current_user.is_authenticated(): user_id = current_user.string_id cache_key = make_template_fragment_key(cache_prefix, vary_on=[user_id, category]) # Add prefix to the cache key and a * return '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if current_user.has_role('admin'): return True return False
def is_accessible(self): try: role = models.Role.objects.get(name='admin') except models.Role.DoesNotExist: return False return ( current_user.is_authenticated() and current_user.has_role(role) )
def lookup_current_user(): if not current_user.is_authenticated() and 'openid' in session: try: user = current_app.security.auth_provider.authenticate_openid(session['openid']) if user: _do_login(user) except BadCredentialsError: pass