def test_authorization_header():
    token = register_request(username='******').json().get('token')

    # Define a dummy endpoint to test authentication
    from apistar import annotate, Include, Route
    from apistar.interfaces import Auth
    from apistar.http import Response
    from apistar.permissions import IsAuthenticated

    @annotate(permissions=[IsAuthenticated()])
    def dummy(auth: Auth):
        return Response(status=200, content='')

    # Small hack to add "dummy" endpoint during runtime
    prev_router_lookup = app.router.lookup
    app.router.lookup = lambda path, method: (dummy, {})

    response = client.get('/dummy',
                          headers={'Authorization': 'Token {}'.format(token)})
    assert response.status_code == 200

    response = client.get('/dummy')
    assert response.status_code == 403

    response = client.get(
        '/dummy', headers={'Authorization': 'Token {}'.format('wrongtoken')})
    assert response.status_code == 403

    # Return router to previous state
    app.router.lookup = prev_router_lookup
Exemplo n.º 2
0
    def delete(self):

        @annotate(permissions=[IsAuthenticated(), ActesWritePermission(self)])
        def acte_delete(obj_id: int, auth: Auth) -> Response:
            obj = self.model.objects.get(id=obj_id)
            obj.delete()
            return Response({'message': 'deleted'}, status=201)

        acte_delete.__doc__ = f""" Delete  {self.url_name}"""
        return acte_delete
Exemplo n.º 3
0
    def update(self):

        @annotate(permissions=[IsAuthenticated(), ActesWritePermission(self)])
        def acte_update(obj_id: int, new_data: actes_schemas[self.model].updater,
                        auth: Auth) -> Response:

            # check against empty data
            if not new_data:
                raise BadRequest("empty query")

            obj = self.model.objects.get(id=obj_id)

            try:
                obj.update(**new_data)
            except AttributeError as e:
                # request should be for valide fields
                raise BadRequest from e
            return Response(actes_schemas[self.model].getter(obj), status=201)

        acte_update.__doc__ = f""" Update  {self.url_name}"""
        return acte_update
Exemplo n.º 4
0
# Third Party Libraries
from apistar.permissions import IsAuthenticated
from config.get_env import env
from users.authentication import MapistarJWTAuthentication

AUTHENTICATION = [
    MapistarJWTAuthentication(),
]
PERMISSIONS = [
    IsAuthenticated(),
]
JWT = {'SECRET': env['JWT_SECRET'], 'PAYLOAD_DURATION': {'seconds': 300}}

ACTES_URL = '/actes'

if not ACTES_URL:
    raise Exception(' ACTES_URL not set')
Exemplo n.º 5
0
from apistar import http, exceptions, Include, Command
from apistar.backends import sqlalchemy_backend
from apistar.frameworks.asyncio import ASyncIOApp
from apistar.handlers import docs_urls, static_urls
from apistar.permissions import IsAuthenticated
from projects.routes import routes as projects_routes
from users.routes import routes as users_routes
from tokens.routes import routes as tokens_routes
from db_base import Base
from server import run
from migrations.commands import revision, upgrade, downgrade
from tokens.routes import TokenAuthentication

settings = {
    "AUTHENTICATION": [TokenAuthentication()],
    "PERMISSIONS": [IsAuthenticated()],
    "JWT_SECRET": os.environ['JWT_SECRET'],
    "DATABASE": {
        "URL": 'postgresql://{e[DB_USER]}:{e[DB_PASSWORD]}@{e[DB_HOST]}/{e[DB_NAME]}'  # nopep8
               .format(e=os.environ),
        "METADATA": Base.metadata
    }
}


