Example #1
0
async def list_users(request):
    """ Retrieves all users from the DB"""

    with scoped_session() as session:
        users = session.query(User).all()
        users = [user.to_dict() for user in users]
        return sanic_json(users)
Example #2
0
async def update_user(request, id, user):
    """ Updates an already existing user """

    if user.id != int(id):
        raise Unauthorized('Unauthorized access.')
    with scoped_session() as session:
        ret_user = session.query(User).filter(User.id == int(id)).first()
        data = request.json or {}
        if 'username' in data and data['username'] != ret_user.username and session.query(User).filter(
                User.username == data['username']).first():
            return sanic_json(Response('Please use a different username.').__dict__)
        if 'email' in data and data['email'] != ret_user.email and session.query(User).filter(
                User.email == data['email']).first():
            return sanic_json(Response('Please use a different email address.').__dict__)
        if 'password' in data:
            user.set_password(data['password'])
            session.query(User).filter(User.id == int(id)).update(
                {User.username: data['username'], User.email: data['email'],
                 User.password: user.password,
                 User.modified_at: datetime.utcnow()})
            session.commit()
            return sanic_json(Response('User successfully updated.').__dict__)
        else:
            session.query(User).filter(User.id == int(id)).update(
                {User.username: data['username'], User.email: data['email'],
                 User.modified_at: datetime.utcnow()})
            session.commit()
            return sanic_json(Response('User successfully updated.').__dict__)
Example #3
0
async def delete_user(request, id, user):
    """ Deletes an existing user from the DB"""

    if user.id == int(id):
        with scoped_session() as session:
            session.query(User).filter(User.id == int(id)).delete()
            return sanic_json(Response('User successfully removed.').__dict__)
    raise Unauthorized('Unauthorized access.')
Example #4
0
async def retrieve_user(request, payload, *args, **kwargs):
    with scoped_session() as session:
        if payload:
            id = payload.get('user_id', None)
            user = session.query(User).filter(User.id == id).first()
            session.expunge_all()
            return user
        else:
            return None
Example #5
0
async def get_user(request, id, user):
    """ Retrieves from the DB a particular user using his `id` """

    if user.id == int(id):
        with scoped_session() as session:
            user = session.query(User).filter(User.id == int(id)).first()
            return sanic_json(user.to_dict())
    else:
        raise Unauthorized('Unauthorized access.')
Example #6
0
async def get_user(request, id, user) -> HTTPResponse:
    """ Retrieves from the DB a particular user using his `id` """

    if user:
        if user.id == int(id):
            with scoped_session() as session:
                user = session.query(User).filter(User.id == int(id)).first()
                return sanic_json(user.to_dict())
        else:
            raise Unauthorized('Unauthorized access.', status_code=400)
    else:
        raise Unauthorized('Please provide credentials.', status_code=400)
Example #7
0
async def delete_user(request, id, user) -> HTTPResponse:
    """ Deletes an existing user from the DB"""

    if user:
        if user.id == int(id):
            with scoped_session() as session:
                session.query(User).filter(User.id == int(id)).delete()
                return sanic_json(
                    Response('User successfully removed.').__dict__,
                    status=200)
        raise Unauthorized('Unauthorized access.', status_code=400)
    else:
        raise Unauthorized('Please provide credentials.', status_code=400)
Example #8
0
async def register_user(request):
    """ Creates a user in the DB """

    data = request.json or {}
    with scoped_session() as session:
        if session.query(User).filter(User.username == data['username']).first():
            return sanic_json(Response('Please use a different username.').__dict__)
        if session.query(User).filter(User.email == data['email']).first():
            return sanic_json(Response('Please use a different email address.').__dict__)
        user = User()
        user.from_dict(data)
        session.add(user)
        session.commit()
        return sanic_json(Response('User {} is successfully created.'.format(user.username)).__dict__)
Example #9
0
async def authenticate(request, *args, **kwargs):
    with scoped_session() as session:
        username = request.json.get('username', None)
        password = request.json.get('password', None)

        if not username or not password:
            raise AuthenticationFailed('Missing username or password.')

        user = session.query(User).filter(User.username == username).first()
        if user is None:
            raise AuthenticationFailed('User not found.')
        if not user.check_password(password):
            raise AuthenticationFailed('Password is incorrect.')
        session.expunge_all()
        return user
Example #10
0
    async def post(self, request):
        """ Creates a new user based on the `email` key

        Args:
            request (object): contains data pertaining request.

        Returns:
            json: containing key `msg` with success info & email.
        """
        # Get email key from json request.
        email = request.json.get('email')

        # Create new user.
        with scoped_session() as session:
            user = User(email=email)
            session.add(user)

        # Return json response.
        return json({'msg': 'Successfully created {}'.format(email)})
Example #11
0
async def register_user(request) -> HTTPResponse:
    """ Creates a user in the DB """

    data = request.json or {}
    with scoped_session() as session:
        if session.query(User).filter(
                User.username == data['username']).first():
            return sanic_json(
                Response('Please use a different username.').__dict__,
                status=400)
        if session.query(User).filter(User.email == data['email']).first():
            return sanic_json(
                Response('Please use a different email address.').__dict__,
                status=400)
        user = User()
        user.from_dict(data)
        session.add(user)
        session.commit()
        return sanic_json(user.to_dict(), status=200)
Example #12
0
    async def get(self, request):
        """ Gets all users in the DB

         Args:
             request (object): contains data pertaining request.

         Notes:
             Realistically There would be some form of authentication in place
             Like a Token to grab the Auth Header value and return a specific
             user based on Token. Although for the purpose of brevity this route
             will just return all users in the database.

         Returns:
             json: containing list of users under the `users` key.
         """
        # Gets all users in DB.
        with scoped_session() as session:
            users = session.query(User).all()

        return json({'users': users})