Esempio n. 1
0
    def test_getting_users(self):
        utils.create_users(10)
        code, users = utils.get(
            self.app,
            f'{self.link}/users',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertAlmostEqual(len(users), 11)

        code, user = utils.get(
            self.app,
            f'{self.link}/user/5',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertAlmostEqual(user, User.get_by_id(5).to_dict())

        code, _ = utils.get(
            self.app,
            f'{self.link}/user/15',
            self.headers
        )
        self.assertAlmostEqual(code, 404)

        admin = User.get_by_id(self.admin['id'])
        admin.is_admin = False
        admin.save()
        code, user = utils.get(
            self.app,
            f'{self.link}/user/5',
            self.headers
        )
        self.assertAlmostEqual(code, 401)
Esempio n. 2
0
    def test_deleting_user(self):
        utils.create_users(10)
        code, msg = utils.delete(
            self.app,
            f'{self.link}/user/3',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertAlmostEqual(User.select().count(), 10)

        code, msg = utils.delete(
            self.app,
            f'{self.link}/user/23',
            self.headers
        )
        self.assertAlmostEqual(code, 404)
        self.assertAlmostEqual(msg['error'], 'User does not exist.')

        utils.create_posts(50)
        seventh_user = User.get_by_id(7)
        self.assertTrue(seventh_user.posts.count() > 0)

        data = {'delete_posts': True}
        code, msg = utils.delete(
            self.app,
            f'{self.link}/user/7',
            self.headers,
            'application/json',
            data
        )
        self.assertAlmostEqual(code, 200)

        num_of_posts = Post.select().where(Post.author == seventh_user).count()
        self.assertAlmostEqual(num_of_posts, 0)
Esempio n. 3
0
def create_users(quantity):
    for _ in range(quantity):
        User.from_dict({
            'username': p.username(),
            'email': p.email(),
            'password': p.password(),
        })
Esempio n. 4
0
 def setUp(self):
     self.app, self.db = create_app(testing=True)
     username, password = p.username(), p.password()
     User.from_dict(dict(username=username, email=p.email(),
                         password=password, is_admin=True))
     self.code, self.admin = utils.post(
         self.app,
         f'{URL}/auth/login',
         username=username,
         password=password
     )
     self.headers = {'x-access-token': self.admin['token']}
Esempio n. 5
0
    def test_editing_users_post(self):
        utils.create_users(3)
        utils.create_posts(50)
        post_id = User.get_by_id(2).posts.first().get_id()
        code, post = utils.post(
            self.app,
            f'{self.link}/user/2/post/{post_id}',
            self.headers,
            title=42
        )
        self.assertAlmostEqual(code, 200)
        self.assertAlmostEqual(post['title'], '42')

        code, _ = utils.post(
            self.app,
            f'{self.link}/user/2/post/404',
            self.headers,
            title='42'
        )
        self.assertAlmostEqual(code, 404)

        code, _ = utils.post(
            self.app,
            f'{self.link}/user/404/post/404',
            self.headers,
            title='42'
        )
        self.assertAlmostEqual(code, 404)

        code, _ = utils.post(
            self.app,
            f'{self.link}/user/2/post/{post_id}',
            self.headers
        )
        self.assertAlmostEqual(code, 403)
Esempio n. 6
0
def create_posts(quantity, users_list=None):
    users = users_list or list(User.select())
    for _ in range(quantity):
        Post.from_dict({
            'title': t.title(),
            'text': t.text(),
            'author': choice(users),
        })
Esempio n. 7
0
def user_exists(user_id, return_user=False):
    try:
        user = User.get_by_id(user_id)
    except User.DoesNotExist:
        return False
    if return_user:
        return user
    return True
Esempio n. 8
0
 def test_others_posts(self):
     utils.create_users(3)
     code, _ = utils.get(self.app, f'{URL}/me/posts/others', self.headers)
     self.assertAlmostEqual(code, 404)
     users = list(User.select().where(User.id != self.user['id']))
     utils.create_posts(10, users)
     code, data = utils.get(self.app, f'{URL}/me/posts/others',
                            self.headers)
     self.assertAlmostEqual(code, 200)
     self.assertAlmostEqual(len(data), 10)
Esempio n. 9
0
    def test_registration(self):
        self.assertAlmostEqual(User.select().count(), 1)

        code, data = utils.post(
            self.app,
            f'{self.link}/register',
            headers=self.headers,
            username=p.username(), email=p.email(),
            password=p.password(), is_admin=True
        )
        self.assertAlmostEqual(code, 201)
Esempio n. 10
0
def create_user(data, admin=False):
    fields = User._meta.allowed_fields
    if any(field not in data or data.get(field) is None for field in fields):
        return error('Must include {}, {} and {} fields.'.format(*fields), 403)
    if 'is_admin' in data:
        if not isinstance(data['is_admin'], bool):
            return error('"is_admin" must be boolean', 403)
        if data['is_admin'] and not admin:
            return error('Admin rights are required for this action.', 401)
    try:
        user = User.from_dict(data)
    except ValueError:
        return error('User with this email or username already exists.', 403)
    return jsonify(user.to_dict()), 201
Esempio n. 11
0
 def inner(*args, **kwargs):
     token = request.headers.get('x-access-token')
     if token is None:
         return error('Token is missing.', 401)
     try:
         data = jwt.decode(token,
                           current_app.config['SECRET_KEY'],
                           algorithms=['HS256'])
     except jwt.InvalidTokenError:
         return error('Token is invalid.', 401)
     user = User.get_by_id(data['id'])
     if admin_required and not user.is_admin:
         return error('Admin rights required to perform this action.',
                      401)
     if return_user:
         return func(user, *args, **kwargs)
     return func(*args, **kwargs)
Esempio n. 12
0
    def test_deleting_users_post(self):
        utils.create_users(3)
        utils.create_posts(50)
        post_id = User.get_by_id(2).posts.first().get_id()
        code, _ = utils.delete(
            self.app,
            f'{self.link}/user/2/post/70',
            self.headers
        )
        self.assertAlmostEqual(code, 404)

        code, post = utils.delete(
            self.app,
            f'{self.link}/user/2/post/{post_id}',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertIs(None, Post.select().where(Post.id == post_id).first())
Esempio n. 13
0
    def test_getting_users_posts(self):
        utils.create_users(10)
        utils.create_posts(50)
        code, _ = utils.get(
            self.app,
            f'{self.link}/user/40/posts',
            self.headers
        )
        self.assertAlmostEqual(code, 404)

        code, posts = utils.get(
            self.app,
            f'{self.link}/user/7/posts',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertTrue(len(posts) > 0)

        code, _ = utils.get(
            self.app,
            f'{self.link}/user/40/post/100', self.headers
        )
        self.assertAlmostEqual(code, 404)

        post_id = User.get_by_id(2).posts.first().get_id()
        code, post = utils.get(
            self.app,
            f'{self.link}/user/2/post/{post_id}',
            self.headers
        )
        self.assertAlmostEqual(code, 200)
        self.assertDictEqual(post, Post.get_by_id(post_id).to_dict())

        code, _ = utils.get(
            self.app,
            f'{self.link}/user/2/post/70',
            self.headers
        )
        self.assertAlmostEqual(code, 404)
Esempio n. 14
0
def auth_login():
    data = request.get_json()
    email, username = data.get('email'), data.get('username')
    password = data.get('password')
    if not any((email, username)) or password is None:
        return error('Both email/username and password are required.', 401)
    user = User.select().where((User.email == email)
                               | (User.username == username)).first()
    if user is None:
        return error('User does not exist.', 403)
    if not user.check_password(password):
        return error('Wrong password.', 403)
    token = jwt.encode(
        {
            'id': user.get_id(),
            'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=2)
        },
        current_app.config['SECRET_KEY'],
        algorithm='HS256')
    data = user.to_dict()
    data['token'] = token.decode('UTF-8')
    return jsonify(data), 200
Esempio n. 15
0
def get_users():
    users = [user.to_dict() for user in User.select()]
    return jsonify(users), 200