async def wrapper(*args):
        try:
            request = args[0]
            payload = __jwt_authorization_decode_by_request(
                request, SECRET_KEY, "HS256")

            if payload == False:
                return web.Response(text="Necessário token de autenticação.",
                                    status=403)

            user_id = payload['id']
            expiration_date = datetime.fromisoformat(
                payload['expiration_date'])
            repository = UserRepository(session)
            user = repository.get_by_id(user_id)
            if (expiration_date < datetime.now()):
                return web.Response(
                    text=
                    'Token está expirado. Realize novamente a autenticação.',
                    status=401)

            return await func(request) if func else None
        except Exception as e:
            print(e)
            if isinstance(e, EntityNotFound):
                return web.Response(text="Usuário/senha incorreto(s)",
                                    status=401)
            return web.Response(
                text=
                "Ocorreu um erro no servidor. Por favor, tente novamente mais tarde.",
                status=500)
Beispiel #2
0
    def login(self, email: str, password: str) -> dict:
        # Get user data
        user_model = UserRepository(self.context).find_by_email(email)
        if not user_model:
            self.logger.info("User does not exit. email: {}".format(email))
            return None

        # Check password
        is_valid = self.bcrypt.check_password_hash(user_model.password, password)
        if not is_valid:
            self.logger.info("Provided password is not correct. email: {}".format(email))
            return None

        # Create session
        token = self._encode_token(email)

        session_repository = SessionRepository(self.context)
        session_model = session_repository.find_by_token(token)
        if session_model:
            self.logger.info("Delete old session. token: {}".format(token))
            session_repository.delete(session_model)
            session_repository.save()

        session_object = SessionConverter().get_model_object(token)
        session_model = session_repository.create(session_object)
        session_repository.save()

        return {
            "user": UserConverter().get_value_object(user_model),
            'session': SessionConverter().get_value_object(session_model)
        }
Beispiel #3
0
def _bind(binder):

    # Auth
    auth_repository = AuthRepository(db)
    auth_service = AuthService(auth_repository)
    binder.bind(AuthRepository, to=auth_repository, scope=request)
    binder.bind(AuthService, to=auth_service, scope=request)

    # File
    file_repository = FileRepository(db)
    file_service = FileService(file_repository)
    binder.bind(FileRepository, to=file_repository, scope=request)
    binder.bind(FileService, to=file_service, scope=request)

    # User
    user_repository = UserRepository(db)
    user_service = UserService(user_repository)
    binder.bind(UserRepository, to=user_repository, scope=request)
    binder.bind(UserService, to=user_service, scope=request)

    # Tag
    tag_repository = TagRepository(db)
    binder.bind(TagRepository, to=tag_repository, scope=request)

    # Note
    note_repository = NoteRepository(db)
    note_service = NoteService(note_repository, tag_repository)
    binder.bind(NoteRepository, to=note_repository, scope=request)
    binder.bind(NoteService, to=note_service, scope=request)
Beispiel #4
0
    def signin(self, token: str) -> dict:
        # Get session object
        session_repository = SessionRepository(self.context)
        session_model = session_repository.find_by_token(token)

        # TODO Check create datetime

        # Decode token
        email = self._decode_token(token)

        # Get user object
        user_repository = UserRepository(self.context)
        user_model = user_repository.find_by_email(email)
        if not user_model:
            self.logger.info("User does not exit. token: {}".format(token))
            return None

        return {
            'user': UserConverter().get_value_object(user_model),
            'session': SessionConverter().get_value_object(session_model)
        }
Beispiel #5
0
    def signup(self, data: dict) -> dict:
        # Prepare model data
        data["password"] = self.bcrypt.generate_password_hash(data["password"]).decode(self.UTF8)
        token = self._encode_token(data["email"])

        user_object = UserConverter().get_model_object(data)
        session_object = SessionConverter().get_model_object(token)

        # Insert into database
        user_repository = UserRepository(self.context)
        user_model = user_repository.create(user_object)

        session_repository = SessionRepository(self.context)
        session_model = session_repository.create(session_object)

        # Commit
        user_repository.save()
        session_repository.save()

        return {
            'user': UserConverter().get_value_object(user_model),
            'session': SessionConverter().get_value_object(session_model)
        }
    async def authenticate(request):
        ''' Returns a json with token and expiration_date (needed for anothers requests)
      Unpacks user and password from authorization for validation.
    '''
        try:
            try:
                authorization = request.headers['Authorization']
            except:
                return web.Response(
                    text="Dados para autenticação necessários.", status=403)
            encoded = authorization[len("Basic "):]
            binary = base64.b64decode(encoded)
            packed = binary.decode().split(":", 2)

            username: str = packed[0]
            password: str = packed[1]

            user_repository = UserRepository(session)
            auth: Auth = user_repository.authenticate(username, password)
            return web.Response(text=json.dumps({
                'token':
                auth.token,
                'expiration_time':
                auth.expiration_time
            }),
                                status=200)
        except Exception as e:
            print(e)
            if isinstance(e, DomainException):
                return web.Response(
                    text=
                    'Usuário e/ou senha incorreta. Por favor, tente novamente.',
                    status=403)
            return web.Response(
                text=
                'Ocorreu um erro no servidor. Por favor, tente novamente mais tarde.',
                status=500)