class App(ASyncIOApp):
    def exception_handler(self, exc: Exception) -> http.Response:
        if isinstance(exc, exceptions.Found):
            return http.Response(
                status=exc.status_code,
                headers={'Location': exc.location}
Exemplo n.º 6
0
from apistar import Response, annotate, Settings
from apistar.backends.sqlalchemy_backend import Session
from apistar.interfaces import Auth
from apistar.permissions import IsAuthenticated

from apistar_token_auth.authentication import SQLAlchemyTokenAuthentication
from .schemas import SignupData
from .models import User
from .utils import hash_password


@annotate(authentication=[SQLAlchemyTokenAuthentication()],
          permissions=[IsAuthenticated()])
def user_profile(session: Session, auth: Auth):
    return {'username': auth.user.username}


def signup(session: Session, data: SignupData, settings: Settings):
    user = User(username=data['username'],
                password=hash_password(data['password'], settings))
    session.add(user)
    session.flush()

    return {'id': user.id, 'username': user.username}
Exemplo n.º 7
0
    db_produto = session.Produto(**produto)
    db_produto.save()
    return http.Response(content=schemas.Produto(db_produto.__dict__),
                         status=201)


def listar_produtos(nota: schemas.Nota, session: Session):
    produtos = session.Produto.objects.all()
    if nota is not None:
        produtos = produtos.filter(nota=nota)
    return [schemas.Produto(db_produto.__dict__) for db_produto in produtos]


def valida_cpf(cpf: schemas.CPF):
    return cpf


def criar_usuario(user: schemas.User, session: Session):
    if not user:
        return
    db_user = session.User.objects.create_user(**user)
    return schemas.User(db_user.__dict__)


@annotate(permissions=[IsAuthenticated()])
def listar_usuarios(username: schemas.Username, session: Session):
    usuarios = session.User.objects.all()
    if username is not None:
        usuarios = usuarios.filter(username=username)
    return [schemas.User(db_user.__dict__) for db_user in usuarios]
Exemplo n.º 8
0
    },

    'RENDERERS': (JSONRenderer(), MessagePackRenderer()),
    # 'RENDERERS': (JSONRenderer(), MessagePackRenderer(), HTMLRenderer()),

    'PARSERS': (JSONParser(), MultiPartParser(), MessagePackParser()),
    # 'PARSERS': (JSONParser(), MultiPartParser()),  # Default.

    'AUTHENTICATION': (JWTAuthentication(), ),
    'JWT': {  # Do NOT PUSH your SECRET into version control!.
        'SECRET': 's0m3-l0ng-s3cr3t',  # Long randomized secret string key.
        'LEEWAY': 60,  # Seconds of expiration time.
    },  # https://github.com/audiolion/apistar-jwt#usage

    'PERMISSIONS': (
        IsAuthenticated(), IsGuestUser(), IsFreeUser(), IsPremiumUser(),
        IsCompanyUser(), IsAdminUser(), IsTesterUser(), IsStaffUser(),
    ),

    'HUEY': {  # https://huey.readthedocs.io
        'FILENAME': 'huey_tasks_queue.db',  # File for Huey DB.
        'NAME': 'apistar',                  # Tasks Queue Name.
        "HOST": '127.0.0.1',                # Your Redis host.
    },

    'DONT_WRITE_BYTECODE': True,  # No *.PYC

})

# settings: dict = dict(settings)  # Uncomment for Mutable Config at runtime.
Exemplo n.º 9
0
        scheme, token = authorization.split()
        if scheme.lower() != 'basic':
            return None

        username, password = base64.b64decode(token).decode('utf-8').split(':')
        return Authenticated(username)


routes = [
    Route('/auth/', 'GET', get_auth),
    Route('/public/', 'GET', public),
]
settings = {
    'AUTHENTICATION': [BasicAuthentication()],
    'PERMISSIONS': [IsAuthenticated()]
}

wsgi_app = WSGIApp(routes=routes, settings=settings)
wsgi_client = TestClient(wsgi_app)

async_app = ASyncIOApp(routes=routes, settings=settings)
async_client = TestClient(async_app)


@pytest.mark.parametrize('client', [wsgi_client, async_client])
def test_unauthenticated_request(client):
    response = client.get('http://example.com/auth/')
    assert response.status_code == 403
    assert response.json() == {'message': 'Forbidden'}