Exemplo n.º 1
0
def user(display_hash=None, action=None):
    """ Create or edit a user. """
    
    if not display_hash:
        abort(404)
    
    user = User.query.filter(User.display_hash==display_hash).first()
    if not user:
        abort(404)
    
    if request.method == 'POST':
        form = UserForm(request.form)
        
        if form.validate():
            #TODO Flash message if this condition is not met
            if form.display_hash.data == current_user.display_hash or current_user.is_admin():
                user = User.query.filter(User.display_hash==form.display_hash.data).first()
                user.update_from_model(user)
                
                if current_user.is_admin():
                    user.roles = []
                    for display_hash in request.form.getlist('role'):
                        role = Role.query.filter(Role.display_hash==display_hash).first()
                        user.roles.append(role)
                db.session.commit()
                return redirect(url_for('users'))
    
    if request.method == 'GET':
        form = UserForm(obj=user)
        
    action = url_for('user', display_hash=user.display_hash)
    roles = Role.query.all()
    return render_template('user.html', form=form, action=action, roles=roles, user=user)
Exemplo n.º 2
0
def view(certificate_id):
    use_ssl = Setting.get_by_name('use_ssl', default=False).value
    if use_ssl == False:
        abort(404)

    cert = Certificate.get_by_id(certificate_id)

    if cert.type != CLIENT and not current_user.is_admin():
        abort(403)

    ca_cert = Certificate.query.filter_by(type=CA).first()
    if cert.user != current_user and not current_user.is_admin():
        abort(403)

    return render_template('certificate/view.html', certificate=cert, ca_cert=ca_cert, current_user=current_user, active='certificates', ssl=use_ssl)
Exemplo n.º 3
0
def pluginCommand(name):
	api_plugins = octoprint.plugin.plugin_manager().get_filtered_implementations(lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin)

	if not api_plugins:
		return make_response("Not found", 404)

	if len(api_plugins) > 1:
		return make_response("More than one api provider registered for {name}, can't proceed".format(name=name), 500)

	api_plugin = api_plugins[0]
	valid_commands = api_plugin.get_api_commands()
	if valid_commands is None:
		return make_response("Method not allowed", 405)

	if api_plugin.is_api_adminonly() and not current_user.is_admin():
		return make_response("Forbidden", 403)

	command, data, response = get_json_command_from_request(request, valid_commands)
	if response is not None:
		return response

	response = api_plugin.on_api_command(command, data)
	if response is not None:
		return response
	return NO_CONTENT
def edit(id):
    if current_user.is_anonymous():
        flash(
            Markup('<span class="glyphicon glyphicon-info-sign"></span> You have to login before editing a proposal.'),
            "info",
        )
        return redirect("/login?next=" + str(request.path))

    """ Edit an proposal """
    p = Proposal.objects.get_or_404(id=id)
    form = ProposalForm(request.form, p)

    if not current_user.is_admin() and current_user.id == p.proposer.id:
        interested_list = p.interested[:]  # Deep copy to manipulate
        for interested in interested_list:
            if interested.user.id == current_user.id:
                interested_list.remove(interested)
        if len(interested_list) > 0:
            flash(
                Markup(
                    '<span class="glyphicon glyphicon-info-sign"></span> You cannot edit a proposal that has interested users.'
                ),
                "info",
            )
            return redirect(url_for("proposals.detail", id=p.id))

            # submit
    if form.validate_on_submit():
        form.populate_obj(p)
        import datetime

        p.updated = datetime.datetime.now()
        p.save()
        return redirect(url_for("proposals.detail", id=p.id))
    return render_template("proposal/edit.html", title=_("Edit a proposal"), proposal=p, form=form)
Exemplo n.º 5
0
def update_name(_id):
    # Check auth
    if not current_user.is_admin():
        flash("Only admins can force-update user names.", "danger")
        return redirect(request.referrer or url_for("index"))

    # Get user
    _user = User.query.filter(User.id == _id).first()
    if _user is None:
        flash("User {} not found.".format(_id), "danger")
        return redirect(request.referrer or url_for("index"))

    old_name = _user.name
    _user.update_steam_name()
    new_name = _user.name

    current_app.logger.info("Manually triggered a user name update.", extra={
        'extra': {
            'old_name': old_name,
            'new_name': new_name,
            'actioned_by': current_user.id
        }
    })

    flash(u"Updated user {}'s name from {} to {}.".format(_id, old_name, new_name), "success")
    return redirect(request.referrer or url_for("index"))
Exemplo n.º 6
0
def view_form_history(word=None):
    page = flask.g.database.get_page(get_url(word))
    access_edit = False
    if page is not None:
        # Проверка на права пользователя вносить правки в статью
        if current_user.is_authenticated():
            access_edit = access_f(page['access'], current_user)
    if current_user.is_authenticated():
        if current_user.is_admin():
             access_edit = True

    if current_user.is_authenticated() is False or access_edit is False:
        return render_template('page.html',
                               page=None,
                               message=u"Вы не имеете прав на просмотр истории изменения страницы",
                               navigation=True,
                               word=get_url(word),
                               history = True
                               )

    pages = flask.g.database.get_pages_history(get_url(word))
