def get_needs(): return flask.jsonify( everybody=Permission(auth.need.everybody).can(), authenticated=Permission(auth.need.authenticated).can(), admin=Permission(auth.need.admin).can(), user_id_foo=Permission(auth.need.user_id('foo')).can(), user_id_bar=Permission(auth.need.user_id('bar')).can())
def blogger_permission(self): if self._blogger_permission is None: if self.config.get("BLOGGING_PERMISSIONS", False): self._blogger_permission = Permission(RoleNeed("blogger")) else: self._blogger_permission = Permission() return self._blogger_permission
def index(parent_table, parent_id): replies = ( models.CommentReply.query .filter_by(parent_table=parent_table) .filter_by(parent_id=parent_id) .all() ) user_id = flask.g.identity.id if user_id is not None: fields = { 'user_id': user_id, 'table': parent_table, 'row_id': parent_id, } if models.CommentReplyRead.query.filter_by(**fields).count() < 1: models.db.session.add(models.CommentReplyRead(**fields)) models.db.session.commit() return flask.render_template('replies/index.html', **{ 'parent_id': parent_id, 'parent_table': parent_table, 'replies': replies, 'can_post_new_reply': Permission(need.authenticated).can(), 'can_delete_reply': Permission(need.admin).can() })
def perm_redraft_comment(comment): if comment.cons_role == DRAFT_COMMENT_ROLE: return Permission(need.impossible) if comment.cons_status in EDITABLE_STATUS_LIST: return Permission(need.admin, need.user_id(comment.cons_user_id)) return Permission(need.admin)
def perm_submit_for_evaluation(comment): if comment.cons_role != DRAFT_COMMENT_ROLE: return Permission(need.impossible) if comment.cons_user_id: return Permission(need.admin, need.user_id(comment.cons_user_id)) else: return Permission(need.admin)
def view(self): if self.access == Post.PUBLIC: return Permission() if self.access == Post.FRIENDS: needs = [UserNeed(user_id) for user_id in \ self.author.friends] return self.default & Permission(*needs) return self.default
def perm_delete_comment(comment): if comment.cons_status not in EDITABLE_STATUS_LIST: return Permission(need.impossible) if comment.cons_status == APPROVED_STATUS: return Denial(need.everybody) elif comment.cons_user_id: return Permission(need.admin, need.user_id(comment.cons_user_id)) else: return Permission(need.admin)
def index(): perm1 = Permission(Need('need1', 'my_value')) perm2 = Permission(Need('need2', 'my_value')) perm3 = Permission(Need('need3', 'my_value')) return render_template('index.html', # rate_graph_dianshang_list=rate_graph_dianshang_list, # rate_graph_work_list = rate_graph_work_list, # rate_graph_others_list = rate_graph_others_list, permission1=perm1.can(), permission2=perm2.can(), permission3=perm3.can(), user=session['username'] )
def perm_edit_comment(comment): if comment.cons_status not in EDITABLE_STATUS_LIST: return Permission(need.impossible) if comment.cons_role not in EDITABLE_COMMENT_ROLES: return Permission(need.admin, *get_roles_for_subject('reviewer', comment.subject)) if comment.cons_user_id: return Permission(need.admin, need.user_id(comment.cons_user_id)) else: return Permission(need.admin)
def housing_price(): ''' controller layer for housing_price :return: ''' # 与界面交互 now = datetime.datetime.utcnow() - datetime.timedelta(days=1) last_day = now - datetime.timedelta(days=80) now_str = str(now)[:10] last_day_str = str(last_day)[:10] date_begin = request.args.get('begin', last_day_str, type=str) date_end = request.args.get('end', now_str, type=str) smooth_days = request.args.get('day', 0, type=int) # get city name city_name = request.args.get('city', 'Beijing', type=str) # get housing_price_list housing_price_model = HousingPriceModel() housing_price_list = housing_price_model.get_housing_price_list( date_end, date_begin, smooth_days, city_name) print housing_price_list # list to json housing_price_list_json = json.dumps(housing_price_list, encoding='utf-8') # permission perm1 = Permission(Need('need1', 'my_value')) perm2 = Permission(Need('need2', 'my_value')) perm3 = Permission(Need('need3', 'my_value')) if perm2.can(): return render_template( 'housing_price/housing_price.html', title=("{0} HousingPrice ".format(city_name)).decode('utf8'), smooth=u'smooth days', city_name=city_name, module_list=housing_price_list_json, smooth_num_list=smooth_num_list, user=session['username'], permission1=perm1.can(), permission2=perm2.can(), permission3=perm3.can(), date_begin=date_begin, date_end=date_end) return redirect(url_for('housing_price', _external=True, _scheme='http'))
class ReferenceValuesUpdate(TemplateView): template_name = 'aggregation/admin/refvals_update.html' decorators = [require(Permission(need.admin))] def get_context(self, **kwargs): subject = kwargs.pop('subject') form = RefValuesForm(request.files) return dict( form=form, subject=subject, page='refvalues', ) def post(self, **kwargs): context = self.get_context(**kwargs) form = context['form'] subject = context['subject'] if form.validate(): required_struct = get_struct(get_refvals(context['subject'])) wb = load_workbook(form.excel_doc.data) struct = {sheet: [r.value for r in wb[sheet].rows[0] if r.value] for sheet in wb.get_sheet_names()} if required_struct == struct: d = process_xls(wb, struct) if subject == 'species': save_species_refval(d) elif subject == 'habitat': save_habitat_refval(d) else: raise NotImplementedError flash(u'Noile valori de referință au fost salvate.', 'success') else: flash(u'Documentul Excel nu este în formatul acceptat.', 'danger') return render_template(self.template_name, **context)
def profile_update(user_id): ucontr = None if admin_permission.can(): ucontr = UserController() elif Permission(UserNeed(user_id)).can(): ucontr = UserController(user_id) else: flash(gettext('You do not have rights on this user'), 'danger') raise Forbidden(gettext('You do not have rights on this user')) user = ucontr.get(id=user_id) profile_form, pass_form = ProfileForm(obj=user), PasswordModForm() if profile_form.validate(): values = { 'login': profile_form.login.data, 'email': profile_form.email.data } if admin_permission.can(): values['is_active'] = profile_form.is_active.data values['is_admin'] = profile_form.is_admin.data values['is_api'] = profile_form.is_api.data ucontr.update({'id': user_id}, values) flash(gettext('User %(login)s successfully updated', login=user.login), 'success') return redirect(url_for('user.profile', user_id=user.id)) return render_template('profile.html', user=user, admin_permission=admin_permission, form=profile_form, pass_form=pass_form)
def edit_post(id): post = Post.query.get_or_404(id) permission = Permission(UserNeed(post.user.id)) print permission.can() # We want admins to be able to edit any post if permission.can() or admin_permission.can(): form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.text = form.text.data post.publish_date = datetime.datetime.now() db.session.add(post) db.session.commit() return redirect(url_for('.post', post_id=post.id)) form.text.data = post.text return render_template('edit.html', form=form, post=post) abort(403)
def perm_edit_record(record): if record.is_agg_final(): return Denial(need.everybody) return Permission( need.admin, *get_roles_for_subject('reporter', record.subject) + get_roles_for_subject('reviewer', record.subject))
def us_airline_delay_prediction(): ''' choose :return: ''' # permission management # 权限管理 perm1 = Permission(Need('need1', 'my_value')) perm2 = Permission(Need('need2', 'my_value')) return render_template( 'us_airline_delay_prediction/data_analysis.html', permission1=perm1.can(), permission2=perm2.can(), user=session['username'], )
def send_message(self): if not self.receive_email: return null needs = [UserNeed(username) for username in self.friends] if not needs: return null return Permission(*needs)
def first_tier_city_list(): ''' choose housing price city :return: ''' # 权限管理 city_list = {x for x in LIANJIA_MAP} city_dict = {} for pos, x in enumerate(city_list): city_dict[pos + 1] = x perm1 = Permission(Need('need1', 'my_value')) perm2 = Permission(Need('need2', 'my_value')) return render_template('housing_price/city_dict.html', title='Choose City', permission1=perm1.can(), permission2=perm2.can(), user=session['username'], city_dict=city_dict)
def find(self, **kwargs): _kwargs = self._set_default_filter_parameters({}) if current_user.is_authenticated(): kwargs['pk__in'] = [ event.pk for event in filter( lambda f: Permission(ItemNeed('access_event', f, 'object'), RoleNeed('admin')).can(), self.__model__.objects.filter(**_kwargs)) ] return super(EventsService, self).find(**kwargs)
def decorated_view(*args, **kwargs): if not current_user.is_authenticated(): return current_app.login_manager.unauthorized() if not current_user.active_member: flash('You need to be aproved as a member to access this resource', 'error') abort(403) for role in roles: if not Permission(RoleNeed(role)).can(): flash('You need the permission \'' + str(role) + '\' to access this resource.', 'error') abort(403) return fn(*args, **kwargs)
def minneapolis_simple_analysis(): ''' choose housing price city :return: ''' # permission manage perm1 = Permission(Need('need1', 'my_value')) perm2 = Permission(Need('need2', 'my_value')) # get the parameter from the form lat = request.args.get('lati', 44.977276, type=float) lon = request.args.get('long', -93.232266, type=float) date = request.args.get('date', '', type=str) time = request.args.get('time', "12:00", type=str) global crime_model top_2_result = crime_model.predict_from_rf(lat, lon, date, time, 2) maker_box = "Latitude:{0}<br>Longtitude:{1}<br>Time:{2}<br>Predictions: <ol>{3} for {4}</ol><ol>{5} for {6}</ol>".format( lat, lon, time, top_2_result[0][0], top_2_result[0][1], top_2_result[1][0], top_2_result[1][1]) sndmap = Map( identifier="sndmap", varname="sndmap", zoom=11, lat=44.977276, lng=-93.232266, style="height:600px;width:1200px;margin:0;", markers={ # icons.dots.green: [(37.4419, -122.1419), (37.4500, -122.1350)], icons.dots.blue: [(lat, lon, maker_box)] }) return render_template( 'minneapolis_crime_prediction/data_analysis_crimes.html', permission1=perm1.can(), permission2=perm2.can(), user=session['username'], sndmap=sndmap, )
class test_user(TestCase): def test_add_user(self): user = User(username=u"tester", email="*****@*****.**", password="******") db.session.add(user) db.session.commit() assert user in db.session def test_authenticate_user1(self): user = User(username=u"tester", email="*****@*****.**", password="******") db.session.add(user) db.session.commit() assert User.query.authenticate("tester", "test") == (user, True) def test_authenticate_user2(self): user = User(username=u"tester", email="*****@*****.**", password="******") db.session.add(user) db.session.commit() assert User.query.authenticate("*****@*****.**", "test") == (user, True) def test_authenticate_user3(self): user = User(username=u"tester", email="*****@*****.**", password="******") db.session.add(user) db.session.commit() assert User.query.authenticate("*****@*****.**", "tes11t") == (user, True) def test_authenticate_user4(self): user = User(username=u"tester", email="*****@*****.**", password="******") db.session.add(user) db.session.commit() assert User.query.authenticate("*****@*****.**", "test") == (user, True) def test_for_case(self): case = Case(author_id=1, case_type=2) db.session.add(case) db.session.commit() assert case.access == 100 assert case.permissions.view == Permission()
def get_checklist_form_dashboard_menu(**kwargs): """Retrieves a list of forms that have the verification flag set :param form_type: The form type for the forms to be retrieved """ return [{ u'url': url_for(u'dashboard.checklists', form_id=str(form.id)), u'text': form.name, u'icon': u'<i class="glyphicon glyphicon-check"></i>', u'visible': True } for form in filter( lambda f: Permission(ItemNeed(u'view_forms', f, u'object'), RoleNeed(u'admin')).can(), services.forms.find(**kwargs).order_by(u'name'))]
def delete(user_id): ucontr = None if admin_permission.can(): ucontr = UserController() elif Permission(UserNeed(user_id)).can(): ucontr = UserController(user_id) logout_user() else: flash(gettext('You do not have rights on this user'), 'danger') raise Forbidden(gettext('You do not have rights on this user')) ucontr.delete(user_id) flash(gettext('Deletion successful'), 'success') if admin_permission.can(): return redirect(url_for('admin.dashboard')) return redirect(url_for('login'))
def get_form_list_menu(**kwargs): """Retrieves a list of forms that the user has access to and returns it in a format that can be rendered on the menu :param form_type: The form type for the forms to be retrieved TODO: Actually restrict forms based on user permissions """ return [{ 'url': url_for('submissions.submission_list', form_id=str(form.id)), 'text': form.name, 'visible': True } for form in filter( lambda f: Permission(ItemNeed('view_forms', f, 'object'), RoleNeed('admin')).can(), services.forms.find(**kwargs))]
def has_permission(self, permission_type, objectId): if objectId is None: return True admin = Permission(RoleNeed(ROLE_ADMIN)) if isinstance(permission_type, tuple): for permission_type_item in permission_type: permission = permission_type_item(unicode(objectId)) if permission.can() or admin.can(): return True else: permission = permission_type(unicode(objectId)) if permission.can() or admin.can(): return True return False
class ReferenceValues(TemplateView): template_name = 'aggregation/admin/reference_values.html' decorators = [require(Permission(need.admin, need.reporter))] def get_context(self, **kwargs): checklist_id = get_reporting_id() current_checklist = get_checklist(checklist_id) checklist_id = current_checklist.id species_refvals = load_species_refval() species_checklist = get_species_checklist(dataset_id=checklist_id) species_data = parse_checklist_ref(species_checklist) species_list = get_species_checklist(groupped=True, dataset_id=checklist_id) habitat_refvals = load_habitat_refval() habitat_checklist = get_habitat_checklist(dataset_id=checklist_id) habitat_data = parse_checklist_ref(habitat_checklist) habitat_list = get_habitat_checklist(distinct=True, dataset_id=checklist_id, groupped=True) relevant_regions = ( {s.bio_region for s in species_checklist}.union( {h.bio_region for h in habitat_checklist} )) bioreg_list = dal.get_biogeo_region_list(relevant_regions) groups = dict( LuGrupSpecie.query .with_entities(LuGrupSpecie.code, LuGrupSpecie.description) ) return dict( species_refvals=species_refvals, species_data=species_data, species_list=species_list, habitat_refvals=habitat_refvals, habitat_data=habitat_data, habitat_list=habitat_list, bioreg_list=bioreg_list, GROUPS=groups, current_checklist=current_checklist, page='refvalues', )
def get_quality_assurance_form_list_menu(**kwargs): """Retrieves a list of forms that have the verification flag set :param form_type: The form type for the forms to be retrieved """ return [{ 'url': url_for('submissions.quality_assurance_list', form_id=str(form.id)), 'text': form.name, 'icon': '<i class="glyphicon glyphicon-ok"></i>', 'visible': True } for form in filter( lambda f: Permission(ItemNeed('view_forms', f, 'object'), RoleNeed('admin')).can(), services.forms.find(**kwargs).order_by('name'))]
def profile(user_id=None): ucontr = None if user_id and admin_permission.can(): ucontr = UserController() elif user_id and Permission(UserNeed(user_id)).can(): ucontr = UserController(user_id) elif user_id: flash(gettext('You do not have rights on this user'), 'danger') raise Forbidden(gettext('You do not have rights on this user')) else: ucontr = UserController(current_user.id) user_id = current_user.id user = ucontr.get(id=user_id) profile_form, pass_form = ProfileForm(obj=user), PasswordModForm() return render_template('profile.html', user=user, admin_permission=admin_permission, form=profile_form, pass_form=pass_form)
def edit_post(id): """View function for edit_post.""" post = Post.query.get_or_404(id) # Ensure the user logged in. if not current_user: return redirect(url_for('main.login')) # Only the post onwer can be edit this post. if current_user != post.user: return redirect(url_for('blog.post', post_id=id)) # Admin can be edit the post. permission = Permission(UserNeed(post.user.id)) if permission.can() or admin_permission.can(): form = PostForm() #if current_user != post.user: # abort(403) if form.validate_on_submit(): post.title = form.title.data post.text = form.text.data post.publish_date = datetime.now() # Update the post db.session.add(post) db.session.commit() return redirect(url_for('blog.post', post_id=post.id)) else: abort(403) # Still retain the original content, if validate is false. form.title.data = post.title form.text.data = post.text return render_template('edit_post.html', form=form, post=post)
def roles_accepted(*args): """View decorator which specifies that a user must have at least one of the specified roles. Example:: @app.route('/create_post') @roles_accepted('editor', 'author') def create_post(): return 'Create Post' The current user must have either the `editor` role or `author` role in order to view the page. :param args: The possible roles. """ roles = args perms = [Permission(RoleNeed(role)) for role in roles] def wrapper(fn): @wraps(fn) def decorated_view(*args, **kwargs): if not current_user.is_authenticated(): return redirect( login_url(current_app.config[LOGIN_VIEW_KEY], request.url)) for perm in perms: if perm.can(): return fn(*args, **kwargs) logger.debug('Identity does not provide at least one of ' 'the following roles: %s' % [r for r in roles]) do_flash(FLASH_PERMISSIONS, 'error') return redirect(request.referrer or '/') return decorated_view return wrapper