Python flask_login.current_user.name() Examples

The following are 30 code examples of flask_login.current_user.name(). 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: service_settings.py    From notifications-admin with MIT License 6 votes vote down vote up
def service_switch_count_as_live(service_id):

    form = ServiceOnOffSettingForm(
        name="Count in list of live services",
        enabled=current_service.count_as_live,
        truthy='Yes',
        falsey='No',
    )

    if form.validate_on_submit():
        current_service.update_count_as_live(form.enabled.data)
        return redirect(url_for('.service_settings', service_id=service_id))

    return render_template(
        'views/service-settings/set-service-setting.html',
        title="Count in list of live services",
        form=form,
    ) 
Example #2
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def audit_work_cancel(id):
    """
    Cancel the work order by auditor.
    :param id:
    :return:
    """
    work = Work.query.get(id)
    work.status = 6
    work.finish_time = datetime.now()
    db.session.add(work)
    db.session.commit()

    if current_app.config['MAIL_ON_OFF'] == 'ON':
        dev = User.query.filter(User.name == work.dev_name).first()
        mail_content = "<p>Work Sheet:" + work.name + " is cancelled by auditor. Please contact with your auditor.</p>"
        send_mail.delay('【inception_mysql】Work Sheet Cancelled', mail_content, dev.email)

    return redirect(url_for('.audit_work_dealt')) 
Example #3
Source File: test_admin.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def test_edit_user(db, client):
    new_password = random_string()
    new_email = '{}foo'.format(EMAIL)
    new_role = UserRole.security_team
    resp = client.post(url_for('tracker.edit_user', username=USERNAME), follow_redirects=True,
                       data=dict(username=USERNAME, email=new_email, password=new_password,
                       role=new_role.name, active=True))
    assert resp.status_code == 200

    resp = client.post(url_for('tracker.logout'), follow_redirects=True)
    assert_not_logged_in(resp)

    resp = client.post(url_for('tracker.login'), follow_redirects=True,
                       data={'username': USERNAME, 'password': new_password})
    assert_logged_in(resp)
    assert USERNAME == current_user.name
    assert new_email == current_user.email
    assert new_role == current_user.role 
Example #4
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def audit_work_reject(id):
    """
    Reject the work order by auditor.
    :param id:
    :return:
    """
    work = Work.query.get(id)
    work.status = 7
    work.finish_time = datetime.now()
    db.session.add(work)
    db.session.commit()

    if current_app.config['MAIL_ON_OFF'] == 'ON':
        dev = User.query.filter(User.name == work.dev_name).first()
        mail_content = "<p>Work Sheet:" + work.name + " is rejected by auditor. Please modify it.</p>"
        send_mail.delay('【inception_mysql】Work Sheet Rejected', mail_content, dev.email)

    return redirect(url_for('.audit_work_dealt')) 
Example #5
Source File: service_settings.py    From notifications-admin with MIT License 6 votes vote down vote up
def service_set_sms_prefix(service_id):

    form = SMSPrefixForm(enabled=(
        'on' if current_service.prefix_sms else 'off'
    ))

    form.enabled.label.text = 'Start all text messages with ‘{}:’'.format(current_service.name)

    if form.validate_on_submit():
        current_service.update(
            prefix_sms=(form.enabled.data == 'on')
        )
        return redirect(url_for('.service_settings', service_id=service_id))

    return render_template(
        'views/service-settings/sms-prefix.html',
        form=form
    ) 
Example #6
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def audit_resource_cancel(id):
    """
    Cancelled the application from dev.
    :param id:
    :return:
    """
    resource = Dbapply.query.get(id)
    resource.status = 3
    resource.finish_time = datetime.now()

    db.session.add(resource)
    db.session.commit()

    if current_app.config['MAIL_ON_OFF'] == 'ON':
        dev = User.query.filter(User.name == resource.dev_name).first()
        mail_content = "<p>Proposer:" + resource.dev_name + "</p>" + "<p>Db instance's name:" + resource.db_name + \
                       "</p>" + "<p>Your db instance request is disagreed.</p>"
        send_mail.delay('【inception_mysql】Db instance request failure', mail_content, dev.email)

    return redirect(url_for('.audit_resource_dealt')) 
