Example #1
0
 def post(self):
     request_arg = RequestMethod_parser.parse_args()
     requestMethod = request_arg['requestMethod']
     if requestMethod == "POST":
         permission = Permission(ActionNeed('添加新闻'))
         if permission.can()is not True:
             abort_if_unauthorized("添加新闻")
         args = News_parser.parse_args()
         category = args['category']
         detail = args['detail']
         title = args['title']
         tags = args['tags']
         try:
             tags = list(eval(tags[0]))
         except:
             pass
         soup, imgUrlFirst = handle_html(detail)
         outline = soup.get_text()[:80]
         news = News(soup.prettify(), title, outline, imgUrlFirst)
         db.session.add(news)
         db.session.commit()
         news.addCategory(category)
         for tag in tags:
             t = Tag.query.filter_by(name=tag).first()
             abort_if_not_exist(t, "tag")
             news.tags.append(t)
         db.session.add(news)
         db.session.commit()
     else:
         abort(404, message="api not found")
Example #2
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻")
     news = News.query.filter(News.id == id).first()
     abort_if_not_exist(news, "news")
     return news
Example #3
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻")
     silder_show = SilderShow.query.filter(SilderShow.id == id).first()
     abort_if_not_exist(silder_show, "silder_show")
     return silder_show
Example #4
0
def before_request():
    q_per = AuthManager.query.filter(
        AuthManager.route_name == request.path).all()
    if q_per:
        role = set()
        for p in q_per:
            permission = p.permission
            if permission:
                roles = permission.split(',')
                role.update(roles)

        if role:
            per = Permission()
            for r in role:
                if r:
                    per = per.union(Permission(RoleNeed(r)))

            # print(per.can())
            if current_user.username == 'god':
                return
            if not per.can():
                abort(403)

    else:
        # print(request.path, "is not set auth.")
        pass
Example #5
0
def post(post_id):
    form = CommentForm()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.post_id = post_id
        new_comment.date = datetime.now()
        db.session.add(new_comment)
        db.session.commit()
        return redirect(url_for('.post', post_id=post_id))
    post = Post.query.get_or_404(post_id)
    # 添加阅读量
    post.read = post.read + 1
    db.session.add(post)
    db.session.commit()

    tags = post.tags
    comments = post.comments.order_by(Comment.date.desc()).all()
    # 是否有编辑权限
    permission = Permission(UserNeed(post.user.id))
    is_edit = permission.can() or admin_permission.can()
    if g.is_login:
        form.name.data = current_user.username
    return render_template('post.html',
                           post=post,
                           tags=tags,
                           is_edit=is_edit,
                           comments=comments,
                           form=form)
Example #6
0
 def decorator(*args, **kwargs):
     perm = Permission(*[RoleNeed(role) for role in roles])
     if not current_user.is_authenticated:
         return abort(401)
     if perm.can():
         return f(*args, **kwargs)
     return abort(403)
Example #7
0
    def post(self, restaurant_id, user_id):
        identityPermission = Permission(UserNeed(user_id))
        if not identityPermission.can():
            abort(403)

        #data = parser.parse_args()
        data = request.get_json(force=True)
        order = data['orders'][0]
        order['status'] = "new"
        order_items = data['order_items']
        today = datetime.datetime.now()
        #将request里面的json key转化为数据库model的key
        '''
        for i in order_items:
            temp_item['id'] = i['order_history_item_id']
            temp_item['number'] = i['number']
            temp_item['name'] = i['name']
            temp_item['description'] = i['description']
            temp_item['image'] = i['image']
            temp_item['price'] = i['price']
            temp_item['order_history_id'] = i['order_history_id']
            items.append(temp_item.copy())
        order_items = items
        '''
        #用户自身的订单记录
        OrderHistoryDao.add_order_history(today, order['desk_number'],
                                          order['total_price'],
                                          order['restaurant_id'],
                                          order['user_id'], order_items)
        #同时要发送到餐厅的订单记录
        OrderDao.add_order(today, order['desk_number'], order['total_price'],
                           order['status'], order['restaurant_id'],
                           order_items)
        DaoHelper.commit(db)
        return 204