#    if pages is None:
#        return 'error!'
#    else:
    return render_template('history.html', pages=pages, word=get_url(word), navigation=True, history = True)
Exemplo n.º 7
0
def settings(_id):
    # Authentication
    if current_user.id != _id and not current_user.is_admin():
        flash("You are not authorised to edit user {}'s settings.".format(_id), "danger")
        return redirect(request.referrer or url_for("index"))

    # Check user exists
    _user = User.query.filter(User.id == _id).first()
    if _user is None:
        flash("User {} not found.".format(_id), "danger")
        return redirect(request.referrer or url_for("index"))

    # Validate form, if submitted; else render it.
    form = SettingsForm(_user, request.form)

    if form.validate_on_submit():
        _user.email = form.email.data
        _user.show_ads = form.show_ads.data
        db.session.add(_user)
        db.session.commit()
        return redirect(request.args.get("next") or url_for("users.user", _id=_user.id))

    return render_template("users/settings.html",
                           title="Your settings - Dotabank",
                           user=_user,
                           form=form)
Exemplo n.º 8
0
 def index(self):
     if current_user.is_authenticated():
         if not current_user.is_admin():
             return redirect(url_for('chat.login'))
     else:
         return redirect(url_for('chat.login'))
     return super(CustomAdminIndexView, self).index()
Exemplo n.º 9
0
 def test_student_login(self):
     # Ensure login behaves correctly.
     with self.client:
         self.client.get('/logout', follow_redirects=True)
         response = self.client.post(
             '/login',
             data=dict(
                 email='*****@*****.**',
                 password='******',
                 confirm='student_user'
             ),
             follow_redirects=True
         )
         self.assertIn(
             b'Welcome, <em>[email protected]</em>!',
             response.data
         )
         self.assertIn(
             b'<li><a href="/student/courses">View Courses</a></li>',
             response.data
         )
         self.assertIn(
             b'<li><a href="/password">Update Password</a></li>',
             response.data
         )
         self.assertTrue(current_user.email == "*****@*****.**")
         self.assertTrue(current_user.is_authenticated)
         self.assertTrue(current_user.is_active)
         self.assertFalse(current_user.is_anonymous())
         self.assertTrue(current_user.is_student())
         self.assertFalse(current_user.is_teacher())
         self.assertFalse(current_user.is_admin())
         self.assertEqual(response.status_code, 200)
Exemplo n.º 10
0
def add_user():
    """ CRUD for adding a user. """
    
    if not current_user.is_admin():
        return redirect('users')
    
    if request.method == 'POST':
        form = UserForm(request.form)
        
        if form.validate():
            existing_user = User.query.filter(User.username==form.username.data).first()
            if existing_user:
                #TODO Set error to be displayed (flash?)
                return redirect(url_for('users'))
                
            user = form.populated_object()
            user.generate_uuid()
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('users'))
        
    if request.method == 'GET':
        form = UserForm()
        
    action = url_for('add_user')
    roles = Role.query.all()
    return render_template('user.html', form=form, action=action, roles=roles)
Exemplo n.º 11
0
def add_dl_job(_id):
    # Check auth
    if not current_user.is_admin():
        flash("Only admins can add new DL jobs.", "danger")
        return redirect(request.referrer or url_for("index"))

    # Check replay exists
    _replay = Replay.query.filter(Replay.id == _id).first()
    if _replay is None:
        flash("Replay {} doesn't exist.".format(_id), "danger")
        return redirect(request.referrer or url_for("index"))

    # Update status
    _replay.status = "WAITING_DOWNLOAD"
    db.session.add(_replay)

    # Add to job queue.
    queued = Replay.add_dl_job(_replay)
    if queued:
        flash("Added DL job for replay {}.".format(_id), "info")
        db.session.commit()
    else:
        flash("Error adding DL job for replay {}.".format(_id), "danger")
        db.session.rollback()

    return redirect(request.referrer or url_for("index"))
Exemplo n.º 12
0
def post_admin_data():
    if current_user.is_admin():
        res={}
        query = request.json

        if query['op']=='getValues':
            pid = query['dataID']
            p = Point.query.get(pid)
            res['status']='ok'
            res['fields']=[]
            for f in Point.get_external_fields():
                res['fields'].append({"field":f, "data":getattr(p,f)})
            res['fields'].append({"field":'geopointAc',"data":{'id':p.geo.id, 'name':p.geo.name} })

        else:
            res['status']='ok'
            pid = query['dataID']
            if query['op']=='edit':
                p = Point.query.get(pid)
            elif query['op']=='add':
                p =Point()
            for key, value in query['fields'].items():
                print(key, value)
                setattr(p, key, value)
            geo_id = query['fields']['geopointAc']['id']
            print ('>>>>>'+str(geo_id))
            if geo_id !=-1: p.geoId=geo_id
            db.session.add(p)
            db.session.commit()
        return json.dumps(res)
