コード例 #1
0
# this file adds the `flask db import-fixtures` command for Flask Unchained

from flask_unchained import unchained
from flask_unchained.cli import click, with_appcontext
from flask_unchained.bundles.sqlalchemy import SQLAlchemyUnchained
from flask_unchained.bundles.sqlalchemy.commands import db

from .factories.sqlalchemy import SQLAlchemyModelFactory
from .fixtures_loader import FixturesLoader
from .hooks import ModelFixtureFoldersHook

db_ext: SQLAlchemyUnchained = unchained.get_local_proxy('db')


@db.command(name='import-fixtures')
@click.argument('bundles',
                nargs=-1,
                help='Bundle names to load from (defaults to all)')
@with_appcontext
def import_fixtures(bundles=None):
    fixture_dirs = []
    for bundle_name in (bundles or unchained.bundles.keys()):
        bundle = unchained.bundles[bundle_name]
        fixtures_dir = ModelFixtureFoldersHook.get_fixtures_dir(bundle)
        if fixtures_dir:
            fixture_dirs.append(fixtures_dir)
            click.echo(f'Loading fixtures from {bundle_name}')

    if not fixture_dirs:
        click.echo('No fixtures directories were found. Exiting')
        import sys
コード例 #2
0
from flask import _request_ctx_stack, current_app, request
from flask_principal import Identity, identity_changed
from flask_unchained import unchained
from functools import wraps

from .roles_accepted import roles_accepted
from .roles_required import roles_required
from ..utils import current_user

security = unchained.get_local_proxy('security')


def auth_required(decorated_fn=None, **role_rules):
    """
    Decorator for requiring an authenticated user, optionally with roles.

    Roles are passed as keyword arguments, like so::

        @auth_required(role='REQUIRE_THIS_ONE_ROLE')
        @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES'])
        @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE'])

    One of role or roles kwargs can also be combined with one_of::

        @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS'])

    Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or
    ``HTTP 403: Forbidden`` if any of the specified role checks fail.
    """
    required_roles = []
    one_of_roles = []
コード例 #3
0
ファイル: roles.py プロジェクト: HeathNaylor/flask-unchained
from flask_unchained import unchained
from flask_unchained.cli import cli, click, print_table

from .utils import _query_to_role
from ..services import RoleManager

role_manager: RoleManager = unchained.get_local_proxy('role_manager')


@cli.group()
def roles():
    """
    Role commands.
    """


@roles.command(name='list')
def list_roles():
    """
    List roles.
    """
    roles = role_manager.all()
    if roles:
        print_table(['ID', 'Name'], [(role.id, role.name) for role in roles])
    else:
        click.echo('No roles found.')


@roles.command(name='create')
@click.option('--name',
              prompt='Role name',
コード例 #4
0
ファイル: utils.py プロジェクト: zilleanai/flask-unchained
import sys

from flask_unchained import unchained
from flask_unchained.cli import click

from ..services import UserManager, RoleManager

user_manager: UserManager = unchained.get_local_proxy('user_manager')
role_manager: RoleManager = unchained.get_local_proxy('role_manager')


def _query_to_user(query):
    kwargs = _query_to_kwargs(query)
    user = user_manager.get_by(**kwargs)
    if not user:
        click.secho(f'ERROR: Could not locate a user by {_format_query(query)}',
                    fg='white', bg='red')
        sys.exit(1)
    return user


def _query_to_role(query):
    kwargs = _query_to_kwargs(query)
    role = role_manager.get_by(**kwargs)
    if not role:
        click.secho(f'ERROR: Could not locate a role by {_format_query(query)}',
                    fg='white', bg='red')
        sys.exit(1)
    return role

コード例 #5
0
import graphene

from flask_unchained import unchained
from flask_unchained.bundles.sqlalchemy import SessionManager, ValidationErrors
from graphql import GraphQLError

from . import types

session_manager: SessionManager = unchained.get_local_proxy('session_manager')


class CreateParent(graphene.Mutation):
    class Arguments:
        name = graphene.String(required=True)
        children = graphene.List(graphene.ID)

    parent = graphene.Field(types.Parent)
    success = graphene.Boolean()

    def mutate(self, info, children, **kwargs):
        if children:
            children = (session_manager.query(types.Child._meta.model).filter(
                types.Child._meta.model.id.in_(children)).all())
        try:
            parent = types.Parent._meta.model(children=children, **kwargs)
        except ValidationErrors as e:
            raise GraphQLError(str(e))

        session_manager.save(parent, commit=True)
        return CreateParent(parent=parent, success=True)
コード例 #6
0
from flask_unchained import unchained
from flask_unchained.cli import cli, click
from flask_unchained.commands.utils import print_table

from .utils import _query_to_role, _query_to_user
from ..extensions import Security
from ..services import SecurityService, UserManager

security: Security = unchained.get_local_proxy('security')
security_service: SecurityService = unchained.get_local_proxy(
    'security_service')
user_manager: UserManager = unchained.get_local_proxy('user_manager')


@cli.group()
def users():
    """
    User model commands.
    """


@users.command('list')
def list_users():
    """
    List users.
    """
    users = user_manager.all()
    if users:
        print_table(['ID', 'Email', 'Active', 'Confirmed At'], [(
            user.id,
            user.email,
コード例 #7
0
import pytest

from flask_unchained import unchained

parent_manager = unchained.get_local_proxy('parent_manager')
child_manager = unchained.get_local_proxy('child_manager')

GET_CHILD = '''
query Child($id: ID!) {
  child(id: $id) {
    id
    name
    parent {
      id
      name
    }
  }
}
'''

GET_CHILDREN = '''
{
  children {
    id
    name
    parent {
      id
      name
    }
  }
}
コード例 #8
0
ファイル: forms.py プロジェクト: zilleanai/flask-unchained
import inspect

from flask import current_app as app, request
from flask_unchained.bundles.controller.utils import _validate_redirect_url
from flask_unchained.bundles.sqlalchemy import ModelForm
from flask_unchained import unchained, lazy_gettext as _
from wtforms import (Field, HiddenField, StringField, SubmitField,
                     ValidationError, fields, validators)

from .models import User
from .services import SecurityUtilsService, UserManager
from .utils import current_user

user_manager: UserManager = unchained.get_local_proxy('user_manager')
security_utils_service: SecurityUtilsService = \
    unchained.get_local_proxy('security_utils_service')

password_required = validators.DataRequired(
    _('flask_unchained.bundles.security:password_required'))

password_equal = validators.EqualTo(
    'password',
    message=_(
        'flask_unchained.bundles.security:error.retype_password_mismatch'))

new_password_equal = validators.EqualTo(
    'new_password',
    message=_(
        'flask_unchained.bundles.security:error.retype_password_mismatch'))