Python flask_login.current_user.is_admin() Examples

The following are 30 code examples of flask_login.current_user.is_admin(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_login.current_user , or try the search function .
Example #1
Source File: server.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def configure_authentication(self):
        @self.auth.verify_password
        def verify_password(username, password):
            user = app.authenticate_user(name=username, password=password)
            if user:
                request_type = f"{request.method.lower()}_requests"
                endpoint = "/".join(request.path.split("/")[:3])
                authorized_endpoint = endpoint in getattr(user, request_type)
                if user.is_admin or authorized_endpoint:
                    login_user(user)
                    return True
                g.status = 403
            else:
                g.status = 401

        @self.auth.get_password
        def get_password(username):
            return getattr(db.fetch("user", name=username), "password", False)

        @self.auth.error_handler
        def unauthorized():
            message = f"{'Wrong' if g.status == 401 else 'Insufficient'} credentials"
            return make_response(jsonify({"message": message}), g.status) 
Example #2
Source File: admin.py    From ok with Apache License 2.0 6 votes vote down vote up
def clients():
    courses, current_course = get_courses()
    clients = Client.query.order_by(Client.active).all()
    my_clients = [client for client in clients if client.user_id == current_user.id]
    form = forms.ClientForm(client_secret=utils.generate_secret_key())
    if form.validate_on_submit():
        client = Client(
                user=current_user,
                active=True if current_user.is_admin else False)
        form.populate_obj(client)
        db.session.add(client)
        db.session.commit()

        flash('OAuth client "{}" added'.format(client.name), "success")
        return redirect(url_for(".clients"))

    return render_template('staff/clients.html',
            clients=clients,
            my_clients=my_clients,
            form=form,
            courses=courses) 
Example #3
Source File: server.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def monitor_requests(function):
        @wraps(function)
        def decorated_function(*args, **kwargs):
            if not current_user.is_authenticated:
                client_address = request.environ.get(
                    "HTTP_X_FORWARDED_FOR", request.environ["REMOTE_ADDR"]
                )
                app.log(
                    "warning",
                    (
                        f"Unauthorized {request.method} request from "
                        f"'{client_address}' calling the endpoint '{request.url}'"
                    ),
                )
                return redirect(url_for("blueprint.route", page="login"))
            else:
                if (
                    not current_user.is_admin
                    and request.method == "GET"
                    and request.path not in current_user.get_requests
                ):
                    return render_template("error.html", error=403), 403
                return function(*args, **kwargs)

        return decorated_function 
Example #4
Source File: views.py    From MegaQC with GNU General Public License v3.0 6 votes vote down vote up
def register():
    """
    Register new user.
    """
    form = RegisterForm(request.form)
    if form.validate_on_submit():
        user_cnt = db.session.query(User).count()
        u = User.create(
            username=form.username.data,
            email=form.email.data,
            password=form.password.data,
            first_name=form.first_name.data,
            last_name=form.last_name.data,
            active=True,
            is_admin=True if user_cnt == 0 else False,
        )
        flash("Thanks for registering! You're now logged in.", "success")
        login_user(u)
        return redirect(url_for("public.home"))
    else:
        flash_errors(form)
    return render_template("public/register.html", form=form) 
Example #5
Source File: admin.py    From ok with Apache License 2.0 6 votes vote down vote up
def is_oauth_client_owner(oauth_client_id_arg):
    """ A decorator for OAuth client management routes to ensure the user owns
        the OAuth client or is an admin."""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if current_user.is_authenticated:
                if current_user.is_admin:
                    return func(*args, **kwargs)
                oauth_client_id = kwargs[oauth_client_id_arg]
                clients = Client.query.filter_by(user_id=current_user.id)
                if clients.count() > 0:
                    if oauth_client_id in [c.client_id for c in clients]:
                        return func(*args, **kwargs)
            flash("You do not have access to this OAuth client", "warning")
            return redirect(url_for("admin.clients"))
        return login_required(wrapper)
    return decorator 
Example #6
Source File: views.py    From dribdat with MIT License 6 votes vote down vote up
def project_edit(project_id):
    project = Project.query.filter_by(id=project_id).first_or_404()
    event = project.event
    starred = IsProjectStarred(project, current_user)
    allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin)
    if not allow_edit:
        flash('You do not have access to edit this project.', 'warning')
        return project_action(project_id, None)
    form = ProjectForm(obj=project, next=request.args.get('next'))
    form.category_id.choices = [(c.id, c.name) for c in project.categories_all()]
    form.category_id.choices.insert(0, (-1, ''))
    if form.validate_on_submit():
        del form.id
        form.populate_obj(project)
        project.update()
        db.session.add(project)
        db.session.commit()
        cache.clear()
        flash('Project updated.', 'success')
        project_action(project_id, 'update', False)
        return redirect(url_for('public.project', project_id=project.id))
    return render_template('public/projectedit.html', current_event=event, project=project, form=form) 