Example #8
0
 def post(self, id):
     request_arg = RequestMethod_parser.parse_args()
     requestMethod = request_arg['requestMethod']
     if requestMethod == "PUT":
         permission = Permission(ActionNeed('修改新闻标签'))
         if permission.can()is not True:
             abort_if_unauthorized("修改新闻标签")
         tag = Tag.query.filter(Tag.id == id).first()
         abort_if_not_exist(tag, "tag")
         args = parser_spec.parse_args()
         name = args['name']
         if name != None and name != tag.name:
             t = Tag.query.filter(Tag.name == name).first()
             abort_if_exist(t, "tag")
             tag.name = name
         db.session.add(tag)
         db.session.commit()
     elif requestMethod == "DELETE":
         permission = Permission(ActionNeed('删除新闻标签'))
         if permission.can()is not True:
             abort_if_unauthorized("删除新闻标签")
         tag = Tag.query.filter(Tag.id == id).first()
         abort_if_not_exist(tag, "tag")
         db.session.delete(tag)
         db.session.commit()
     else:
         abort(404, message="api not found")
Example #9
0
def records_filter(experiments_needs, admin_needs=None):
    """Filter list of deposits.
    """
    if current_user.is_authenticated:
        user_experiments = []
        if admin_needs and Permission(*admin_needs).can():
            return Q()

        for exp in experiments_needs:
            if Permission(*experiments_needs[exp]).can():
                user_experiments.append(exp.lower())

        q = {
            "bool": {
                "should": [{
                    "terms": {
                        "_experiment": user_experiments
                    }
                }]
            }
        }

        return Q(q)
    else:
        abort(403)
 def decorator(*args, **kwargs):
     topicId = kwargs.get('topicId')
     permission = Permission(EditTopicNeed(topicId))
     if not permission.can():
         flash(_('You have no permission'), 'warning')
         return redirect(url_for('topic.topic', topicId=topicId))
     return func(*args, **kwargs)
Example #11
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻")
     silder_show = SilderShow.query.filter(SilderShow.id == id).first()
     abort_if_not_exist(silder_show, "silder_show")
     return silder_show
Example #12
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看权限节点')))
     if permission.can() is not True:
         abort_if_unauthorized("查看权限节点")
     node = Node.query.filter(Node.id == id).first()
     abort_if_not_exist(node, "node")
     return node
Example #13
0
def edit_post(id):

    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 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)

    form.title.data = post.title
    form.text.data = post.text
    return render_template('edit_post.html', form=form, post=post)
Example #14
0
def edit_post(id):
    if not current_user:
        return redirect(url_for('main.login'))

    post = Post.query.get_or_404(id)

    if current_user != post.user:
        abort(403)

    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.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)
Example #15
0
def edit_post(id):

    post = Post.query.get_or_404(id)
    permission = Permission(UserNeed(post.author.id))
    # 设置访问本视图的权限

    if permission.can() or admin_permission.can():
        # 判断Identity是否有要求的permission
        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('blog.post', post_id=post.id))

        form.text.data = post.text

        return render_template('blog/edit.html', form=form, post=post)

    abort(403)
