Python flask_login.current_user() Examples

The following are 30 code examples of flask_login.current_user(). 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 , or try the search function .
Example #1
Source File: init_session.py    From airflow with Apache License 2.0 9 votes vote down vote up
def init_logout_timeout(app):
    """Add logout user after timeout"""

    def before_request():
        _force_log_out_after = conf.getint('webserver', 'FORCE_LOG_OUT_AFTER', fallback=0)
        if _force_log_out_after > 0:
            flask.session.permanent = True
            app.permanent_session_lifetime = datetime.timedelta(minutes=_force_log_out_after)
            flask.session.modified = True
            flask.g.user = flask_login.current_user

    app.before_request(before_request) 
Example #2
Source File: oauth2.py    From flask-restplus-server-example with MIT License 6 votes vote down vote up
def _grantsetter(self, client_id, code, request, *args, **kwargs):
        # pylint: disable=method-hidden,unused-argument
        # TODO: review expiration time
        # decide the expires time yourself
        expires = datetime.utcnow() + timedelta(seconds=100)
        try:
            with db.session.begin():
                grant_instance = self._grant_class(
                    client_id=client_id,
                    code=code['code'],
                    redirect_uri=request.redirect_uri,
                    scopes=request.scopes,
                    user=current_user,
                    expires=expires
                )
                db.session.add(grant_instance)
        except sqlalchemy.exc.IntegrityError:
            log.exception("Grant-setter has failed.")
            return None
        return grant_instance 
Example #3
Source File: __init__.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def form_postprocessing(form, form_data):
    data = {**form_data.to_dict(), **{"user": current_user}}
    if request.files:
        data["file"] = request.files["file"]
    for property, field in form_properties[form_data.get("form_type")].items():
        if field["type"] in ("object-list", "multiselect", "multiselect-string"):
            value = form_data.getlist(property)
            if field["type"] == "multiselect-string":
                value = str(value)
            data[property] = value
        elif field["type"] == "object":
            data[property] = form_data.get(property)
        elif field["type"] == "field-list":
            data[property] = []
            for entry in getattr(form, property).entries:
                properties = entry.data
                properties.pop("csrf_token")
                data[property].append(properties)
        elif field["type"] == "bool":
            data[property] = property in form_data
        elif field["type"] in db.field_conversion and property in data:
            data[property] = db.field_conversion[field["type"]](form_data[property])
    return data 