Example #7
Source File: views.py    From dribdat with MIT License 6 votes vote down vote up
def project_post(project_id):
    project = Project.query.filter_by(id=project_id).first_or_404()
    event = project.event
    starred = IsProjectStarred(project, current_user)
    allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin)
    if not allow_edit:
        flash('You do not have access to edit this project.', 'warning')
        return project_action(project_id, None)
    form = ProjectPost(obj=project, next=request.args.get('next'))
    form.progress.choices = projectProgressList(event.has_started or event.has_finished)
    if not form.note.data:
        form.note.data = "---\n`%s` " % datetime.utcnow().strftime("%d.%m.%Y %H:%M")
    if form.validate_on_submit():
        del form.id
        form.populate_obj(project)
        project.longtext += "\n\n" + form.note.data
        project.update()
        db.session.add(project)
        db.session.commit()
        cache.clear()
        flash('Project updated.', 'success')
        project_action(project_id, 'update', False)
        return redirect(url_for('public.project', project_id=project.id))
    return render_template('public/projectpost.html', current_event=event, project=project, form=form) 
Example #8
Source File: admin.py    From c3bottles with MIT License 6 votes vote down vote up
def create_user():
    form = UserCreateForm()
    if not form.validate_on_submit():
        abort(400)
    if User.get(form.username.data) is not None:
        flash({
            "class": "danger",
            "text": lazy_gettext("A user with this name already exists")
        })
        return redirect(url_for("admin.index"))
    else:
        user = User(
            form.username.data, form.password.data, form.can_visit.data,
            form.can_edit.data, form.is_admin.data, False
        )
        db.session.add(user)
        db.session.commit()
        flash({
            "class": "success",
            "text": lazy_gettext("The new user has been created successfully.")
        })
        return redirect(url_for("admin.index")) 
Example #9
Source File: controllers.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def activate_case(store, institute_obj, case_obj, current_user):
    """ Activate case when visited for the first time.

        Args:
            store(adapter.MongoAdapter)
            institute_obj(dict) a scout institutet object
            case_obj(dict) a scout case object
            current_user(UserMixin): a scout user
    """

    # update status of case if visited for the first time
    if case_obj["status"] == "inactive" and not current_user.is_admin:
        flash("You just activated this case!", "info")

        user_obj = store.user(current_user.email)
        case_link = url_for(
            "cases.case", institute_id=institute_obj["_id"], case_name=case_obj["display_name"],
        )
        store.update_status(institute_obj, case_obj, user_obj, "active", case_link) 
Example #10
Source File: api.py    From ok with Apache License 2.0 6 votes vote down vote up
def get(self, user, email=None):
        target = self.model.lookup(email)

        if not email or email.lower() == user.email.lower():
            # Get the current user
            return user

        if not target and user.is_admin:
            restful.abort(404)
        elif not target:
            restful.abort(403)

        if user.is_admin:
            return target

        restful.abort(403) 