Example #7
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def audit_resource_alloc(id):
    """
    Alloc db instances to dev.
    :param id:
    :return:
    """
    resource = Dbapply.query.get(id)
    user = User.query.filter(User.name == resource.dev_name).first()
    db_config = Dbconfig.query.filter(Dbconfig.name == resource.db_name).first()
    user.dbs.append(db_config)
    resource.finish_time = datetime.now()
    resource.status = 0

    db.session.add(resource)
    db.session.commit()

    if current_app.config['MAIL_ON_OFF'] == 'ON':
        dev = User.query.filter(User.name == resource.dev_name).first()
        mail_content = "<p>Proposer:" + resource.dev_name + "</p>" + "<p>Db instance's name:" + resource.db_name + \
                       "</p>" + "<p>Your db instance request has been passed.</p>"
        send_mail.delay('【inception_mysql】Db instance request passed', mail_content, dev.email)

    return redirect(url_for('.audit_resource_pending')) 
Example #8
Source File: service_settings.py    From notifications-admin with MIT License 6 votes vote down vote up
def link_service_to_organisation(service_id):

    all_organisations = organisations_client.get_organisations()

    form = LinkOrganisationsForm(
        choices=convert_dictionary_to_wtforms_choices_format(all_organisations, 'id', 'name'),
        organisations=current_service.organisation_id
    )

    if form.validate_on_submit():
        if form.organisations.data != current_service.organisation_id:
            organisations_client.update_service_organisation(
                service_id,
                form.organisations.data
            )
        return redirect(url_for('.service_settings', service_id=service_id))

    return render_template(
        'views/service-settings/link-service-to-organisation.html',
        has_organisations=all_organisations,
        form=form,
        search_form=SearchByNameForm(),
    ) 
Example #9
Source File: user_profile.py    From notifications-admin with MIT License 6 votes vote down vote up
def user_profile_disable_platform_admin_view():
    if not current_user.platform_admin and not session.get('disable_platform_admin_view'):
        abort(403)

    form = ServiceOnOffSettingForm(
        name="Signing in again clears this setting",
        enabled=not session.get('disable_platform_admin_view'),
        truthy='Yes',
        falsey='No',
    )

    if form.validate_on_submit():
        session['disable_platform_admin_view'] = not form.enabled.data
        return redirect(url_for('.user_profile'))

    return render_template(
        'views/user-profile/disable-platform-admin-view.html',
        form=form
    ) 
Example #10
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
def dev_resource_cancel(id):
    """
    Dev users cancelled the application
    :param id:
    :return:
    """
    resource = Dbapply.query.get(id)
    resource.status = 2
    resource.finish_time = datetime.now()

    db.session.add(resource)
    db.session.commit()

    if current_app.config['MAIL_ON_OFF'] == 'ON':
        auditor = User.query.filter(User.name == resource.audit_name).first()
        mail_content = "<p>Proposer:" + resource.dev_name + "</p>" + "<p>Db instance's name:" + resource.db_name + \
                       "</p>" + "<p>Dev has cancelled the application.</p>"
        send_mail.delay('【inception_mysql】Db instance application cancelled', mail_content, auditor.email)

    return redirect(url_for('.dev_resource_status')) 
Example #11
Source File: views.py    From flasky-first-edition with MIT License 6 votes vote down vote up
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user) 
Example #12
Source File: test_admin.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def test_create_user(db, client):
    role = UserRole.security_team
    resp = client.post(url_for('tracker.create_user'), follow_redirects=True,
                       data=dict(username=USERNAME, password=PASSWORD,
                                 email=EMAIL, active=True, role=role.name))
    assert resp.status_code == 200

    resp = client.post(url_for('tracker.logout'), follow_redirects=True)
    assert_not_logged_in(resp)

    resp = client.post(url_for('tracker.login'), follow_redirects=True,
                       data=dict(username=USERNAME, password=PASSWORD))
    assert_logged_in(resp)
    assert USERNAME == current_user.name
    assert EMAIL == current_user.email
    assert role == current_user.role 