Exemplo n.º 13
0
 def test_update_password2(self):
     # Ensure update password behaves correctly.
     with self.client:
         self.client.post(
             '/login',
             data=dict(
                 email='*****@*****.**',
                 password='******',
             ),
             follow_redirects=True
         )
         response = self.client.post(
             '/password',
             data=dict(
                 password='******',
                 confirm='short'
             ),
             follow_redirects=True
         )
         self.assertIn(
             b'<h1>Update Password</h1>',
             response.data
         )
         self.assertIn(
             b'Field must be between 6 and 25 characters long.',
             response.data
         )
         self.assertTrue(current_user.email == '*****@*****.**')
         self.assertTrue(current_user.is_authenticated())
         self.assertTrue(current_user.is_active())
         self.assertFalse(current_user.is_anonymous())
         self.assertTrue(current_user.is_student())
         self.assertFalse(current_user.is_teacher())
         self.assertFalse(current_user.is_admin())
         self.assertEqual(response.status_code, 200)
Exemplo n.º 14
0
    def post(self):        
        if request.method == 'POST':
            form = NewUserForm()
            if form.validate_on_submit():
                try:
                    user = User.create()
                    # Set Permissions
                    if current_user.is_admin():
                        user.role = int(form.role.data)

                    del form.role
                    del form.timezone
                    del form.lang
                    form.populate_obj(user)
                    user.set_password(form.password.data)
                    user.save()

                    flash(gettext('User was succesfully saved'))
                    return redirect(url_for('UsersView:get',id=user.id))                     
                except:
                    flash(gettext('Error while creating the user'), 'error')
                    raise                    
            else:
                flash(gettext('Invalid submission, please check the messages below'), 'error')
        else:
            form = NewUserForm()

        return render_template('admin/users/add.html', 
            title = gettext('Create new user'),
            form = form,
            user = [])
Exemplo n.º 15
0
def organize(id):
	if current_user.is_anonymous():
		flash(Markup("<span class=\"glyphicon glyphicon-info-sign\"></span> You have to login before organizing a proposal."), "info")
		return redirect('/login?next=' + str(request.path))

	p = Proposal.objects.get_or_404(id=id)

	# Throw 403 if user isn't an admin
	if not current_user.is_admin():
		abort(403)

    # You can only organize proposals with interested users
	if p.num_interested == 0:
		flash(Markup("<span class=\"glyphicon glyphicon-exclamation-sign\"></span> You cannot " 
        + "organize a proposal that has no interested users."), "danger")
		return redirect(url_for('proposals.detail', id=p.id))

	form = OrganizeProposalForm()
	if form.validate_on_submit():
		e = Event()
		e.creator = current_user._get_current_object()
		form.populate_obj(e)
		e.save()	
		#p.delete()
		return redirect(url_for('events.detail', id=e.id))

	return render_template("proposal/organize.html", form=form, proposal_title=p.title, proposal_description=p.description)
Exemplo n.º 16
0
def delete_users(user):
    print user
    ## Checks if the user is an admin
    if current_user.is_admin(current_user.username):
        u = User.query.filter_by(username=user).first()
        us = UserStatistics.query.filter_by(userId=u.id).first()
	
	## Checks if the user tries to delete itself
	if current_user.username == u.username:
		flash('Sorry, but you cannot delete yourself. Think about those people who love you more than their world mi amigo.')
		return redirect(url_for('Users.set_roles'))
        # loads the supervisor and deletes the user
        load_supervisor = u.supervisor
        supervisor = User.query.filter_by(username=load_supervisor).first()
        load_supervisees = supervisor.supervisee
        print "Load supervisee before split: " + str(load_supervisees)
        load_supervisees = load_supervisees.split(' ')
        print "Load supervisee after split: " + str(load_supervisees)
        load_supervisees.remove(u.username)
        supervisor.supervisee = ' '.join(load_supervisees)
        print supervisor.supervisee
        db_session.delete(u)
        db_session.add(supervisor)
        db_session.commit()
        flash('User Deleted')
        return redirect(url_for('Users.set_roles'))
    flash('USER UNAUTHORIZED')
    return redirect(url_for('Home.show_home'))
Exemplo n.º 17
0
def delete_comment(comment_id):
    if (current_user.is_anonymous()):
        return '{ "state": "failed" }'
    if CommentService.remove_comment_by_id(comment_id, current_user.id, current_user.is_admin()):
        return '{ "state": "ok" }'
    else:
        return '{ "state": "failed" }'
Exemplo n.º 18
0
def edit(username):
    if current_user.username != username and not current_user.is_admin():
        return redirect(url_for('user.home', username=username))
    user = User.query.filter_by(username=username).first()
    if not user: 
        return redirect(url_for('user.home',username=username))

    form = EditUserForm(request.form, obj=user)
    if form.validate_on_submit():
        # create an user instance not yet stored in the database
        if username != form.username.data.lower():
	    user_already_exist = User.query.filter_by(username=form.username.data.lower()).first()
	    if user_already_exist:
	        flash('Username already exists', 'danger')
	        return render_template("user.edit.html", form=form, user=user)

        user.name=form.name.data 
        user.username=form.username.data.lower()
        user.email=form.email.data.lower()
        if len(form.password.data):
            user.password=generate_password_hash(form.password.data)
        user.role = form.role.data
        # Insert the record in our database and commit it
        try:
            db.session.add(user)
            db.session.commit()
            flash('User edited successfully!')
        except:
            db.session.rollback()
            flash('Unable to edit user', 'danger')

        # redirect user to the 'home' method of the user module.
        return redirect(url_for('user.home', username=user.username))

    return render_template("user.edit.html", form=form, user=user)