Example #4
Source File: view.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def get(self, sketch_id):
        """Handles GET request to the resource.

        Args:
            sketch_id: Integer primary key for a sketch database model

        Returns:
            Views in JSON (instance of flask.wrappers.Response)
        """
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(
                HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')
        if not sketch.has_permission(current_user, 'read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN,
                  'User does not have read access controls on sketch.')
        return self.to_json(sketch.get_named_views) 
Example #5
Source File: base.py    From eNMS with GNU General Public License v3.0 6 votes vote down vote up
def update(self, type, **kwargs):
        try:
            must_be_new = kwargs.get("id") == ""
            for arg in ("name", "scoped_name"):
                if arg in kwargs:
                    kwargs[arg] = kwargs[arg].strip()
            kwargs["last_modified"] = self.get_time()
            kwargs["creator"] = kwargs["user"] = getattr(current_user, "name", "")
            instance = db.factory(type, must_be_new=must_be_new, **kwargs)
            if kwargs.get("copy"):
                db.fetch(type, id=kwargs["copy"]).duplicate(clone=instance)
            db.session.flush()
            return instance.serialized
        except db.rbac_error:
            return {"alert": "Error 403 - Operation not allowed."}
        except Exception as exc:
            db.session.rollback()
            if isinstance(exc, IntegrityError):
                return {"alert": f"There is already a {type} with the same parameters."}
            return {"alert": str(exc)} 
Example #6
Source File: evesso.py    From evesrp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _get_user_data(self):
        if not hasattr(request, '_user_data'):
            try:
                resp = self.session.get(self.domain + '/oauth/verify').json()
                current_app.logger.debug(u"SSO lookup results: {}".format(resp))
            except OAuth2Error as e:
                current_app.logger.error(u"Error verifying user data for user "
                                         u"'{}': {}".format(current_user, e))
                # The session can be bugged in some situations. Kill it to be
                # sure.
                del self.session
                raise
            try:
                char_data = {
                    'name': resp[u'CharacterName'],
                    'id': resp[u'CharacterID'],
                    'owner_hash': resp[u'CharacterOwnerHash'],
                }
                request._user_data = char_data
            except (TypeError, KeyError):
                abort(500, u"Error in receiving EVE SSO response: {}".format(
                        resp))
        return request._user_data 
Example #7
Source File: login.py    From evesrp with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def refresh_user():
    auth_methods = {am.name: am for am in current_app.auth_methods}
    user_auth_method = auth_methods[flask_login.current_user.authmethod]
    if user_auth_method.refresh(flask_login.current_user):
        current_app.logger.debug("Marking '{}' as fresh".format(
            flask_login.current_user))
        flask_login.confirm_login()
        # Call the original endpoint
        view = current_app.view_functions[request.endpoint]
        return view(**request.view_args)
    else:
        flash(login_manager.needs_refresh_message,
                category=login_manager.needs_refresh_message_category)
        original_url = url_for(request.endpoint, **request.view_args)
        return redirect(url_for('login.login', next=original_url,
                _anchor=user_auth_method.safe_name)) 
Example #8
Source File: confirm_email.py    From flask-react-spa with MIT License 6 votes vote down vote up
def confirm_email(token):
    """View function which handles a email confirmation request."""

    expired, invalid, user = confirm_email_token_status(token)

    if not user or invalid:
        invalid = True

    already_confirmed = user is not None and user.confirmed_at is not None
    expired_and_not_confirmed = expired and not already_confirmed

    if expired_and_not_confirmed:
        send_confirmation_instructions(user)

    if invalid or expired_and_not_confirmed:
        return redirect(get_url(_security.confirm_error_view))

    if confirm_user(user):
        after_this_request(_commit)

    if user != current_user:
        logout_user()
        login_user(user)

    return redirect(get_url(_security.post_confirm_view)) 
Example #9
Source File: conversation.py    From notifications-admin with MIT License 6 votes vote down vote up
def conversation_reply(
    service_id,
    notification_id,
    from_folder=None,
):
    return render_template(
        'views/templates/choose-reply.html',
        templates_and_folders=TemplateList(
            current_service,
            template_folder_id=from_folder,
            user=current_user,
            template_type='sms'
        ),
        template_folder_path=current_service.get_template_folder_path(from_folder),
        search_form=SearchByNameForm(),
        notification_id=notification_id,
        template_type='sms'
    ) 
Example #10
Source File: aggregation.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def get(self, sketch_id):
        """Handles GET request to the resource.

        Handler for /api/v1/sketches/<int:sketch_id>/aggregation/

        Args:
            sketch_id: Integer primary key for a sketch database model

        Returns:
            Views in JSON (instance of flask.wrappers.Response)
        """
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(
                HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')

        if not sketch.has_permission(current_user, 'read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN,
                  'User does not have read access controls on sketch.')
        aggregations = sketch.get_named_aggregations
        return self.to_json(aggregations) 
Example #11
Source File: __init__.py    From timesketch with Apache License 2.0 6 votes vote down vote up
def get_with_acl(self, model_id, user=current_user):
        """Get a database object with permission check enforced.

        Args:
            model_id: The integer ID of the model to get.
            user: User (instance of timesketch.models.user.User)

        Returns:
            A BaseQuery instance.
        """
        result_obj = self.get(model_id)
        if not result_obj:
            abort(HTTP_STATUS_CODE_NOT_FOUND)
        try:
            if result_obj.get_status.status == 'deleted':
                abort(HTTP_STATUS_CODE_NOT_FOUND)
        except AttributeError:
            pass
        if result_obj.is_public:
            return result_obj
        if not result_obj.has_permission(user=user, permission='read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN)
        return result_obj 
Example #12
Source File: blueprint.py    From website with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(
            base_url="https://api.github.com/",
            authorization_url="https://github.com/login/oauth/authorize",
            token_url="https://github.com/login/oauth/access_token",
            session_class=GitHubSession,
            storage=SQLAlchemyStorage(
                OAuth, db.session, user=current_user, user_required=False, cache=cache
            ),
            *args,
            **kwargs,
        )
        self.from_config.update(
            {
                "client_id": "GITHUB_OAUTH_CLIENT_ID",
                "client_secret": "GITHUB_OAUTH_CLIENT_SECRET",
                "scope": "GITHUB_SCOPE",
                "members_team_id": "GITHUB_MEMBERS_TEAM_ID",
                "roadies_team_id": "GITHUB_ROADIES_TEAM_ID",
                "admin_access_token": "GITHUB_ADMIN_TOKEN",
                "org_id": "GITHUB_ORG_ID",
            }
        ) 
Example #13
Source File: log.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_db(data=None, as_api=False):
        """
        记录日志到数据库

        :param data: dict, 键必须是 log 表字段名
        :param as_api:
        :return:
        """
        log = {
            'log_action': request.endpoint,
            'log_operator': getattr(current_user, 'realname', request.remote_addr)
        }

        isinstance(data, dict) and log.update(data)
        if not isinstance(log.get('log_content', ''), str):
            log['log_content'] = json.dumps(log['log_content'], ensure_ascii=False)

        res = TBLog().insert(log)
        if not res and as_api:
            raise APIFailure('日志入库失败')

        return res 
Example #14
Source File: views.py    From fitbit-api-example-python with Apache License 2.0 6 votes vote down vote up
def index():
    if not flask_login.current_user.is_authenticated:
        return redirect(url_for('main.login'))
    else:
        user_profile = "Could not access fitbit profile"
        fitbit_creds = get_user_fitbit_credentials(flask_login.current_user.id)
        if fitbit_creds:
            with fitbit_client(fitbit_creds) as client:
                try:
                    profile_response = client.user_profile_get()
                    user_profile = "{} has been on fitbit since {}".format(
                        profile_response['user']['fullName'],
                        profile_response['user']['memberSince']
                    )
                except BadResponse:
                    flash("Api Call Failed")
        return render_template('index.html', user_profile=user_profile, permission_url=get_permission_screen_url()) 
Example #15
Source File: object_faker.py    From betterlifepsi with MIT License 5 votes vote down vote up
def category(self, category_id=None, creator=current_user):
        from psi.app.models import ProductCategory
        category = ProductCategory()
        category.id = category_id if category_id is not None else db_util.get_next_id(ProductCategory)
        category.code = self.faker.pystr(max_chars=8)
        category.name = self.faker.name()
        category.organization = creator.organization
        return category 
Example #16
Source File: data_security_mixin.py    From betterlifepsi with MIT License 5 votes vote down vote up
def can_view_details(self, user=current_user):
        if hasattr(self, 'organization_id') and hasattr(self, 'organization'):
            return (user.organization_id == self.organization_id or
                    self.organization in user.organization.all_children)
        return True 
Example #17
Source File: object_faker.py    From betterlifepsi with MIT License 5 votes vote down vote up
def product(self, product_id=None, supplier=None, creator=current_user):
        from psi.app.models import Product
        product = Product()
        product.id = product_id if product_id is not None else db_util.get_next_id(Product)
        product.category = self.category(creator=creator)
        product.name = self.faker.name()
        product.deliver_day = random.randint(3, 7)
        product.supplier = self.supplier(creator=creator) if supplier is None else supplier
        product.distinguishing_feature = self.faker.paragraphs(nb=3)
        product.lead_day = random.randint(1, 5)
        product.need_advice = self.faker.pybool()
        product.purchase_price = random.randint(1, 100)
        product.retail_price = product.purchase_price + random.randint(1, 100)
        product.organization = creator.organization
        return product 
Example #18
Source File: object_faker.py    From betterlifepsi with MIT License 5 votes vote down vote up
def customer(self, customer_id=None, creator=current_user):
        from psi.app.models import Customer
        customer = Customer()
        customer.id = customer_id if customer_id is not None else db_util.get_next_id(Customer)
        customer.address = self.faker.address()
        customer.birthday = self.faker.date_time_this_decade()
        customer.email = self.faker.safe_email()
        customer.first_name = self.faker.first_name()
        customer.last_name = self.faker.last_name()
        customer.join_date = self.faker.date_time_this_decade()
        customer.join_channel = random.choice(customer.join_channel_filter().all())
        customer.level = random.choice(customer.level_filter().all())
        customer.organization = creator.organization
        customer.points = self.faker.pyint()
        return customer 
Example #19
Source File: object_faker.py    From betterlifepsi with MIT License 5 votes vote down vote up
def supplier(self, supplier_id=None, creator=current_user):
        from psi.app.models import Supplier
        supplier = Supplier()
        supplier.id = supplier_id if supplier_id is not None else db_util.get_next_id(Supplier)
        supplier.name = self.faker.name()
        supplier.can_mixed_whole_sale = self.faker.pybool()
        supplier.contact = self.faker.name()
        supplier.email = self.faker.email()
        supplier.phone = self.faker.phone_number()
        supplier.qq = self.faker.pyint()
        supplier.organization = creator.organization
        supplier.remark = self.faker.pystr(max_chars=100)
        supplier.website = self.faker.uri()[:64]
        return supplier 
Example #20
Source File: decorators.py    From tutorial-flask with Apache License 2.0 5 votes vote down vote up
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kws):
        is_admin = getattr(current_user, 'is_admin', False)
        if not is_admin:
            abort(401)
        return f(*args, **kws)
    return decorated_function 
Example #21
Source File: users.py    From unshred-tag with MIT License 5 votes vote down vote up
def init_social_login(app, db):
    app.register_blueprint(social_auth)
    init_social(app, db)

    login_manager = flask_login.LoginManager()
    login_manager.login_view = 'index'
    login_manager.login_message = ''
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(userid):
        try:
            user = User.objects.get(id=userid)
            if user:
                user.last_login = datetime.datetime.now()
                user.save()
            return user
        except (TypeError, ValueError, User.DoesNotExist):
            pass

    @app.before_request
    def global_user():
        g.user = flask_login.current_user

    @app.context_processor
    def inject_user():
        try:
            return {'user': g.user}
        except AttributeError:
            return {'user': None} 
Example #22
Source File: object_faker.py    From betterlifepsi with MIT License 5 votes vote down vote up
def purchase_order(self, po_id=None, number_of_line=1, creator=current_user,
                       type=None, status=None):
        from psi.app.models import PurchaseOrder, PurchaseOrderLine, EnumValues
        po = PurchaseOrder()
        po.remark = self.faker.text(max_nb_chars=20)
        po.logistic_amount = self.faker.pyfloat(positive=True, left_digits=2, right_digits=0)
        po.order_date = self.faker.date()
        if status is None:
            draft_status = EnumValues.get(const.PO_DRAFT_STATUS_KEY)
            po.status = draft_status
        else:
            po.status = status
            po.status_id = status.id
        if type is None:
            types = EnumValues.type_filter(const.PO_TYPE_KEY).all()
            type = random.choice(types)
            if type.code == const.FRANCHISE_PO_TYPE_KEY:
                if creator.organization.parent is not None:
                    po.to_organization = creator.organization.parent
                else:
                    po.to_organization = creator.organization
        po.type = type
        po.type_id = type.id
        po.id = po_id if po_id is not None else db_util.get_next_id(PurchaseOrder)
        po.organization = creator.organization
        po.supplier = self.supplier(creator=creator)
        for i in range(0, number_of_line):
            line = PurchaseOrderLine()
            line.remark = self.faker.text(max_nb_chars=10)
            line.id = db_util.get_next_id(PurchaseOrderLine)
            line.product = self.product(supplier=po.supplier, creator=creator)
            line.purchase_order = po
            line.quantity = random.randint(1, 100)
            line.unit_price = self.faker.pydecimal(positive=True, left_digits=3, right_digits=0)
        return po 
Example #23
Source File: sales_order.py    From betterlifepsi with MIT License 5 votes vote down vote up
def can_edit(self, user=current_user):
        can = super(SalesOrder, self).can_edit()
        return can and self.status.code != const.SO_DELIVERED_STATUS_KEY 
Example #24
Source File: test_login.py    From flask-react-spa with MIT License 5 votes vote down vote up
def test_html_login_with_username(self, client, user):
        r = client.post(url_for('security.login'),
                        data=dict(email=user.username, password='password'))
        assert r.status_code == 302
        assert r.path == '/'
        assert current_user == user 
Example #25
Source File: data_security_mixin.py    From betterlifepsi with MIT License 5 votes vote down vote up
def can_edit(self, user=current_user):
        if hasattr(self, 'organization_id') and hasattr(self, 'organization'):
            return (user.organization_id == self.organization_id or
                    self.organization in user.organization.all_children)
        return True 
Example #26
Source File: inventory_transaction.py    From betterlifepsi with MIT License 5 votes vote down vote up
def can_edit(self, user=current_user):
        return (self.type.code == const.INVENTORY_LOST_TYPE_KEY
               or self.type.code == const.INVENTORY_DAMAGED_TYPE_KEY) 
Example #27
Source File: receiving.py    From betterlifepsi with MIT License 5 votes vote down vote up
def can_edit(self, user=current_user):
        return self.receiving_in_draft() 
Example #28
Source File: db_util.py    From betterlifepsi with MIT License 5 votes vote down vote up
def filter_by_organization(object_type, user=current_user):
    """
    Filter object by user's organization
    :param object_type: Object type to filter
    :param user: User('s Organization) to use for the filter
    :return: List of object filter by the user's organisation
    """
    db = Info.get_db()
    return db.session.query(object_type).filter_by(organization_id=user.organization_id).all() 
Example #29
Source File: db_util.py    From betterlifepsi with MIT License 5 votes vote down vote up
def get_by_name(object_type, val, user=current_user):
    """
    Get the first model object via query condition of name field
    :param object_type: Object type
    :param val: value of the name
    :param user: user context, default to current login user.
    :return: The object if found, otherwise None
    """
    db = Info.get_db()
    if hasattr(object_type, 'organization_id'):
        return db.session.query(object_type).filter_by(name=val, organization_id=user.organization_id).first()
    return db.session.query(object_type).filter_by(name=val).first() 
Example #30
Source File: db_util.py    From betterlifepsi with MIT License 5 votes vote down vote up
def get_by_external_id(object_type, external_id, user=current_user):
    """
    Get model object via external_id, a field names "external_id" should exists
    :param object_type: Object type
    :param external_id: external id
    :param user: user context, default to current login user.
    :return: The object if found, otherwise None
    """
    db = Info.get_db()
    if hasattr(object_type, 'organization_id'):
        return db.session.query(object_type).filter_by(external_id=external_id, organization_id=user.organization_id).first()
    return db.session.query(object_type).filter_by(external_id=external_id).first()