class AuthService:
    def __init__(self):
        self.user_repository = UserRepository()

    def authenticate(self, email, password):
        user = self.user_repository.get_user_by_email(email)

        if not user or not user.verify_password(password):
            raise BadCredentialsException('Email or password incorrect')

        current_user = CurrentUser.from_user(user)

        return {
            'access_token': create_access_token(identity=current_user),
            'refresh_token': create_refresh_token(identity=current_user)
        }

    def refresh_token(self):
        current_user = SecurityUtils.get_current_user()

        return {
            'access_token': create_access_token(identity=current_user),
            'refresh_token': create_refresh_token(identity=current_user)
        }
 def __init__(self):
     self.user_repository = UserRepository()
class UserService:
    def __init__(self):
        self.user_repository = UserRepository()

    def get_users(self, name, page, per_page):
        return self.user_repository.get_users(name, page, per_page)

    def get_current_user(self):
        current_user = SecurityUtils.get_current_user()
        return self.get_user_by_id(current_user.id)

    def get_user_by_id(self, id):
        user = self.user_repository.get_user_by_id(id)

        if not user:
            raise ResourceNotFoundException(
                f'User not found with identifier {id}')

        return user

    def get_user_by_email(self, email):
        user = self.user_repository.get_user_by_email(email)

        if not user:
            raise ResourceNotFoundException(
                f'User not found with identifier {email}')

        return user

    def user_exists_by_id(self, id):
        return self.user_repository.user_exists_by_id(id)

    def user_exists_by_email(self, email):
        return self.user_repository.user_exists_by_email(email)

    def create_user(self, user):
        exists = self.user_exists_by_email(user.email)

        if exists:
            raise ConflictException('That email address is already in use')

        user.id = None
        user.hash_password()

        return self.user_repository.save_user(user)

    def update_user(self, id, user):
        if not self.user_exists_by_id(id):
            raise ResourceNotFoundException(
                f'User not found with identifier {id}')

        user.id = id

        return self.user_repository.save_user(user)

    def delete_user_by_id(self, id):
        user = self.user_repository.get_user_by_id(id)

        if not user:
            raise ResourceNotFoundException(
                f'User not found with identifier {id}')

        self.user_repository.delete_user_by_id(id)
Beispiel #10
0
def test_authentication_fail(mocker, user_repository, user):
    mocker.patch('sqlalchemy.orm.query.Query.first', return_value=None)
    user_repository = UserRepository(session)
    with pytest.raises(DomainException):
        auth: Auth = user_repository.authenticate(user.username, user.password)
Beispiel #11
0
def user_repository():
    return UserRepository(session)
Beispiel #12
0
from app.interfaces.api_interfaces import RepositoryInterface
from app.repositories.item_repository import ItemRepository
from app.repositories.user_repository import UserRepository

ItemRepository()
UserRepository()


def test_item_repository():
    assert issubclass(ItemRepository, RepositoryInterface)


def test_user_repository():
    assert issubclass(UserRepository, RepositoryInterface)
Beispiel #13
0
 def read(db: Session, user_id: int):
     return repository.read(db, user_id=user_id)
Beispiel #14
0
 def delete(db: Session, user_id: str):
     return repository.delete(db=db, user_id=user_id)
Beispiel #15
0
 def update(db: Session, user: schema.UserCreate, user_id: str):
     return repository.update(db=db, user=user, user_id=user_id)
Beispiel #16
0
 def create(db: Session, user: schema.UserCreate):
     return repository.create(db=db, user=user)
Beispiel #17
0
 def reads(db: Session,
           skip: int = 0,
           limit: int = 100,
           active: bool = True):
     return repository.reads(db, skip=skip, limit=limit, active=active)
Beispiel #18
0
 def read_by_email(db: Session, email: str):
     return repository.read_by_email(db, email=email)