Exemplo n.º 19
0
 def relevant_posts(query):
     if not current_user.is_admin():
         query = query.filter(Post.last_published_at != None)
     project_id = request.args.get('project_id')
     if project_id:
         query = query.filter(Post.project_id == project_id)
     return query
Exemplo n.º 20
0
def post_admin_tables():
    if current_user.is_admin():
        res={}
        query = request.json


        if query['cmd']=='getTable':
            if query['tid']=='geosTable':
                geos = Geo.query.all()
                res['tableRows']=[]
                res['tableHeader']=['Name','Address', 'Number', 'Country']
                for g in geos:
                    res['tableRows'].append([g.name, g.formatted_address, g.number, g.country.name])
                res['status']='ok'
            elif query['tid']=='pointsTable':
                points = Point.query.all()
                res['tableRows']=[]
                res['tableHeader']=['Id','Name','GEO', 'pop','bch']
                for p in points:
                    res['tableRows'].append([p.id, p.pointName, p.geo.name, p.pointPop, p.rtBch])
                res['status']='ok'
            else:
                res['status']='unknown table'
        else:
            res['status']='unknown command'


    else:
        res= {'status':'unauthorized'}
    return json.dumps(res)
Exemplo n.º 21
0
def role(page=1):
    """ Create and list roles. """
    
    if not current_user.is_admin():
        return redirect(url_for('index'))
    
    if request.method == 'POST':
        if 'display_hash' in request.form:
            display_hash = request.form['display_hash']
            role = Role.query.filter(Role.display_hash==display_hash).first()
            #TODO Flash message if role does not exist
            if role:
                db.session.delete(role)
                db.session.commit()
                return redirect(url_for('role', page=page))
        
        form = RoleForm(request.form)
        if form.validate():
            existing_role = Role.query.filter(Role.title==form.title.data).first()
            #TODO If role exists, flash message
            if not existing_role:
                role = form.populated_object()
                if form.add_all_users.data:
                    role.users = User.query.all()
                
                db.session.add(role)
                db.session.commit()
                return redirect(url_for('role', page=page))
        
    if request.method == 'GET':
        form = RoleForm()
    
    pagination = Role.query.paginate(page, CONVERSATIONS_PER_PAGE, False)    
    return render_template('roles.html', pagination=pagination, form=form)
Exemplo n.º 22
0
def edit(id):
    notification = Notification.query.filter_by(id=id).first_or_404()
    if notification.user != current_user and not current_user.is_admin():
        abort(403)

    type_id, form_type = NOTIFICATION_TYPE_DETAILS[NOTIFICATION_TYPES[notification.type]]
    obj = notification
    if request.method == "POST":
        obj = None

    form = form_type(obj=obj)

    if not form.is_submitted():
        form.populate_from_settings(id)

    if form.validate_on_submit():
        notification.description = form.description.data
        form.populate_settings(notification.settings, id=id)

        db.session.add(notification)
        db.session.commit()

        current_app.decoder.refresh_notifier(id)

        if str(ZONE_FAULT) in form.subscriptions.data or str(ZONE_RESTORE) in form.subscriptions.data:
            return redirect(url_for("notifications.zone_filter", id=notification.id))

        return redirect(url_for("notifications.review", id=notification.id))

    use_ssl = Setting.get_by_name("use_ssl", default=False).value

    return render_template(
        "notifications/edit.html", form=form, id=id, notification=notification, active="notifications", ssl=use_ssl
    )
Exemplo n.º 23
0
def flatten_series_by_url(data):
	if not current_user.is_admin():
		return getResponse(error=True, message="You have to have administrator privileges to do that!")

	dups = db.engine.execute('''
		SELECT
			website, COUNT(*) AS dupes
		FROM
			series
		WHERE
			website IS NOT NULL AND website != ''
		GROUP
			BY website
		HAVING
			(COUNT(*) > 1);''')
	dups = list(dups)

	match_num = 0
	for website, number in dups:
		print(website, number)
		matches = Series.query.filter(Series.website==website).all()
		ids = [match.id for match in matches]
		zipped = list(zip(ids, ids[1:]))
		for m1, m2 in zipped:
			match_num += 1
			merge_series_ids(m1, m2)

	return getResponse("%s Items merged." % match_num, error=False)
Exemplo n.º 24
0
def edit(id):
    notification = Notification.query.filter_by(id=id).first_or_404()
    if notification.user != current_user and not current_user.is_admin():
        abort(403)

    type_id, form_type = NOTIFICATION_TYPE_DETAILS[NOTIFICATION_TYPES[notification.type]]
    obj = notification
    if request.method == 'POST':
        obj = None

    form = form_type(obj=obj)

    if not form.is_submitted():
        form.populate_from_settings(id)

    if form.validate_on_submit():
        form.populate_obj(notification)
        form.populate_settings(notification.settings, id=id)

        db.session.add(notification)
        db.session.commit()

        current_app.decoder.refresh_notifier(id)

        flash('Notification saved.', 'success')

    use_ssl = Setting.get_by_name('use_ssl', default=False).value

    return render_template('notifications/edit.html',
                            form=form,
                            id=id,
                            notification=notification,
                            active='notifications',
                            ssl=use_ssl)