Example #11
Source File: views.py    From dribdat with MIT License 6 votes vote down vote up
def project_action(project_id, of_type, as_view=True, then_redirect=False):
    project = Project.query.filter_by(id=project_id).first_or_404()
    event = project.event
    if of_type is not None:
        ProjectActivity(project, of_type, current_user)
    if not as_view:
        return True
    starred = IsProjectStarred(project, current_user)
    allow_edit = starred or (not current_user.is_anonymous and current_user.is_admin)
    allow_edit = allow_edit and not event.lock_editing
    project_stars = GetProjectTeam(project)
    latest_activity = project.latest_activity()
    if then_redirect:
        return redirect(url_for('public.project', project_id=project.id))
    return render_template('public/project.html', current_event=event, project=project,
        project_starred=starred, project_stars=project_stars,
        allow_edit=allow_edit, latest_activity=latest_activity) 
Example #12
Source File: api.py    From ok with Apache License 2.0 6 votes vote down vote up
def get(self, user, key=None):
        if key is None:
            restful.abort(405)
        try:
            bid = decode_id(key)
        except (ValueError, TypeError):
            restful.abort(404)

        backup = self.model.query.filter_by(id=bid).first()
        if not backup:
            if user.is_admin:
                return restful.abort(404)
            return restful.abort(403)
        if not self.model.can(backup, user, 'view'):
            return restful.abort(403)
        backup.group = [models.User.get_by_id(uid) for uid in backup.owners()]
        return backup 
Example #13
Source File: admin.py    From ok with Apache License 2.0 5 votes vote down vote up
def get_courses(cid=None):
    if current_user.is_authenticated and current_user.is_admin:
        courses = (Course.query.order_by(Course.created.desc())
                         .all())
    else:
        enrollments = current_user.enrollments(roles=STAFF_ROLES)
        courses = [e.course for e in enrollments]
    if not cid:
        return courses, []

    matching_courses = [c for c in courses if c.id == cid]
    if len(matching_courses) == 0:
        abort(401)
    current_course = matching_courses[0]
    return courses, current_course 
Example #14
Source File: admin.py    From ok with Apache License 2.0 5 votes vote down vote up
def client(client_id):
    courses, current_course = get_courses()

    client = Client.query.get(client_id)
    # Show the client owner's email in edit form when owner exists
    client.owner = client.user.email if client.user else ""
    form = forms.EditClientForm(obj=client)
    # Hide the active field and scopes if not an admin
    if not current_user.is_admin:
        del form.active
        del form.default_scopes
    if form.validate_on_submit():
        # Be careful not to overwrite user data
        if not form.user_id.data or not form.user.data:
            del form.user_id, form.user
        form.populate_obj(client)
        if form.roll_secret.data:
            client.client_secret = utils.generate_secret_key()
            flash_msg = ('OAuth client "{}" updated with new secret: "{}"'
                         .format(client.name, client.client_secret))
        else:
            flash_msg = ('OAuth client "{}" updated without changing the secret'
                         .format(client.name))
        db.session.commit()
        flash(flash_msg, "success")
        return redirect(url_for(".clients"))
    return render_template('staff/edit_client.html', client=client, form=form, courses=courses)

################
# Student View #
################ 
Example #15
Source File: queue.py    From ok with Apache License 2.0 5 votes vote down vote up
def authenticate(*args, **kwargs):
    if not current_user.is_authenticated:
        return current_app.login_manager.unauthorized()
    if not current_user.is_admin:
        abort(403) 