Example #16
0
def edit_post(id):
    post = Post.query.get_or_404(id)

    #保证用户市登录的
    if not current_user:
        return redirect(url_for('main.login'))

    if current_user != post.users:
        return redirect(url_for('blog.post', post_id=id))

    #当user是poster或者admin,才可以编辑文章
    permission = Permission(UserNeed(post.users.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.published_date = datetime.now()

            db.session.add(post)
            db.session.commit()
            return redirect(url_for('blog.post', post_id=post.id))
        else:
            abort(403)

        form.title.data = post.title
        form.text.data = post.text
        return render_template('edit_post.html', form=form, post=post)
Example #17
0
 def post(self):
     request_arg = RequestMethod_parser.parse_args()
     requestMethod = request_arg['requestMethod']
     if requestMethod == "POST":
         permission = Permission(ActionNeed('添加用户'))
         if permission.can()is not True:
             abort_if_unauthorized("添加用户")
         args = User_parser.parse_args()
         try:
             args['roleName'] = list(eval(args['roleName'][0]))
         except:
             pass
         userName = args['userName']
         passWord = args['passWord']
         email = args['email']
         roleName = args['roleName']
         phone = args['phone']
         user1 = User.query.filter(User.userName == userName).first()
         abort_if_exist(user1, "userName")
         try:
             html = render_template(
                 "Admin/user_info.html", user_name=userName, password=passWord, flag="创建账号")
             send_email("社团网账号信息", [email], html)
             user = User(userName, passWord, email, phone)
             for name in roleName:
                 role = Role.query.filter(Role.roleName == name).first()
                 abort_if_not_exist(role, "role")
                 user.roles.append(role)
             db.session.add(user)
             db.session.commit()
         except:
             pass
     else:
         abort(404, message="api not found")
Example #18
0
 def status(self, value):
     old_status = self._status
     assert value in status_enum_list
     if value == self._status:
         return True
     roles_accepted = self.roles_accepted.get(value, None)
     if roles_accepted:
         perm = Permission(*[RoleNeed(role) for role in roles_accepted])
         if not perm.can():
             raise RuntimeError("You're not authorized to set this status")
     status_required = self.status_required.get(value, None)
     if status_required and self._status != status_required:
         raise ValueError("You cannot set status from {} to {}".format(self._status, value))
     self._status = value
     self.status_changed()
     taxi = TaxiM.cache.get(self.taxi_id)
     taxi.synchronize_status_with_hail(self)
     client = influx_db.get_client(current_app.config['INFLUXDB_TAXIS_DB'])
     try:
         client.write_points([{
             "measurement": "hails_status_changed",
             "tags": {
                 "added_by": User.query.get(self.added_by).email,
                 "operator": self.operateur.email,
                 "zupc": taxi.ads.zupc.insee,
                 "previous_status": old_status,
                 "status": self._status
                 },
             "time": datetime.utcnow().strftime('%Y%m%dT%H:%M:%SZ'),
             "fields": {
                 "value": 1
             }
             }])
     except Exception as e:
         current_app.logger.error('Influxdb Error: {}'.format(e))
Example #19
0
def edit_post(id):

    post = Post.query.get_or_404(id)

    if not current_user:
        return redirect(url_for('main.login'))

    if current_user != post.users:
        return redirect(url_for('blog.post', post_id=id))

    # 当 user 是 poster 或者 admin 时, 才能够编辑文章
    permission = Permission(UserNeed(post.users.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()

            # Update the post
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('blog.post', post_id=post.id))

        # 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)
    else:
        abort(403)
Example #20
0
def _contact_handler(user_id, endpoint):
    contact = Contact.query.get(user_id) if user_id else Contact()
    contact_form = ContactForm(obj=contact)

    admin_permisssion = Permission(RoleNeed('admin'))
    if not admin_permisssion.can():
        del contact_form.roles

    credentials_form = CredentialsForm(obj=contact)
    forms = {
        'contact_details': contact_form,
        'contact_credentials': credentials_form,
    }
    current_form = forms.get(request.form.get('action'))
    if current_form and current_form.validate_on_submit():
        contact = Contact.query.get(user_id) if user_id else Contact()
        current_form.populate_obj(contact)
        if not contact.id:
            db.session.add(contact)
        db.session.commit()
        flash(_('User updated.'), 'success')
        kwargs = {
            'user_id': contact.id,
        }
        return redirect(url_for(endpoint, **kwargs))
    context = {
        'user_id': contact.id,
        'contact': contact,
        'contact_form': contact_form,
        'credentials_form': credentials_form,
    }
    return render_template('admin/users/form.html', **context)
Example #21
0
    def post(self):
        request_arg = RequestMethod_parser.parse_args()
        requestMethod = request_arg['requestMethod']
        print(requestMethod)
        if requestMethod == "POST":
            permission = Permission(ActionNeed('添加角色'))
            if permission.can()is not True:
                abort_if_unauthorized("添加角色")
            args = Role_parser.parse_args()
            roleName = args['roleName']
            try:
                nodeName = list(eval(args['nodeName'][0]))
            except:
                nodeName = args['nodeName']

            role1 = Role.query.filter(Role.roleName == roleName).first()
            abort_if_exist(role1, "roleName")
            role = Role(roleName)
            db.session.add(role)
            db.session.commit()
            for name in nodeName:
                node = Node.query.filter(Node.nodeName == name).first()
                abort_if_not_exist(node, "node")
                role.nodes.append(node)
            db.session.add(role)
            db.session.commit()
        else:
            abort(404, message="api not found")
Example #22
0
def update_user():
    """Update current logged user
    """
    user = current_user
    form = UserForm(request.form, obj=user)
    del form.role
    del form.is_active

    perm = Permission(UserNeed(user.id), RoleNeed('admin'))
    perm.test()

    if form.validate_on_submit():
        if form.username.data != user.username and User.username_is_in_use(
                form.username.data):
            flash(
                "This username is already been used. Please choose another one!",
                "alert-danger")
            form.username.errors.append('Please correct this field')
        elif form.email.data != user.email and User.email_is_in_use(
                form.email.data):
            flash(
                "This email is already been used. Please choose another one!",
                "alert-danger")
            form.email.errors.append('Please correct this field')
        else:
            form.populate_obj(user)
            db.session.commit()
            flash("Informations updated", "alert-info")
            return redirect(url_for('dashboard.index'))

    return render_template("user/update.html", form=form, user=current_user)
Example #23
0
	def post(self):
		request_arg=RequestMethod_parser.parse_args()
		requestMethod=request_arg['requestMethod']
		print(requestMethod)
		if requestMethod=="POST":
			permission=Permission(ActionNeed('添加角色'))
			if permission.can()is not True:
				abort_if_unauthorized("添加角色")
			args=Role_parser.parse_args()
			roleName=args['roleName']
			try:
				nodeName=list(eval(args['nodeName'][0]))
			except:
				nodeName=args['nodeName']
			
			role1=Role.query.filter(Role.roleName==roleName).first()
			abort_if_exist(role1,"roleName")
			role=Role(roleName)
			db.session.add(role)
			db.session.commit()
			for name in nodeName:
				node=Node.query.filter(Node.nodeName==name).first()
				abort_if_not_exist(node,"node")
				role.nodes.append(node)
			db.session.add(role)
			db.session.commit()
		else:
			abort(404,message="api not found")
Example #24
0
    def post(self, id):
        request_arg = RequestMethod_parser.parse_args()
        requestMethod = request_arg['requestMethod']
        if requestMethod == "PUT":
            permission = Permission(ActionNeed('修改新闻属性'))
            if permission.can()is not True:
                abort_if_unauthorized("修改新闻属性")

            category = Category.query.filter(Category.id == id).first()
            abort_if_not_exist(category, "category")
            args = parser_spec.parse_args()
            name = args['name']
            if name != None and name != category.name:
                c = Category.query.filter(Category.name == name).first()
                abort_if_exist(c, "category")
                category.name = name
            db.session.add(category)
            db.session.commit()
        elif requestMethod == "DELETE":
            permission = Permission(ActionNeed('删除新闻属性'))
            if permission.can()is not True:
                abort_if_unauthorized("删除新闻属性")
            id = int(id)
            category = Category.query.filter(Category.id == id).first()
            abort_if_not_exist(category, "category")
            db.session.delete(category)
            db.session.commit()
        else:
            abort(404, message="api not found")
Example #25
0
 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
Example #26
0
	def post(self):
		request_arg=RequestMethod_parser.parse_args()
		requestMethod=request_arg['requestMethod']
		if requestMethod=="POST":
			permission=Permission(ActionNeed('添加用户'))
			if permission.can()is not True:
				abort_if_unauthorized("添加用户")
			args=User_parser.parse_args()
			try:
				args['roleName']=list(eval(args['roleName'][0]))
			except:
				pass
			userName=args['userName']
			passWord=args['passWord']
			email=args['email']
			roleName=args['roleName']
			phone=args['phone']
			user1=User.query.filter(User.userName==userName).first()
			abort_if_exist(user1,"userName")
			user=User(userName,passWord,email,phone)
			for name in roleName:
				role=Role.query.filter(Role.roleName==name).first()
				abort_if_not_exist(role,"role")
				user.roles.append(role)
			db.session.add(user)
			db.session.commit()
		else:
			abort(404,message="api not found")
Example #27
0
	def get(self,id):
		permission=Permission(ActionNeed(('查看权限节点')))
		if permission.can() is not True:
			abort_if_unauthorized("查看权限节点")	
		node=Node.query.filter(Node.id==id).first()
		abort_if_not_exist(node,"node")
		return node
Example #28
0
def edit_post(id):
    # 此处验证用login_required装饰器代替
    """
    if not g.current_user:
        return redirect(url_for('main.login'))
    """
    post = Post.query.get_or_404(id)
    # 此处使用用户权限进行限制访问
    """
    if current_user != post.user:
        abort(403)
    """
    permission = Permission(UserNeed(post.user.id))
    if permission.can() or admin_permission.can():
        form = PostForm()
        if form.validate_on_submit():
            if form.title.data == post.title and form.text.data == post.text:
                flash('no changes detected!', category='message')
            else:
                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)
Example #29
0
def article_edit(id):
    article = BlogArticle.query.get_or_404(id)

    if not current_user:
        return redirect(url_for('site.login'))

    if current_user != article.user:
        return redirect(url_for('blog.article_one', id=id))

    permission = Permission(UserNeed(article.user.id))
    if permission.can() or permission_admin.can():
        form = ArticleForm()
        if form.validate_on_submit():
            article.title = form.title.data
            article.content = form.content.data
            article.publish_time = datetime.datetime.now()

            db.session.add(article)
            db.session.commit()
            return redirect(url_for('blog.article_one', id=article.id))
    else:
        abort(403)

    form.title.data = article.title
    form.content.data = article.content
    return render_template('blog/article/edit.html',
                           obj_form=form,
                           article_one=article)
Example #30
0
def contact(retailer_id, contact_id):
    permisssion = Permission(RoleNeed('normal'))
    need = ItemNeed('access', 'retailer', retailer_id)
    if not permisssion.union(Permission(need)).can():
        return abort(403)
    retailer = Retailer.query.get(retailer_id)
    contact = Contact.query.get(contact_id) if contact_id else Contact()
    contact_form = ContactForm(obj=contact)
    del contact_form.roles
    if contact_form.validate_on_submit():
        contact_form.populate_obj(contact)
        contact.phone = contact_form.phone.data
        if not contact.id:
            retailer.contacts.append(contact)
        db.session.commit()
        flash(_('User updated.'), 'success')
        kwargs = {
            'retailer_id': retailer.id,
            'contact_id': contact.id,
        }
        return redirect(url_for('retailers_bp.contact', **kwargs))
    context = {
        'user_id': contact.id,
        'retailer': retailer,
        'tab_counts': tab_counts(retailer),
        'contact': contact,
        'contact_form': contact_form,
    }
    return render_template('retailers/contact.html', **context)
Example #31
0
 def test_permission_difference(self):
     p1 = Permission(('a', 'b'), ('a', 'c'))
     p2 = Permission(('a', 'c'), ('d', 'e'))
     p3 = p1.difference(p2)
     assert p3.needs == set([('a', 'b')])
     p4 = p2.difference(p1)
     assert p4.needs == set([('d', 'e')])
Example #32
0
    def wrapper():

        route = func.__name__
        q_per = AuthManager.query.filter(AuthManager.route_name == '/' +
                                         route).all()
        if q_per:
            role = set()
            for p in q_per:
                permission = p.permission
                if permission:
                    roles = permission.split(',')
                    role.update(roles)

            if role:
                per = Permission()
                for r in role:
                    if r:
                        per = per.union(Permission(RoleNeed(r)))

                @per.require(http_exception=403)
                def f():
                    return func()

                return f()
            else:
                return func()
        else:
            return func()
Example #33
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻")
     news = News.query.filter(News.id == id).first()
     abort_if_not_exist(news, "news")
     return news
Example #34
0
 def post(self):
     request_arg = RequestMethod_parser.parse_args()
     requestMethod = request_arg['requestMethod']
     if requestMethod == "POST":
         permission = Permission(ActionNeed('添加新闻'))
         if permission.can() is not True:
             abort_if_unauthorized("添加新闻")
         args = News_parser.parse_args()
         category = args['category']
         detail = args['detail']
         title = args['title']
         tags = args['tags']
         try:
             tags = list(eval(tags[0]))
         except:
             pass
         soup = BeautifulSoup(detail, "html.parser")
         k = 0
         for img in soup.find_all('img'):
             imgurl = img.get('src')
             r = request.urlopen(imgurl)
             data = r.read()
             imgBuf = BytesIO(data)
             i = Image.open(imgBuf)
             filename = str(
                 int(random.uniform(1, 1000) + time.time())) + ".png"
             path = os.path.join(app.config['BASEDIR'],
                                 'aunet/static/Uploads/News', filename)
             # return path;
             i.save(path, quality="96")
             f = open(path, "rb")
             data = f.read()
             data = base64.b64encode(data)
             data = str(data)
             data = data[2:-1]
             data = "data:image/jpg;base64," + data
             img['src'] = data
             # return img
             k = k + 1
             if k > 1:
                 os.remove(path)
             else:
                 imgUrlFirst = "static/Uploads/News/" + filename
         if k == 0:
             imgUrlFirst = "static/Uploads/News/1.jpg"  #默认的新闻展示图片
         # return imgUrlFirst
         outline = soup.get_text()[:100]
         news = News(soup.prettify(), title, outline, imgUrlFirst)
         db.session.add(news)
         db.session.commit()
         news.addCategory(category)
         for tag in tags:
             t = Tag.query.filter_by(name=tag).first()
             abort_if_not_exist(t, "tag")
             news.tags.append(t)
         db.session.add(news)
         db.session.commit()
     else:
         abort(404, message="api not found")
Example #35
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看角色')))
     if permission.can() is not True:
         abort_if_unauthorized("查看角色")
     role = Role.query.filter(Role.id == id).first()
     abort_if_not_exist(role, "role")
     data = build_role_data(role)
     return data
Example #36
0
 def decorator(*args, **kwargs):
     permission = Permission(RoleNeed('confirmed'))
     if not permission.can():
         flash(_("You haven't confirm your account,Please confirmed"),
               'warning')
         return redirect(
             url_for('user.user', user_url=current_user.username))
     return func(*args, **kwargs)
Example #37
0
    def test_permission_or(self):
        p1 = Permission(RoleNeed('boss'), RoleNeed('lackey'))
        p2 = Permission(RoleNeed('lackey'), RoleNeed('underling'))

        p3 = p1 | p2
        p4 = p1.difference(p2)

        assert p3.needs == p4.needs
Example #38
0
 def decorated_view(*args, **kwargs):
     perm = Permission(*[RoleNeed(role) for role in roles])
     if perm.can():
         return fn(*args, **kwargs)
     if _security._unauthorized_callback:
         return _security._unauthorized_callback()
     else:
         return _get_unauthorized_view()
Example #39
0
 def decorated_function(*args, **kwargs):
     if not current_user.is_authenticated():
         return redirect(url_for('login_bp.login', next=request.path))
     for key in role_keys:
         permisssion = Permission(RoleNeed(key))
         if permisssion.can():
             return f(*args, **kwargs)
     return abort(403)
Example #40
0
 def decorated_view(*args, **kwargs):
     perm = Permission(*[RoleNeed(role) for role in roles])
     if perm.can():
         return fn(*args, **kwargs)
     if _security._unauthorized_callback:
         # Backwards compat - deprecated
         return _security._unauthorized_callback()
     return _security._unauthz_handler(roles_accepted, list(roles))
Example #41
0
 def decorated_view(*args, **kwargs):
     perm = Permission(*[RoleNeed(role) for role in roles])
     if perm.can():
         return fn(*args, **kwargs)
     if _security._unauthorized_callback:
         return _security._unauthorized_callback()
     else:
         return _get_unauthorized_view()
    def put(self, topicId):
        def callback():
            return jsonify(judge=False, error=_('You have no permission'))

        permission = Permission(EditTopicNeed(topicId))
        if not permission.can():
            self.callback = callback
            return True
Example #43
0
    def test_permission_or(self):
        p1 = Permission(RoleNeed('boss'), RoleNeed('lackey'))
        p2 = Permission(RoleNeed('lackey'), RoleNeed('underling'))

        p3 = p1 | p2
        p4 = p1.difference(p2)

        assert p3.needs == p4.needs
Example #44
0
    def test_permission_and(self):
        p1 = Permission(RoleNeed('boss'))
        p2 = Permission(RoleNeed('lackey'))

        p3 = p1 & p2
        p4 = p1.union(p2)

        assert p3.needs == p4.needs
Example #45
0
 def decorated_view(*args, **kwargs):
     perm = Permission(*[FsPermNeed(fsperm) for fsperm in fsperms])
     if perm.can():
         return fn(*args, **kwargs)
     if _security._unauthorized_callback:
         # Backwards compat - deprecated
         return _security._unauthorized_callback()
     return _security._unauthz_handler(permissions_accepted, list(fsperms))
Example #46
0
    def test_permission_and(self):
        p1 = Permission(RoleNeed('boss'))
        p2 = Permission(RoleNeed('lackey'))

        p3 = p1 & p2
        p4 = p1.union(p2)

        assert p3.needs == p4.needs
Example #47
0
 def decorator(*args, **kwargs):
     permission = Permission(RoleNeed('confirmed'))
     if not permission.can():
         flash(
             _("You haven't confirm your account,Please confirmed"),
             'warning')
         return redirect(url_for('user.user',
                                 user_url=current_user.username))
     return func(*args, **kwargs)
Example #48
0
    def put(self, topicId):
        def callback():
            flash(_("You have no permission"), 'warning')
            return redirect(url_for('topic.topic', topicId=topicId))

        permission = Permission(EditTopicNeed(topicId))
        if not permission.can():
            self.callback = callback
            return True
Example #49
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻标签')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻标签")
     tag = Tag.query.filter_by(id=id).first()
     abort_if_not_exist(tag, "tag")
     data = dict()
     data['name'] = tag.name
     data['id'] = tag.id
     return data
Example #50
0
 def post(self):
     form = request.form.getlist('add-to-collect')
     for collectId in form:
         try:
             collectId = int(collectId)
             permission = Permission(PostCollect(collectId))
             if not permission.can():
                 return True
         except ValueError:
             abort(403)
Example #51
0
 def get(self):
     permission = Permission(ActionNeed(('查看角色')))
     if permission.can() is not True:
         abort_if_unauthorized("查看角色")
     roles = Role.query.all()
     datas = list()
     for role in roles:
         data = build_role_data(role)
         datas.append(data)
     return datas
Example #52
0
def can_access(endpoint):
    """ Method used in templates only, it helps to validate endpoint access """
    f = current_app.view_functions[endpoint]
    if not hasattr(f, 'role_keys'):
        return True
    for role_key in f.role_keys:
        permisssion = Permission(RoleNeed(role_key))
        if permisssion.can():
            return True
    return False
Example #53
0
 def get(self):
     permission = Permission(ActionNeed(('查看用户')))
     if permission.can() is not True:
         abort_if_unauthorized("查看用户")
     datas = list()
     users = User.query.all()
     for user in users:
         data = build_user_data(user)
         datas.append(data)
     return datas
Example #54
0
 def get(self, id):
     permission = Permission(ActionNeed(('查看新闻栏目')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻栏目")
     category = Category.query.filter_by(id=id).first()
     abort_if_not_exist(category, "category")
     data = dict()
     data['name'] = category.name
     data['id'] = category.id
     return data
Example #55
0
def index():
    permisssion = Permission(RoleNeed('normal'))
    retailers = Retailer.query.all()
    for retailer in retailers[:]:
        need = ItemNeed('access', 'retailer', retailer.id)
        if not permisssion.union(Permission(need)).can():
            retailers.remove(retailer)
    context = {
        'retailers': retailers,
    }
    return render_template('retailers/index.html', **context)
Example #56
0
def index(retailer_id):
    permisssion = Permission(RoleNeed('normal'))
    need = ItemNeed('access', 'retailer', retailer_id)
    if not permisssion.union(Permission(need)).can():
        return abort(403)
    retailer = Retailer.query.get(retailer_id)
    context = {
        'retailer': retailer,
        'stocks': retailer.stocks.filter(RetailerProduct.sold_date.is_(None)),
        'tab_counts': tab_counts(retailer),
    }
    return render_template('retailers/stocks.html', **context)
Example #57
0
    def post(self):
        def callback():
            flash(
                _("You haven't confirm your account,Please confirmed"),
                'warning')
            return redirect(url_for('user.user',
                                    user_url=current_user.username))

        permission = Permission(RoleNeed('confirmed'))
        if not permission.can():
            self.callback = callback
            return True
Example #58
0
def contacts(retailer_id):
    permisssion = Permission(RoleNeed('normal'))
    need = ItemNeed('access', 'retailer', retailer_id)
    if not permisssion.union(Permission(need)).can():
        return abort(403)
    retailer = Retailer.query.get(retailer_id)
    context = {
        'retailer': retailer,
        'contacts': retailer.contacts,
        'tab_counts': tab_counts(retailer),
    }
    return render_template('retailers/contacts.html', **context)
Example #59
0
 def get(self):
     permission = Permission(ActionNeed(('查看新闻标签')))
     if permission.can() is not True:
         abort_if_unauthorized("查看新闻标签")
     tags = Tag.query.all()
     datas = list()
     for tag in tags:
         data = dict()
         data['name'] = tag.name
         data['id'] = tag.id
         datas.append(data)
     return datas