Exemplo n.º 25
0
def messages():
    if not current_user.is_admin():
        abort(403)

    messages = NotificationMessage.query.all()

    return render_template("notifications/messages.html", messages=messages, active="notifications")
Exemplo n.º 26
0
def index():
    current_app.logger.debug('debug')
    
    if current_user.is_authenticated():
        if current_user.is_admin():
            return redirect(url_for('admin.index'))
        return redirect(url_for('user.index'))
    
    form = LoginForm(login=request.args.get('login', None),
                     next=request.args.get('next', None))

    if form.validate_on_submit():
        user, authenticated = User.authenticate(form.login.data,
                                    form.password.data)

        if user and authenticated:
            remember = request.form.get('remember') == 'y'
            if login_user(user, remember=remember):
                user.locale_code = request.form.get('locale_code')
                db.session.add(user)
                db.session.commit()            
                #flash(_("Logged in"), 'success')
            return redirect(form.next.data or url_for('user.index'))
        else:
            flash(_('Sorry, invalid login'), 'error')

    return render_template('frontend/login.html', form=form)
Exemplo n.º 27
0
Arquivo: app.py Projeto: amumu/wyzq
def on_identity_loaded(sender, identity):
    identity.user = current_user
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))
    if hasattr(current_user, 'is_admin'):
        if current_user.is_admin():
            identity.provides.add(RoleNeed('admin'))
Exemplo n.º 28
0
    def put(self, id):
        post = Post.get_by_id(id)
        if post is None:
            flash(gettext('The post was not found'), 'error')
            return redirect(url_for('PostsView:index'))
        if not current_user.is_admin() and not post.is_mine():
            abort(401)

        if request.method in ['POST', 'PUT']:
            form = EditPostForm()
            if form.validate_on_submit():
                try:
                    form.populate_obj(post)
                    post.save()
                    flash(gettext('Post was succesfully saved'))
                    if request.method == 'POST':
                        if form.remain.data:
                            return redirect(url_for('PostsView:get', id=post.id))
                        else:
                            return redirect(url_for('PostsView:index'))
                except:
                    flash(gettext('Error while updating the post'), 'error')
            else:
                flash(gettext('Invalid submission, please check the message below'), 'error')
            
            if request.method == 'PUT':
                return jsonify(redirect_to=url_for('PostsView:index'))
        else:
            form = NewPostForm(post)
        return render_template('admin/posts/edit.html',
            title=gettext('Edit Post: %(title)s', title=post.title),
            form=form,
            post=post)
Exemplo n.º 29
0
def admin_delete_live():
    if current_user.is_admin():
        models.Live.delete(request.form['live_id'])
        lecloud.cancelLive(request.form['activity_id'])
    else:
        flash('权限不足!')
    return redirect(url_for('admin'))
def edit_comment(discussion_id, comment_id, proposal_id):
	if current_user.is_anonymous():
		flash(Markup("<span class=\"glyphicon glyphicon-info-sign\"></span> You have to login before editing a comment."), "info")
		return redirect('/login?next=' + str(request.path))

	""" Edit a comment of a discussion """
	d = Discussion.objects.get_or_404(id=discussion_id)
	c = Comment.objects.get_or_404(id=comment_id)
	form = EditCommentForm()

	# If the user is not the owner of the comment and not an admin, throw a 403
	if current_user._get_current_object() != c.creator:
		if not current_user.is_admin():
			abort(403)

	if form.validate_on_submit():
		c.edit_comment(newText=form.text.data)
		return redirect(url_for('discussions.detail', discussion_id=d.id, proposal_id=proposal_id))

	return render_template('discussion/edit_comment.html',
		discussion = d,
        proposal_id = proposal_id,
		title = d.title,
		comment = c,
        text = c.text,
        form = form)
Exemplo n.º 31
0
 def decorator(*args, **kwargs):
     if not current_user.is_admin():
         abort(403)
     return f(*args, **kwargs)
Exemplo n.º 32
0
def before_request():
    """ If logged in user is an admin, add the flask-admin object to the global scope. """
    if current_user.is_admin():
        g.admin = admin  # Only utilized under is_admin condition
Exemplo n.º 33
0
Arquivo: login.py Projeto: maocis/ybk
 def decorated_view(*args, **kwargs):
     if current_user.is_authenticated() and current_user.is_admin():
         return func(*args, **kwargs)
     else:
         return current_app.login_manager.unauthorized()
Exemplo n.º 34
0
 def decorated_view(*args, **kwargs):
     if not (current_user.is_authenticated() and current_user.is_admin()):
         abort(403)
     return f(*args, **kwargs)