Example #13
Source File: service_settings.py    From notifications-admin with MIT License 6 votes vote down vote up
def archive_service(service_id):
    if not current_service.active and (
        current_service.trial_mode or current_user.platform_admin
    ):
        abort(403)
    if request.method == 'POST':
        # We need to purge the cache for the services users as otherwise, although they will have had their permissions
        # removed in the DB, they would still have permissions in the cache to view/edit/manage this service
        cached_service_user_ids = [user.id for user in current_service.active_users]

        service_api_client.archive_service(service_id, cached_service_user_ids)
        flash(
            '‘{}’ was deleted'.format(current_service.name),
            'default_with_tick',
        )
        return redirect(url_for('.choose_account'))
    else:
        flash(
            'Are you sure you want to delete ‘{}’? There’s no way to undo this.'.format(current_service.name),
            'delete',
        )
        return service_settings(service_id) 
Example #14
Source File: user.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def validate(self):
        rv = BaseForm.validate(self)
        if not rv:
            return False

        if current_user.name in self.password.data:
            self.password.errors.append(ERROR_PASSWORD_CONTAINS_USERNAME)
            return False

        if self.password.data != self.password_repeat.data:
            self.password_repeat.errors.append(ERROR_PASSWORD_REPEAT_MISMATCHES)
            return False

        if not compare_digest(current_user.password, hash_password(self.password_current.data, current_user.salt)):
            self.password_current.errors.append(ERROR_PASSWORD_INCORRECT)
            return False

        return True 
Example #15
Source File: admin.py    From arch-security-tracker with MIT License 6 votes vote down vote up
def list_user():
    users = User.query.order_by(User.name).all()
    users = sorted(users, key=lambda u: u.name)

    if not current_user.role.is_administrator:
        masked = []
        for user in users:
            guest = Guest()
            guest.name = user.name
            guest.email = user.email
            guest.role = user.role if not user.role.is_administrator else UserRole.security_team
            guest.active = user.active
            if user.active:
                masked.append(guest)
        users = masked

    users = sorted(users, key=lambda u: u.role)
    return render_template('admin/user.html',
                           title='User list',
                           users=users) 
Example #16
Source File: views.py    From circleci-demo-python-flask with MIT License 6 votes vote down vote up
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user) 
Example #17
Source File: test_dashboard_views.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dashboard(app, user_obj, institute_obj):
    # GIVEN an initialized client
    # GIVEN a valid user and institute

    with app.test_client() as client:
        # GIVEN that the user could be logged in
        resp = client.get(url_for("auto_login"))
        assert resp.status_code == 200

        our_current_user = current_user.name
        log.debug("Current user %s", our_current_user)
        log.debug("Current user institutes {}".format(current_user.institutes))

        # WHEN accessing the dashboard page
        resp = client.get(url_for("dashboard.index", institute_id=institute_obj["internal_id"]))

        # THEN it should return a page
        assert resp.status_code == 200 
Example #18
Source File: prefs.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _store_prefs(self, key, val):
        """Store the prefs if persistent storage is enabled"""
        if bui.config['WITH_SQL'] and not bui.config['BUI_DEMO']:
            from ..ext.sql import db
            from ..models import Pref
            pref = Pref.query.filter_by(user=current_user.name, key=key).first()
            if pref:
                if val:
                    pref.value = val
                else:
                    db.session.delete(pref)
            elif val:
                pref = Pref(current_user.name, key, val)
                db.session.add(pref)
            try:
                db.session.commit()
            except:  # pragma: no cover
                db.session.rollback() 
