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 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 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'))
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
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 Policy: def __init__(self, name): self.name = name self._action_need = ActionNeed(name) self._permission = Permission(self._action_need) def __str__(self): return self.name def __repr__(self): return '<Policy %s>' % self.name def can(self): return self._permission.can() def require(self, *args, **kwargs): return self._permission.require(*args, **kwargs) @property def permission(self): return self._permission @property def action_need(self): return self._action_need
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 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'))
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 get(self, user_id): """ Get details for a given user. """ personal_details_view = Permission(UserNeed(user_id)) is_self = personal_details_view.can() user = User.query.get_or_404(user_id) return { 'user': user.to_json(include_personal_data=is_self), }
def decorated_view(*args, **kwargs): perm = Permission(*[RoleNeed(role) for role in roles]) if perm.can(): return fn(*args, **kwargs) r1 = [r for r in roles] r2 = [r.name for r in current_user.roles] _logger.debug('Current user does not provide a required role. ' 'Accepted: %s Provided: %s' % (r1, r2)) return _get_unauthorized_view()
def test(self, *records): if self._model_view.permission_required: def _get_edit_need(obj): pk = self._model_view.modell.get_pk_value(obj) return self._model_view.edit_need(pk) needs = [_get_edit_need(record) for record in records] perm = Permission(*needs).union(Permission( self._model_view.edit_all_need)) return 0 if perm.can() else ACTION_IMPERMISSIBLE
def decorated_view(*args, **kwargs): iden = Identity(g.user.id) for r in g.user.roles: iden.provides.add(RoleNeed(r.name)) g.identity = iden perm = Permission(*[RoleNeed(role) for role in roles]) if perm.can(): return fn(*args, **kwargs) abort(403, message=u"Недостаточно прав!")
def delete(self, entry_id): """ Delete the entry with the given ID. """ entry = Entry.query.get(entry_id) delete_permission = Permission(UserNeed(entry.stream.creator_id)) if delete_permission.can(): db.session.delete(entry) return {'msg': 'Entry deleted.'} else: return { 'msg': 'Only the stream creator can delete entries.', }, 403
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 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, )
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 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, )
def delete(self, stream_id): """ Delete the stream with the given ID. """ stream = Stream.query.get_or_404(stream_id) delete_permission = Permission(UserNeed(stream.creator_id)) if delete_permission.can(): movie = stream.movie movie.number_of_streams -= 1 db.session.delete(stream) db.session.add(movie) return {'msg': 'Stream deleted.'} else: return { 'msg': "You're not allowed to delete this stream." }, 403
def put(self, entry_id): """ Update the entry with the given ID. """ entry = Entry.query.get_or_404(entry_id) put_permission = Permission(UserNeed(entry.stream.creator_id)) if put_permission.can(): form = EntryForm(obj=entry) if form.validate_on_submit(): form.populate_obj(entry) return { 'msg': 'Entry updated.', 'entry': entry.to_json(), } return { 'msg': 'Some attributes did not pass validation.', 'errors': form.errors, }, 400 else: return { 'msg': "Only the stream creator can edit it's entries.", }, 403
def put(self, stream_id): """ Update the stream with the given ID. """ stream = Stream.query.get_or_404(stream_id) edit_permission = Permission(UserNeed(stream.creator_id)) if edit_permission.can(): form = StreamForm(obj=stream) if form.validate_on_submit(): form.populate_obj(stream) return { 'msg': 'Stream updated.', 'stream': stream.to_json(), } return { 'msg': 'Some attributes did not pass validation.', 'errors': form.errors, }, 400 else: return { 'msg': "You're not allowed to edit this stream" }, 403
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 edit_post(id): """Edit existing blog post.""" post = Post.query.get_or_404(id) permission = Permission(UserNeed(post.user.id)) 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.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 post(self, stream_id): """ Create new entry. """ stream = Stream.query.get_or_404(stream_id) add_entry_to_stream_permission = Permission(UserNeed(stream.creator_id)) if add_entry_to_stream_permission.can(): form = EntryForm() if form.validate_on_submit(): entry = Entry() form.populate_obj(entry) entry.stream = stream db.session.add(entry) db.session.commit() return { 'msg': 'Entry created.', 'entry': entry.to_json(), }, 201 return { 'msg': 'Some attributes did not pass validation.', 'errors': form.errors, }, 400 else: return { 'msg': 'Only the creator can add entries to streams', }, 403
def require_item_perm(action, item, http_exception=403): perm = Permission(ItemNeed(action, item, 'object'), RoleNeed('admin')) if not perm.can(): abort(http_exception, perm)
def decorated_view(*args, **kwargs): perm = Permission(*[RoleNeed(role) for role in roles]) if perm.can(): return fn(*args, **kwargs) return _get_unauthorized_view()
def decorated_view(*args, **kwargs): perm = Permission(*[RoleNeed(role) for role in roles]) if perm.can(): return fn(*args, **kwargs) return _get_unauthorized_view()
def has_role(self, role): p = Permission(RoleNeed(role)) return p.can()
def decorated_view(*args, **kwargs): perm = Permission(*[RoleNeed(role) for role in roles]) if perm.can(): return fn(*args, **kwargs) abort(403)
def permission(role): perm = Permission(RoleNeed(role)) return perm.can()
def require_item_perm(action, item, http_exception=403): perm = Permission(ItemNeed(action, item, 'object'), RoleNeed('admin')) if not perm.can(): abort(http_exception, perm)