Exemplo n.º 35
0
def changePasswordForUser(username):
	if userManager is None:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		if "application/json" in request.headers["Content-Type"]:
			data = request.json
			if "password" in data.keys() and data["password"]:
				try:
					userManager.changeUserPassword(username, data["password"])
				except users.UnknownUser:
					return app.make_response(("Unknown user: %s" % username, 404, []))
		return jsonify(SUCCESS)
	else:
		return app.make_response(("Forbidden", 403, []))
Exemplo n.º 36
0
 def is_accessible(self):
     if current_user.is_authenticated():
         if current_user.is_admin():
             return True
Exemplo n.º 37
0
def admin():
    if current_user.is_admin():
        user_list = models.User.list()
        return render_template('admin.html', user_list=user_list)
    else:
        return redirect(url_for('manage'))
Exemplo n.º 38
0
 def is_accessible(self):
     if not current_user.is_anonymous:
         return current_user.is_admin()
     return False
Exemplo n.º 39
0
 def is_accessible(self):
     return current_user.is_admin()
Exemplo n.º 40
0
 def is_accessible(self):
     if not current_user:
         return False
     return current_user.is_admin() if hasattr(current_user,
                                               'is_admin') else False
Exemplo n.º 41
0
def getUser(username):
	if userManager is None:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		user = userManager.findUser(username)
		if user is not None:
			return jsonify(user.asDict())
		else:
			abort(404)
	else:
		abort(403)
Exemplo n.º 42
0
def limitedAdmin(**kwargs):
    if not current_user.is_admin():
        return abort(403)

    return render_template('index.html', brand_image=get_brand_image())
Exemplo n.º 43
0
    def decorated_function(*args, **kwargs):
        if user_is_anonymous(current_user) or not current_user.is_admin():
            if Setting.get_by_name('setup_complete', default=False) == True:
                abort(403)

        return f(*args, **kwargs)
Exemplo n.º 44
0
def query_on_description(description):
    offset = request.args.get('offset', 0)
    size = request.args.get('size', 10)
    order_by = request.args.get('order_by', "upload_time")
    reverse = request.args.get('reverse', 0) > 0
    res = VideoListService.query_on_description(description, offset, size, order_by, reverse,
                                          show_banned = (not current_user.is_anonymous()) and current_user.is_admin(),
                                          show_disabled = (not current_user.is_anonymous()) and current_user.is_admin())
    res = [v.to_rich_dict() for v in res]
    return json.dumps(res, ensure_ascii = False)
Exemplo n.º 45
0
def update():
    """ route to update the database """
    if current_user.is_admin():
        app.update_db.set()
    return redirect(url_for("index"))
Exemplo n.º 46
0
 def authorize_changes(resource):
     return current_user.is_admin()
Exemplo n.º 47
0
 def decorated_view(*args, **kwargs):
     logger.info("admin access attempt by %s" % current_user.get_id())
     if not current_user.is_admin():
         return flask.abort(403)  # access denied
     return fn(*args, **kwargs)
Exemplo n.º 48
0
    def decorated_function(*args, **kwargs):
        if not current_user.is_admin():
            flash('Nu puteti face aceasta operatie!')
            return redirect(request.referrer)

        return f(*args, **kwargs)
Exemplo n.º 49
0
def check_mod_permissions(mod):
    if mod.completed is False or mod.enabled is False:
        abort(404)
    elif mod.visibility == "H" and current_user not in mod.authors and not current_user.is_admin():
        abort(403)
Exemplo n.º 50
0
    def wrapper(*args, **kwargs):
        if current_user.is_admin():
            return func(*args, **kwargs)

        abort(403)