Example #19
Source File: prefs.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self):
        """Delete prefs"""
        args = self.parser.parse_args()
        sess = session
        ret = {}
        for key in args.keys():
            temp = args.get(key)
            if temp:
                del sess[key]
                if bui.config['WITH_SQL']:
                    from ..ext.sql import db
                    from ..models import Pref
                    try:
                        Pref.query.filter_by(
                            user=current_user.name,
                            key=key
                        ).delete()
                        db.session.commit()
                    except:  # pragma: no cover
                        db.session.rollback()
            ret[key] = sess.get(key)

        return ret 
Example #20
Source File: tasks.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete(self, task_type, task_id, server=None):
        """Cancel a given task"""
        if task_type not in task_types:
            self.abort(400)
        task_obj, _ = task_types[task_type]
        task = task_obj.AsyncResult(task_id)
        user = task.result.get('user')
        dst_server = task.result.get('server')

        if (current_user.name != user or (dst_server and dst_server != server)) and \
                not current_user.acl.is_admin():
            self.abort(403, 'Unauthorized access')

        # do not remove the task from db yet since we may need to remove
        # some temporary files afterward. The "cleanup_restore" task will take
        # care of this
        task.revoke()
        return '', 201 
Example #21
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def save_positions(self, workflow_id, **kwargs):
        now, old_position = self.get_time(), None
        workflow = db.fetch("workflow", allow_none=True, id=workflow_id, rbac="edit")
        if not workflow:
            return
        for id, position in kwargs.items():
            new_position = [position["x"], position["y"]]
            if "-" not in id:
                service = db.fetch("service", id=id, rbac="edit")
                old_position = service.positions.get(workflow.name)
                service.positions[workflow.name] = new_position
            elif id in workflow.labels:
                old_position = workflow.labels[id].pop("positions")
                workflow.labels[id] = {"positions": new_position, **workflow.labels[id]}
            if new_position != old_position:
                workflow.last_modified = now
        return now 
Example #22
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def run_service(self, path, **kwargs):
        service_id = str(path).split(">")[-1]
        for property in ("user", "csrf_token", "form_type"):
            kwargs.pop(property, None)
        kwargs["creator"] = getattr(current_user, "name", "")
        service = db.fetch("service", id=service_id, rbac="run")
        kwargs["runtime"] = runtime = self.get_time()
        if kwargs.get("asynchronous", True):
            Thread(target=self.run, args=(service_id,), kwargs=kwargs).start()
        else:
            service.run(runtime=runtime)
        return {
            "service": service.serialized,
            "runtime": runtime,
            "user": current_user.name,
        } 
Example #23
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def copy_service_in_workflow(self, workflow_id, **kwargs):
        service_sets = list(set(kwargs["services"].split(",")))
        service_instances = db.objectify("service", service_sets)
        workflow = db.fetch("workflow", id=workflow_id)
        services, errors = [], []
        if kwargs["mode"] == "shallow":
            for service in service_instances:
                if not service.shared:
                    errors.append(f"'{service.name}' is not a shared service.")
                elif service in workflow.services:
                    errors.append(f"This workflow already contains '{service.name}'.")
        if errors:
            return {"alert": errors}
        for service in service_instances:
            if kwargs["mode"] == "deep":
                service = service.duplicate(workflow)
            else:
                workflow.services.append(service)
            services.append(service)
        workflow.last_modified = self.get_time()
        db.session.commit()
        return {
            "services": [service.serialized for service in services],
            "update_time": workflow.last_modified,
        } 
Example #24
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def calendar_init(self, type):
        results = {}
        for instance in db.fetch_all(type):
            if getattr(instance, "workflow", None):
                continue
            date = getattr(instance, "next_run_time" if type == "task" else "runtime")
            python_month = search(r".*-(\d{2})-.*", date)
            if not python_month:
                continue
            month = "{:02}".format((int(python_month.group(1)) - 1) % 12)
            start = [
                int(i)
                for i in sub(
                    r"(\d+)-(\d+)-(\d+) (\d+):(\d+).*",
                    r"\1," + month + r",\3,\4,\5",
                    date,
                ).split(",")
            ]
            results[instance.name] = {"start": start, **instance.serialized}
        return results 
