def email_alerts(): """ Allow a user to manage their notification alerts. """ next_url = request.values.get('next', '') if current_user.is_authenticated() and request.method == 'POST': ids = request.form.getlist('committees') current_user.committee_alerts = Committee.query.filter(Committee.id.in_(ids)).all() current_user.subscribe_daily_schedule = bool(request.form.get('subscribe_daily_schedule')) db.session.commit() # register a google analytics event ga_event('user', 'change-alerts') if next_url: return redirect(next_url) return '' committees = load_from_api( 'v2/committees', return_everything=True, params={'monitored': True})['results'] if current_user.is_authenticated(): subscriptions = set(c.id for c in current_user.committee_alerts) else: subscriptions = set() provincial_committees = OrderedDict() for committee in committees: house = committee['house'] house_name = house['name'] if house['sphere'] == 'provincial': if house_name not in provincial_committees: provincial_committees[house_name] = [] provincial_committees[house_name].append(committee) saved_searches = defaultdict(list) if current_user.is_authenticated(): for ss in current_user.saved_searches: saved_searches[ss.search].append(ss) return render_template( 'user_management/email_alerts.html', committees=committees, after_signup=bool(next_url), subscriptions=subscriptions, next_url=next_url, saved_searches=saved_searches, provincial_committees=provincial_committees )
def email_alerts(): """ Allow a user to manage their notification alerts. """ next_url = request.values.get('next', '') if current_user.is_authenticated() and request.method == 'POST': ids = request.form.getlist('committees') current_user.committee_alerts = Committee.query.filter( Committee.id.in_(ids)).all() current_user.subscribe_daily_schedule = bool( request.form.get('subscribe_daily_schedule')) db.session.commit() # register a google analytics event ga_event('user', 'change-alerts') if next_url: return redirect(next_url) return '' committees = load_from_api('v2/committees', return_everything=True, params={'monitored': True})['results'] if current_user.is_authenticated(): subscriptions = set(c.id for c in current_user.committee_alerts) else: subscriptions = set() provincial_committees = OrderedDict() for committee in committees: house = committee['house'] house_name = house['name'] if house['sphere'] == 'provincial': if house_name not in provincial_committees: provincial_committees[house_name] = [] provincial_committees[house_name].append(committee) saved_searches = defaultdict(list) if current_user.is_authenticated(): for ss in current_user.saved_searches: saved_searches[ss.search].append(ss) return render_template('user_management/email_alerts.html', committees=committees, after_signup=bool(next_url), subscriptions=subscriptions, next_url=next_url, saved_searches=saved_searches, provincial_committees=provincial_committees)
def authenticated_query(query, **kwargs): """Enhance query with user authentication rules.""" from invenio_query_parser.ast import AndOp, DoubleQuotedValue, Keyword, KeywordOp if not current_user.is_authenticated(): query.body["_source"] = {"exclude": ["public"]} query.query = AndOp(KeywordOp(Keyword("public"), DoubleQuotedValue(1)), query.query)
def get_megamenu(): user_following = None recent_meetings = None user_follows_committees = False if current_user and 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 index(): if current_user.is_authenticated(): form = NewEntryForm() user_entries = current_user.entries return render_template("index.html", entries=user_entries, new_entry_form=form) else: return render_template("welcome.html")
def login_view(self): if request.method=='GET' and current_user.is_authenticated(): return redirect(url_for('.index')) # handle user login form = LoginForm(request.form) if helpers.validate_form_on_submit(form): user = authenticate(username=form.email.data, password=form.password.data) if user: if user.has_role('admin'): if login_user(user): user.save() #This is to make sure the track changes occur return redirect(url_for('.index')) else: self._template_args['error'] = "User is not active or could not be logged in." else: self._template_args['error'] = "User has insufficient privilege." else: self._template_args['error'] = "Invalid user and/or password" self._template_args['form'] = form return self.render('admin/login.html')
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 before_request(): if current_user.is_authenticated(): g.new = Messages.query.filter(Messages.recipient_id == current_user.id, Messages.user_for_id == current_user.id, Messages.unread == True).count() else: g.new = None
def get_megamenu(): user_following = None recent_meetings = None user_follows_committees = False if current_user and 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 is_authenticated(self): """ Check user is authenticated. :return: """ return current_user.is_authenticated()
def check_permission(self): # by default, all committee meetings are accessible if self.committee and self.committee.premium: if not current_user.is_authenticated(): return False return current_user.subscribed_to_committee(self.committee) return True
def send_mail_from_translator(): data = request.get_json() if current_user.is_authenticated( ) and not current_user.has_role('blocked'): translator = Translator.query.filter( Translator.slug == data['translator']).first() data['translator'] = translator.first_name + " " + translator.last_name data['user'] = current_user.email data['date'] = datetime.datetime.now() mail_template = render_template('service-mail.jinja', **data) msg = Message('new service', sender="*****@*****.**", recipients=["*****@*****.**"]) msg.body = mail_template mail.send(msg) return jsonify( **{ 'status': 'ok', 'notification': render_template( '_notification.html', text= "We have recived your service offer. We will contact you soon." ) }) else: if not current_user.is_authenticated(): return jsonify( **{ 'status': 'fail', 'notification': render_template('_notification.html', text="Sorry, you are not authenticated!") }) elif current_user.has_role('blocked'): return jsonify( **{ 'status': 'fail', 'notification': render_template('_notification.html', text="Sorry, you are in the blacklist!") })
def user_add_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.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 authenticated_query(query, **kwargs): """Enhance query with user authentication rules.""" from invenio_query_parser.ast import AndOp, DoubleQuotedValue, Keyword, \ KeywordOp if not current_user.is_authenticated(): query.body['_source'] = {'exclude': ['public']} query.query = AndOp(KeywordOp(Keyword('public'), DoubleQuotedValue(1)), query.query)
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 index(self): # Logged in as a superuser? if is_superuser(): return super(ProtectedAdminIndexView, self).index() # Logged in but not a superuser? if current_user.is_authenticated(): abort(403) # User is not logged in. return redirect(url_for("security.login", next=request.path))
def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): if current_user.is_authenticated(): abort(403) else: return redirect(url_for("security.login", next=request.path))
def oauth_authorized(name): """ Callback for oauth authorizations. Handles adding the token to the logged in user, errors, as well as redirecting back to the original page """ try: oauth_app = get_oauth_app(name) configured, register, login = check_oauth_enabled(name) if not configured: raise OAuthRegError("%s auth not enabled" % name.title()) resp = oauth_app.authorized_response() if isinstance(resp, Exception): try: logging.error('OAuth exception data: %s', resp.data) except AttributeError: pass raise resp if resp is None or 'error' in resp: flash("{name}: {message}".format( name=name.title(), message=request.args['error_description'], ), 'danger') return oauth_redir() if current_user.is_authenticated(): oauth_token = associate_oauth_current_user(name, resp) user = current_user user_id = current_user.id elif not (register or login): raise OAuthRegError( "Registration and login disabled for %s" % name.title()) else: user, oauth_token = user_from_oauth(name, resp) user_id = user.id if user.id is None and not register: raise OAuthRegError( "Registration disabled for %s" % name.title()) elif user.id is not None and not login: raise OAuthRegError( "Login disabled for %s" % name.title()) associate_user(name, user, oauth_token) return oauth_redir(user_id=user_id) except OAuthRegError as ex: flash(ex.reason, 'danger') return oauth_redir()
def is_user_authenticated(): """ Wrapper for user.is_authenticated :return: """ try: result = current_user.is_authenticated() except: result = current_user.is_authenticated return result
def get_validate_job(project_slug, job_slug): """ Get the job object, validate that project slug matches expected """ job_id = Job.id_from_slug(job_slug) job = Job.query.get_or_404(job_id) if job.project.slug != project_slug: flask_restful.abort(404) if not (job.project.public or current_user.is_authenticated()): flask_restful.abort(404) return job
def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): if current_user.is_authenticated(): # permission denied abort(403) else: # login return redirect(url_for('security.login', next=request.url))
def job_view(project_slug, job_slug): """ View to display a job """ project = Project.query.filter_by(slug=project_slug).first_or_404() if not (project.public or current_user.is_authenticated()): abort(404) job = Job.query.get_or_404(Job.id_from_slug(job_slug)) return render_template('job.html', job=job)
def is_accessible(self): if not self.require_authentication: return True if not current_user.is_active() or not current_user.is_authenticated(): return False if all(current_user.has_role(r) for r in self.required_roles): return True return False
def get(self, project_slug): """ List all jobs for a project """ project = Project.query.filter_by(slug=project_slug).first_or_404() if not (project.public or current_user.is_authenticated()): flask_restful.abort(404) base_query = filter_jobs_by_request(project) return { 'items': base_query.paginate().items, 'meta': {'total': base_query.count()}, }
def send_mail_from_service(): data = request.get_json() if current_user.is_authenticated() and not current_user.has_role('blocked'): service=Service.query.filter(Service.slug==data['service']).first() data['service'] = service.name data['user'] = current_user.email data['date'] = datetime.datetime.now() mail_template = render_template('service-mail.jinja', **data) msg = Message('new service', sender="*****@*****.**", recipients=["*****@*****.**"]) msg.body = mail_template mail.send(msg) return jsonify(**{'status':'ok', 'notification': render_template('_notification.html', text="We have recived your service offer. We will contact you soon.")}) else: if not current_user.is_authenticated(): return jsonify(**{'status':'fail', 'notification': render_template('_notification.html', text="Sorry, you are not authenticated!")}) elif current_user.has_role('blocked'): return jsonify(**{'status':'fail', 'notification': render_template('_notification.html', text="Sorry, you are in the blacklist!")})
def company_delete(company_id): if not current_user.is_authenticated(): return abort(403) try: company.delete(current_user, company_id) except (ObjectNotFoundError, UnauthorizedObjectAccessError): # In either instance, return a not found response return abort(404) # TODO :: This response needs to make sense. return json_response([0], 204)
def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible :param name: :param kwargs: :return: """ if not self.is_accessible(): if _current_user.is_authenticated(): abort(403) else: return redirect(url_for('security.login', next=request.url))
def before_request(self, name, *args , **kwargs): if current_user.is_authenticated(): g.settings = Settings.objects(user_ref=current_user.id).first() if g.settings and 'tz' in g.settings: g.today = datetime.now(pytz.timezone(g.settings['tz'])).date() else: g.today = datetime.now(pytz.utc).date() g.reached_goal = False g.last_item = Item.objects(user_ref=current_user.id).first() if g.last_item and g.last_item.is_today and g.last_item.reached_goal: g.reached_goal = True else: return redirect(url_for('frontend.index'))
def before_request(self, name, *args, **kwargs): if current_user.is_authenticated(): g.settings = Settings.objects(user_ref=current_user.id).first() if g.settings and 'tz' in g.settings: g.today = datetime.now(pytz.timezone(g.settings['tz'])).date() else: g.today = datetime.now(pytz.utc).date() g.reached_goal = False g.last_item = Item.objects(user_ref=current_user.id).first() if g.last_item and g.last_item.is_today and g.last_item.reached_goal: g.reached_goal = True else: return redirect(url_for('frontend.index'))
def inject_user_tags(): if not current_user.is_authenticated(): return {"user_tags": None} else: user_tags = Tag.query.filter(Tag.user == current_user.id, Tag.count > 0).all() user_tags.sort(key=lambda k: k.text.lower()) user_tags = [{ 'text': tag.text.encode('utf-8'), 'value': tag.text.encode('utf-8'), 'count': tag.count } for tag in user_tags if tag.text != ''] return {"user_tags": user_tags}
def user_unfollow_committee(committee_id): if current_user.is_authenticated() and request.method == 'POST': committee = Committee.query.get(committee_id) if committee in current_user.following: current_user.unfollow_committee(committee) if committee in current_user.committee_alerts: current_user.committee_alerts.remove(committee) db.session.commit() ga_event('user', 'unfollow-committee', 'cte-follow-committee') return redirect(request.headers.get('referer', '/'))
def get_token_for(oauth_app): """ Get a token for the currently logged in user """ if current_user.is_authenticated(): token = current_user.oauth_tokens.filter_by( service=oauth_app.name, ).first() if token: from dockci.server import OAUTH_APPS_SCOPES if token.scope == OAUTH_APPS_SCOPES[oauth_app.name]: return (token.key, token.secret) return None
def inject_user_tags(): if not current_user.is_authenticated(): return { "user_tags": None } else: user_tags = Tag.query.filter(Tag.user == current_user.id, Tag.count > 0).all() user_tags.sort(key=lambda k: k.text.lower()) user_tags = [{'text': tag.text.encode('utf-8'), 'value': tag.text.encode('utf-8'), 'count': tag.count} for tag in user_tags if tag.text != ''] return { "user_tags": user_tags }
def register_event(): if (request.method == 'POST') and current_user.is_authenticated(): event = request.form['event'] events = get_all_events() if contains(events, lambda x: x.view_name == event): bogie = add_event_to_user(current_user.email,event) if bogie==True: flash("You are successfully registered for this event") return redirect("/event/%s"%(event)) else: return redirect("/events") else: return redirect("/events") else: return redirect('/login') return render_template('test.html')
def event(event_name): # check if user is registered with that have = False events = get_all_events() check = contains(events, lambda x: x.view_name == event_name) if check is not None: if current_user.is_authenticated(): check2 = contains(current_user.events, lambda x: x.view_name == event_name) if check2 is not None: return render_template('events/%s.html'%(event_name),regiterz=3,event_name=event_name) else: return render_template('events/%s.html'%(event_name),regiterz=1,event_name=event_name) else: return render_template('events/%s.html'%(event_name),regiterz=2,event_name=event_name) else: return redirect("/events")
def get(self, project_slug): """ List of all branches in a project """ project = Project.query.filter_by(slug=project_slug).first_or_404() if not (project.public or current_user.is_authenticated()): flask_restful.abort(404) return [ dict(name=job.git_branch) for job in ( project.jobs.distinct(Job.git_branch) .order_by(sqlalchemy.asc(Job.git_branch)) ) if job.git_branch is not None ]
def home(): form = LoginForm(request.form) if current_user.is_authenticated(): AuthInfoManager.get_or_create(current_user) # Handle logging in # if request.method == 'POST': # if form.validate_on_submit(): # login_user(form.user) # flash("You are logged in.", 'success') # redirect_url = request.args.get("next") or url_for("user.members") # return redirect(redirect_url) # else: # flash_errors(form) return render_template("public/home.html", login_user_form=form)
def get(self, project_slug): """ List all distinct job commits for a project """ project = Project.query.filter_by(slug=project_slug).first_or_404() if not (project.public or current_user.is_authenticated()): flask_restful.abort(404) base_query = filter_jobs_by_request(project).filter( Job.commit.op('SIMILAR TO')(r'[0-9a-fA-F]+') ) commit_query = base_query.from_self(Job.commit).distinct(Job.commit) return { 'items': [ res_arr[0] for res_arr in commit_query.paginate().items ], 'meta': {'total': commit_query.count()}, }
def load_user(): login_mechanisms = { 'token': lambda: _check_token(), 'basic': lambda: _check_http_auth(), 'session': lambda: current_user.is_authenticated() } def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): for mechanism in login_mechanisms.itervalues(): if mechanism(): break return fn(*args, **kwargs) return decorated_view return wrapper
def check_output(project_slug, job_slug, filename): """ Ensure the job exists, and that the path is not dangerous """ project = Project.query.filter_by(slug=project_slug).first_or_404() if not (project.public or current_user.is_authenticated()): abort(404) job = Job.query.get_or_404(Job.id_from_slug(job_slug)) job_output_path = job.job_output_path() data_file_path = job_output_path.join(filename) # Ensure no security issues opening path above our output dir if not path_contained(job_output_path, data_file_path): abort(404) if not data_file_path.check(file=True): abort(404) return data_file_path
def login(): """User login route.""" if current_user.is_authenticated(): # if user is logged in we get out of here return redirect(url_for('index')) form = LoginForm2() if form.validate_on_submit(): user = Usuario.query.filter_by(username=form.email.data).first() if user is None or not user.verify_password(form.password.data) or \ not user.verify_totp(form.token.data): flash('Invalid username, password or token.') return redirect(url_for('login')) # log user in login_user(user) flash('You are now logged in!') return redirect(url_for('index')) print form print "Form" return render_template('login_user.html', form2=form)
def register(provider_id=None): if current_user.is_authenticated(): return redirect(request.referrer or '/') form = RegisterForm() if provider_id: provider = get_provider_or_404(provider_id) connection_values = session.get('failed_login_connection', None) else: provider = None connection_values = None if form.validate_on_submit(): ds = current_app.extensions['security'].datastore user = ds.create_user(email=form.email.data, password=form.password.data) ds.commit() # See if there was an attempted social login prior to registering # and if so use the provider connect_handler to save a connection connection_values = session.pop('failed_login_connection', None) if connection_values: connection_values['user_id'] = user.id connect_handler(connection_values, provider) if login_user(user): ds.commit() flash('Account created successfully', 'info') return redirect(url_for('website.index')) return render_template('thanks.html', user=user) login_failed = int(request.args.get('login_failed', 0)) return render_template('register.html', form=form, provider=provider, login_failed=login_failed, connection_values=connection_values)
def is_own(self): if current_user.is_authenticated(): return self.user == current_user._get_current_object() return False #updated_at = db.Column(db.DateTime, onupdate=datetime.datetime.now)
def _handle_view(self, *args, **kwargs): if not current_user.is_authenticated(): return redirect(url_for_security('login', next="/admin")) if not self.is_accessible(): return self.render("admin/denied.html")
def decorated_function(*args, **kwargs): if not current_user.is_authenticated(): return {}, 401 return f(*args, **kwargs)
def user_follow_committee(committee_id): if current_user.is_authenticated() and request.method == 'POST': follow_committee(committee_id) return redirect(request.headers.get('referer', '/'))
def load_from_api(resource_name, resource_id=None, page=None, return_everything=False, fields=None, params=None, pagesize=None): """ Load data from the PMG API. :param str resource_name: resource to load (used as the start of the URL), or a full URL :param int resource_id: resource id (optional), appended to the resource name :param int page: page number to load (default is the first page) :param bool return_everything: fetch all pages? (default: False) :param list fields: list of field names to ask for (V2 only). :param dict params: additional query params :param int pagesize: items per page """ params = {} if (params is None) else params # check for full URL? if resource_name.startswith('http'): resource_name = resource_name.split('/', 3)[3] v2 = resource_name.startswith('v2') if fields and not v2: raise ValueError("Fields parameter is only supported for API v2 urls.") query_str = resource_name if resource_id: query_str += "/" + str(resource_id) if not v2: query_str += '/' if page: params["page"] = str(page) if fields: params["fields"] = ','.join(fields) if pagesize: params["per_page"] = pagesize headers = {} # add auth header if current_user.is_authenticated(): headers = {'Authentication-Token': current_user.get_auth_token()} try: response = http.request('GET', API_URL + query_str, headers=headers, fields=params) if response.status == 404: abort(404) if response.status != 200 and response.status not in [401, 403]: try: msg = response_json(response).get('message') except Exception: msg = None raise ApiException(response.status, msg or "An unspecified error has occurred.") out = response_json(response) if return_everything: next_response_json = out i = 0 while next_response_json.get('next') and i < 1000: next_response = http.request('GET', next_response_json.get('next'), headers=headers) next_response_json = response_json(next_response) out['results'] += next_response_json['results'] i += 1 if out.get('next'): out.pop('next') return out except urllib3.exceptions.HTTPError as e: logger.error("Error connecting to backend service: %s" % e, exc_info=e) flash(u'Error connecting to backend service.', 'danger') raise e
def inject_bmark_count(): if current_user.is_authenticated(): bookmark_count = Bookmark.query.filter_by(user=current_user.id, deleted=False).count() return dict(bookmark_count=bookmark_count) return dict(bookmark_count=0)
def is_accessible(self): if _current_user.is_active() and \ _current_user.is_authenticated() and \ _current_user.has_role('superuser'): return True
def user_megamenu(): if current_user.is_authenticated(): return render_template('_megamenu.html', **get_megamenu()) else: abort(404)