Exemplo n.º 51
0
def edit(mod_id):
    mod = Mod.query.get_or_404(mod_id)
    new_item = False
    if request.referrer == url_for(".upload", _external=True):
        new_item = True

    check_edit_permissions(mod)
    edit_form = EditMod()

    edit_form.equip_regions.query = TF2EquipRegion.query.all()
    edit_form.bodygroups.query = TF2BodyGroup.query.all()
    edit_form.tags.query = Tag.query.all()

    package_formats = [("vpk", "VPK")]
    visibilities = [("Pu", "Public"), ("Pr", "Unlisted"), ("H", "Hidden")]

    edit_form.package_format.choices = package_formats
    edit_form.visibility.choices = visibilities

    if edit_form.workshop_id.data == "":
        edit_form.workshop_id.data = None

    if edit_form.validate_on_submit():
        valid = True
        mod.pretty_name = edit_form.pretty_name.data
        mod.description = edit_form.description.data
        workshop_id = edit_form.workshop_id.data
        if workshop_id:
            from re import match
            try:
                if match(
                        "http[s]?:\/\/(www\.)?steamcommunity\.com\/sharedfiles\/filedetails\/",
                        workshop_id):
                    from urlparse import urlparse, parse_qs
                    workshop_id = parse_qs(
                        urlparse(workshop_id).query).get("id")[0]
                    int(workshop_id)
                elif not int(workshop_id) > 0:
                    valid = False
                    edit_form.workshop_id.errors.append(
                        "Not a valid workshop ID.")
                    workshop_id = None
            except (ValueError, TypeError):
                valid = False
                edit_form.workshop_id.errors.append("Not a valid workshop ID.")
                workshop_id = None
            mod.workshop_id = workshop_id
        if not workshop_id or workshop_id == "":
            mod.workshop_id = None

        mod.package_format = edit_form.package_format.data
        mod.visibility = edit_form.visibility.data

        mod.defindex = edit_form.defindex.data
        if not mod.defindex.isnumeric():
            mod.defindex = None

        mod.hide_downloads = edit_form.hide_downloads.data

        if mod.hide_downloads and not mod.defindex:
            mod.hide_downloads = False
            flash(
                "If the item is not officially in-game, please simply change the item visibility to hidden to remove downloads.",
                "danger")

        mod.bodygroups = []
        mod.equip_regions = []

        for bodygroup in edit_form.bodygroups.data:
            mod.bodygroups.append(TF2BodyGroup.query.get(bodygroup))

        for equip_region in edit_form.equip_regions.data:
            mod.equip_regions.append(TF2EquipRegion.query.get(equip_region))

        for tag in edit_form.tags.data:
            mod.tags.append(Tag.query.get(tag))

        authors_to_add = []
        for i, author in enumerate(edit_form.authors):
            authors_to_add.append((i, author.author.data))

        author_profiles = []
        for i, add_author in authors_to_add:
            if add_author:
                user_author_record = new_user(add_author)

                if isinstance(user_author_record, str):
                    edit_form.authors.entries[i].author.errors.append(
                        user_author_record)
                    valid = False
                else:
                    author_profiles.append(user_author_record)

        if not current_user.is_admin() and current_user not in author_profiles:
            edit_form.authors.errors.append(
                "You may not remove yourself as an author.")
            valid = False

        author_profiles = remove_duplicates(author_profiles)

        if valid:
            for i in range(0, len(mod.authors)):
                mod.authors.pop()
            for i, author_profile in enumerate(author_profiles):
                mod_author = ModAuthor(mod_id=mod.id,
                                       user_id=author_profile.account_id,
                                       order=i)
                db.session.add(mod_author)
            db.session.add(mod)
            db.session.commit()
            flash("Save successful.", "success")
            return redirect(url_for("mods.page", mod_id=mod.id))

    classes = [_class for _class in mod.class_model]

    edit_form.pretty_name.data = mod.pretty_name
    edit_form.workshop_id.data = mod.workshop_id
    edit_form.description.data = mod.description
    for i, author in enumerate(mod.authors):
        edit_form.authors[i].author.data = author.perma_profile_url
    edit_form.equip_regions.data = [
        equip_region for equip_region in mod.equip_regions
    ]
    edit_form.bodygroups.data = [bodygroup for bodygroup in mod.bodygroups]
    edit_form.tags.data = [tag for tag in mod.tags]
    edit_form.package_format.data = mod.package_format
    edit_form.visibility.data = mod.visibility
    edit_form.hide_downloads.data = mod.hide_downloads
    edit_form.defindex.data = mod.defindex
    if new_item:
        edit_form.visibility.data = "Pu"
        edit_form.publish.label.text += " and Publish!"

    classes_array = json.dumps(classes)

    count = item_search(
        classes=classes,
        bodygroups=[bodygroup.bodygroup for bodygroup in mod.bodygroups],
        equip_regions=[
            equip_region.equip_region for equip_region in mod.equip_regions
        ]).count()
    """if request.method == 'POST' and 'mod_image' in request.files:
        try:
            filename = modimages.save(request.files['mod_image'])
            print filename
        except UploadNotAllowed:
            flash("Only images can be uploaded.", "danger")
        <form method=POST enctype=multipart/form-data>
            <input type=file name=mod_image>
            <input type="submit" value="Submit">
        </form>"""
    return render_template('mods/edit.html',
                           mod=mod,
                           edit_form=edit_form,
                           classes=classes_array,
                           count=count,
                           title=u"Editing {}".format(mod.pretty_name))
Exemplo n.º 52
0
 def decorated_view(*args, **kwargs):
     if current_user.is_admin():
         return fn(*args, **kwargs)
     else:
         abort(403)