Example #25
Source File: tasks.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get(self, task_id, server=None):
        """Returns the generated archive"""
        task = load_all_tree.AsyncResult(task_id)
        if task.state != 'SUCCESS':
            if task.state == 'FAILURE':
                self.abort(
                    500,
                    'Unsuccessful task: {}'.format(task.result.get('error'))
                )
            self.abort(400, 'Task not processed yet: {}'.format(task.state))

        user = task.result.get('user')
        dst_server = task.result.get('server')
        resp = task.result.get('tree')

        if current_user.name != user or (dst_server and dst_server != server):
            self.abort(403, 'Unauthorized access')

        task.revoke()

        return resp 
Example #26
Source File: automation.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def add_edge(self, workflow_id, subtype, source, destination):
        workflow_edge = self.update(
            "workflow_edge",
            **{
                "name": f"{workflow_id}-{subtype}:{source}->{destination}",
                "workflow": workflow_id,
                "subtype": subtype,
                "source": source,
                "destination": destination,
            },
        )
        if "alert" in workflow_edge:
            return workflow_edge
        db.session.commit()
        now = self.get_time()
        db.fetch("workflow", id=workflow_id).last_modified = now
        return {"edge": workflow_edge, "update_time": now} 
Example #27
Source File: inventory.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def save_pool_objects(self, pool_id, **kwargs):
        pool = db.fetch("pool", id=pool_id)
        for obj_type in ("device", "link"):
            string_objects = kwargs[f"string_{obj_type}s"]
            if string_objects:
                objects = []
                for name in [obj.strip() for obj in string_objects.split(",")]:
                    obj = db.fetch(obj_type, allow_none=True, name=name)
                    if not obj:
                        return {
                            "alert": f"{obj_type.capitalize()} '{name}' does not exist."
                        }
                    if obj not in objects:
                        objects.append(obj)
            else:
                objects = db.objectify(obj_type, kwargs[f"{obj_type}s"])
            setattr(pool, f"{obj_type}_number", len(objects))
            setattr(pool, f"{obj_type}s", objects)
        pool.last_modified = self.get_time()
        return pool.serialized 
Example #28
Source File: clients.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _parse_clients_reports(self, res=None, server=None):
        if not res:
            try:
                clients = bui.client.get_all_clients(agent=server, last_attempt=False)
            except BUIserverException as e:
                self.abort(500, str(e))
            if mask.has_filters(current_user):
                clients = [x for x in clients if mask.is_client_allowed(current_user, x['name'], server)]
            return bui.client.get_clients_report(clients, server)
        if bui.config['STANDALONE']:
            ret = res
        else:
            ret = res.get(server, {})
        if mask.has_filters(current_user):
            ret['backups'] = [x for x in ret.get('backups', []) if mask.is_client_allowed(current_user, x.get('name'), server)]
            ret['clients'] = [x for x in ret.get('clients', []) if mask.is_client_allowed(current_user, x.get('name'), server)]
        return ret 
Example #29
Source File: server.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def register_plugins(self):
        for plugin_path in Path(app.settings["app"]["plugin_path"]).iterdir():
            if not Path(plugin_path / "settings.json").exists():
                continue
            try:
                with open(plugin_path / "settings.json", "r") as file:
                    settings = load(file)
                if not settings["active"]:
                    continue
                module = import_module(f"eNMS.plugins.{plugin_path.stem}")
                module.Plugin(self, app, db, **settings)
                for setup_file in ("database", "properties", "rbac"):
                    update_file(getattr(app, setup_file), settings.get(setup_file, {}))
            except Exception as exc:
                app.log("error", f"Could not load plugin '{plugin_path.stem}' ({exc})")
                continue
            app.log("info", f"Loading plugin: {settings['name']}")
        init_variable_forms(app)
        db.base.metadata.create_all(bind=db.engine) 
Example #30
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)