Example #16
Source File: admin.py    From ok with Apache License 2.0 5 votes vote down vote up
def is_staff(course_arg=None):
    """ A decorator for routes to ensure that user is a member of
    the course staff.

    Usage:
    @is_staff() - A staff member for any course
    @is_staff(course_arg=1) A staff member for the course with id 1
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if current_user.is_authenticated:
                if current_user.is_admin:
                    return func(*args, **kwargs)
                roles = current_user.enrollments(roles=STAFF_ROLES)
                if len(roles) > 0:
                    if course_arg:
                        course = kwargs[course_arg]
                        if course in [r.course.id for r in roles]:
                            return func(*args, **kwargs)
                    else:
                        return func(*args, **kwargs)
            else:
                return redirect(url_for("student.index"))
            flash("You are not on the course staff", "warning")
            return redirect(url_for("student.index"))
        return login_required(wrapper)
    return decorator 
Example #17
Source File: admin.py    From ok with Apache License 2.0 5 votes vote down vote up
def is_admin():
    """ A decorator for routes to ensure the user is an admin."""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if current_user.is_authenticated and current_user.is_admin:
                return func(*args, **kwargs)
            else:
                flash("You are not an administrator", "warning")
                return redirect(url_for("admin.index"))
        return login_required(wrapper)
    return decorator 
Example #18
Source File: __init__.py    From OctoPrint-Pushover with GNU General Public License v3.0 5 votes vote down vote up
def on_settings_load(self):
		data = octoprint.plugin.SettingsPlugin.on_settings_load(self)

		# only return our restricted settings to admin users - this is only needed for OctoPrint <= 1.2.16
		restricted = ("default_token", "token", "user_key")
		for r in restricted:
			if r in data and (current_user is None or current_user.is_anonymous() or not current_user.is_admin()):
				data[r] = None

		return data 
Example #19
Source File: auth.py    From Python-Microservices-Development with MIT License 5 votes vote down vote up
def admin_required(func):
    @functools.wraps(func)
    def _admin_required(*args, **kw):
        admin = current_user.is_authenticated and current_user.is_admin
        if not admin:
            return login_manager.unauthorized()
        return func(*args, **kw)
    return _admin_required 
Example #20
Source File: api.py    From ok with Apache License 2.0 5 votes vote down vote up
def post(self, user, backup_id):
        backup = models.Backup.query.get(backup_id)
        if not backup:
            if user.is_admin:
                restful.abort(404)
            else:
                restful.abort(403)
        if not models.Backup.can(backup, user, "view"):
            restful.abort(403)
        if not self.model.can(None, user, "create"):
            restful.abort(403)

        return self.schema.store_comment(user, backup) 
Example #21
Source File: student.py    From ok with Apache License 2.0 5 votes vote down vote up
def check_enrollment(course):
    enrolled = current_user.is_enrolled(course.id)
    if not enrolled and not current_user.is_admin:
        flash("You have not been added to this course on OK", "warning") 
Example #22
Source File: main.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def on_identity_loaded(sender, identity):
    """Helper for flask-principal."""
    # Set the identity user object
    identity.user = current_user

    # Add the UserNeed to the identity
    if hasattr(current_user, "id"):
        identity.provides.add(UserNeed(current_user.id))

    try:
        if current_user.is_admin:
            identity.provides.add(RoleNeed("admin"))
    except AttributeError:
        pass  # Definitely not an admin 
Example #23
Source File: views.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def change_club_details(club_id):
    club = Club.query.filter_by(id=club_id).first()
    if club is None:
        abort(404)
    if (current_user.id != club.admin_id) and (current_user.is_admin() is False):
        print(current_user.is_admin())
        abort(403)
    form = EditClubForm()
    if form.validate_on_submit():
        club.name=form.name.data
        club.img_link=form.img_link.data
        club.website=form.website.data
        print(form.owner.data)
        club.admin_id=form.owner.data.id
        club.description=form.desc.data
        club.recruitment_info=form.recruitment_info.data
        club.categories = form.categories.data
        club.is_confirmed = bool(form.is_confirmed.data)
        db.session.add(club)
        db.session.commit()
        flash('Club successfully edited', 'form-success')
    form.name.data=club.name
    form.img_link.data=club.img_link
    form.website.data=club.website
    form.recruitment_info.data=club.recruitment_info
    form.owner.data = User.query.get(club.admin_id) if club.admin_id else None
    form.categories.data = club.categories
    form.desc.data = club.description
    form.is_confirmed.data = str(club.is_confirmed)
    return render_template('club/manage_club.html', club=club, form=form) 
Example #24
Source File: views.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def new_club():
    """Create a new club."""
    form = NewClubForm()
    if form.validate_on_submit():
        club = Club(
            name=form.name.data,
            img_link=form.img_link.data,
            website=form.website.data,
            description=form.desc.data,
            recruitment_info=form.recruitment_info.data,
            is_confirmed=current_user.is_admin(),
            categories=form.categories.data)
        db.session.add(club)
        db.session.commit()
        link = url_for(
            'club.change_club_details', club_id=club.id, _external=True)
        if (current_user.is_admin() == False):
            for r in Role.query.filter_by(name='Administrator').all():
                for a in r.users:
                    get_queue().enqueue(
                        send_email,
                        recipient=a.email,
                        subject='A new club was suggested by {}'.format(
                            current_user.first_name),
                        template='club/email/suggested_club',
                        club=club,
                        link=link)
        action = 'created' if current_user.is_admin() else 'suggested'
        flash('Club {} successfully {}'.format(club.name, action),
              'form-success')
    return render_template('club/new_club.html', form=form) 
Example #25
Source File: utils.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def user_institutes(store, login_user):
    """Preprocess institute objects."""
    if login_user.is_admin:
        institutes = store.institutes()
    else:
        institutes = [store.institute(inst_id) for inst_id in login_user.institutes]

    return institutes 
Example #26
Source File: utils.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def institute_and_case(store, institute_id, case_name=None):
    """Fetch insitiute and case objects."""
    institute_obj = store.institute(institute_id)
    if institute_obj is None:
        flash("Can't find institute: {}".format(institute_id), "warning")
        return abort(404)

    if case_name:
        case_obj = store.case(institute_id=institute_id, display_name=case_name)
        if case_obj is None:
            return abort(404)

    # validate that user has access to the institute

    if not current_user.is_admin:
        if institute_id not in current_user.institutes:
            if not case_name or not any(
                inst_id in case_obj["collaborators"] for inst_id in current_user.institutes
            ):
                # you don't have access!!
                flash("You don't have acccess to: {}".format(institute_id), "danger")
                return abort(403)

    # you have access!
    if case_name:
        return institute_obj, case_obj
    return institute_obj 
Example #27
Source File: admin.py    From c3bottles with MIT License 5 votes vote down vote up
def user_permissions():
    form = PermissionsForm()
    if not form.validate_on_submit():
        abort(400)
    user = User.get_or_404(form.user_id.data)
    user.can_visit = form.can_visit.data
    user.can_edit = form.can_edit.data
    user.is_admin = form.is_admin.data
    db.session.add(user)
    db.session.commit()
    flash({
        "class": "success",
        "text": lazy_gettext("The user's permissions have been updated successfully.")
    })
    return redirect(url_for("admin.index")) 
Example #28
Source File: admin.py    From c3bottles with MIT License 5 votes vote down vote up
def handle_404(e):
    if request.path.startswith(bp.url_prefix) and not current_user.is_admin:
        return unauthorized(e)
    else:
        return not_found(e) 
Example #29
Source File: __init__.py    From c3bottles with MIT License 5 votes vote down vote up
def needs_admin(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if current_user.is_admin:
            return func(*args, **kwargs)
        else:
            abort(401)
    return decorated_view 
Example #30
Source File: routes.py    From flask-pycon2014 with MIT License 5 votes vote down vote up
def moderate_admin():
    if not current_user.is_admin:
        abort(403)
    comments = Comment.for_moderation().order_by(Comment.timestamp.asc())
    return render_template('talks/moderate.html', comments=comments)