Exemplo n.º 53
0
def conflict_resolve(conf_id):
    """
    Renders conflict resolve page.
    """
    conflict = Conflict.query.get(conf_id)
    form = ResolveConflict(formdata=request.form, obj=conflict)
    if current_user.is_admin():
        form.resolved_by.choices = [
            ("Not resolved yet", "Not resolved yet"),
            ("Order did not come", "Order did not come"),
            ("Order come but someone ate it", "Order come but someone ate it"),
        ]
        info = [
            "Order did not come -- means that the order cost will be "
            "changed to 0 and there will be additional description in "
            "the order",
            "Order come but someone ate it -- does not change anything.",
            "Not resolved yet -- does not change anything"
        ]
    elif current_user.username == conflict.user_connected:
        form.resolved_by.choices = [
            ("I did not eat your lunch", "I did not eat your lunch"),
            ("I'm sorry, I ate your meal", "I'm sorry, I ate your meal"),
        ]
        info = [
            "I'm sorry, I ate your meal -- means that the order will be "
            "asinged to you.",
            "I did not eat your lunch -- does not change anything"
        ]
    else:
        flash("You cannot resolve conflicts by yourself")
        return redirect('conflicts')

    if request.method == 'POST' and form.validate():
        conflict.resolved = (request.form.get("resolved") == "y")
        conflict.resolved_by = request.form["resolved_by"]
        conflict.notes = request.form.get("notes")
        msg = Message(
            'Lunch app conflict update',
            recipients=[conflict.created_by_user],
        )
        if conflict.resolved_by == "Order did not come":
            order = Order.query.get(conflict.order_connected)
            order.cost = 0
            order.description = "ORDER DID NOT COME\n" + order.description
            msg.body = "The order \n{}\n did not come so it cost was changed" \
                       "to 0 pln and it got properly described on your list " \
                       "of orders.".format(order.description)
        elif conflict.resolved_by == "I'm sorry, I ate your meal":
            conflict.resolved = True
            order = Order.query.get(conflict.order_connected)
            order.user_name = current_user.username
            msg.body = "{} is sorry he ate Your meal the order is now" \
                       "assigned to him/her".format(conflict.user_connected)
        else:
            url = server_url() + url_for("conflict_resolve", conf_id=conf_id)
            msg.body = "Your conflict was updated check out the changes " \
                       "here: \n {}".format(url)
        mail.send(msg)
        db.session.commit()
        flash('Conflict updated')
        return redirect('conflicts')
    return render_template("conflict_resolve.html", form=form, info=info)
Exemplo n.º 54
0
 def decorated_view(*args, **kwargs):
     if not current_user or not current_user.is_admin():
         return current_app.login_manager.unauthorized()
     return func(*args, **kwargs)
Exemplo n.º 55
0
def check_edit_permissions(mod):
    check_mod_permissions(mod)
    if current_user not in mod.authors and not current_user.is_admin():
        abort(403)
Exemplo n.º 56
0
def package(mod_id, defindex):
    mod_package = ModPackage.query.filter_by(mod_id=mod_id,
                                             defindex=defindex).first()
    mod = Mod.query.get_or_404(mod_id)
    check_mod_permissions(mod)
    if mod.hide_downloads:
        abort(404)
    replacement = TF2Item.query.filter_by(defindex=defindex,
                                          inactive=False).first()
    if mod and replacement:
        if not current_user.is_admin():
            twenty_four_hours_ago = datetime.datetime.utcnow(
            ) - datetime.timedelta(hours=24)
            downloads_by_mod = PackageDownload.query.filter_by(user=current_user)\
                .filter(PackageDownload.downloaded >= twenty_four_hours_ago)\
                .outerjoin(ModPackage)\
                .filter(ModPackage.mod_id == mod_id)
            if downloads_by_mod.count() >= 15:
                flash(
                    u"Download limit for {} reached. Please try again in 24 hours."
                    .format(mod.pretty_name), "danger")
                return redirect(url_for("mods.page", mod_id=mod_id))
            downloads_by_replacement = downloads_by_mod.filter(
                ModPackage.defindex == defindex)
            if downloads_by_replacement.count() >= 2:
                flash(
                    u"Download limit for {} replacement reached. Please try again in 24 hours."
                    .format(replacement.item_name), "danger")
                return redirect(url_for("mods.page", mod_id=mod_id))
        if not mod_package:
            filename = package_mod_to_item(mod, replacement)
            long_date = False
            if datetime.datetime.utcnow() < mod.uploaded + datetime.timedelta(
                    weeks=4):
                long_date = True
            mod_package = ModPackage(mod.id, replacement.defindex, filename,
                                     long_date)
            db.session.add(mod_package)
            db.session.commit()
        elif datetime.datetime.utcnow() > mod_package.expire_date:
            mod = mod_package.mod
            replacement = mod_package.replacement
            long_date = False
            if datetime.datetime.utcnow() < mod.uploaded + datetime.timedelta(
                    weeks=4):
                long_date = True
            filename = package_mod_to_item(mod, replacement)
            mod_package.filename = filename
            mod_package.update_expire(long_date)
            mod_package.deleted = False
            db.session.add(mod_package)
            db.session.commit()
        else:
            filename = mod_package.filename
        download_record = PackageDownload(mod_package.id,
                                          current_user.account_id)
        db.session.add(download_record)
        db.session.commit()
        return send_from_directory(os.path.abspath(
            os.path.join(current_app.config['OUTPUT_FOLDER_LOCATION'],
                         str(mod.id))),
                                   filename,
                                   as_attachment=True)
    else:
        abort(404)
Exemplo n.º 57
0
 def is_accessible(self):
     # print current_user.is_admin()
     # print current_user.is_authenticated()
     return current_user.is_admin()
Exemplo n.º 58
0
 def decorated_view(*args, **kwargs):
     print('Inside decorated view.')
     if not current_user.is_admin():  # Where have we defined current_user
         return abort(403)
     return func(*args, **kwargs)
Exemplo n.º 59
0
 def is_accessible(self):
     return current_user.is_authenticated() and current_user.is_admin()
Exemplo n.º 60
0
 def validate_vm_quota(form, field):
     if (not current_user.is_admin()) and current_user.vm_quota != int(
             field.data):
         raise ValidationError(_("Only admin user can update vm quota."))