Пример #1
0
 def setUp(self):
     self.app = create_app(TestingConfig)
     self.client = self.app.test_client
     # seed data
     self.role = Role('general')
     self.role.insert()
     self.user = User('Ahmed', 'Hamed', '*****@*****.**',
                      'ahmedhrayyan', 'secret', self.role.id)
     self.user.insert()
     self.question = Question(self.user.id, 'Is sal the best QA engine')
     self.question.insert()
     self.answer = Answer(self.user.id, self.question.id, 'Yes it is')
     self.answer.insert()
     self.token = gen_token(self.app.config['SECRET_KEY'], self.user)
Пример #2
0
def upgrade():
    bind = op.get_bind()
    session = orm.Session(bind=bind)

    session.add_all([
        Role(id=0, name="Guest", permissions={}),
        Role(id=1, name="Admin", permissions={"all": 1}),
        Role(id=2, name="Secretary", permissions={
             "user_list": 1, "user_create": 1, "user_edit": 1}),
        Role(id=3, name="GBC", permissions={
             "user_list": 1, "user_create": 1}),
    ])

    session.commit()
Пример #3
0
    async def post(self):
        r_dict = {'code': 0}
        try:
            code = self.get_argument('code')
            title = self.get_argument('title')
            content = self.get_argument('content')
            status = self.get_argument('status')
            if code and title:
                r_count = await Role.count(dict(code=code))
                if r_count > 0:
                    r_dict['code'] = -3
                else:
                    if status == 'on':
                        status = STATUS_ROLE_ACTIVE
                    else:
                        status = STATUS_ROLE_INACTIVE

                    role = Role(code=code, title=title, status=status)
                    role.content = content
                    role.created_id = self.current_user.oid
                    role.updated_id = self.current_user.oid
                    role.needless = {'user_amount': 0}
                    role_id = await role.save()
                    if role_id:
                        r_dict['code'] = 1
            else:
                if not code:
                    r_dict['code'] = -1
                elif not title:
                    r_dict['code'] = -2
        except Exception:
            logger.error(traceback.format_exc())
        return r_dict
Пример #4
0
 def db_seed():
     # permission
     delete_users = Permission('delete:users')
     delete_answers = Permission('delete:answers')
     delete_questions = Permission('delete:questions')
     delete_users.insert()
     delete_answers.insert()
     delete_questions.insert()
     # roles
     general = Role('general')
     superamdin = Role('superadmin')
     superamdin.permissions.append(delete_users)
     superamdin.permissions.append(delete_answers)
     superamdin.permissions.append(delete_questions)
     general.insert()
     superamdin.insert()
Пример #5
0
def load_data():
    from db.models import (User, UserEmail, UserPermission, Role, Permission,
                           Group, GroupMember, GroupPermission)
    from db.models.utils import Session

    session = Session()

    dev_role = Role(name='PYTHON_DEV')
    intellij_ide = Permission(name='pycharm')

    session.add_all([dev_role, intellij_ide])
    session.commit()

    prem = User(
        first_name='Premkumar',
        last_name='Chalmeti',
        username='******',
        avatar='https://avatars0.githubusercontent.com/u/22867776',
        bio=
        'Software Craftsman | Python | Django | Elasticsearch | VueJS | AWS',
        role=dev_role.id,
        password='******')

    session.add(prem)
    session.commit()

    emails = UserEmail(user_id=prem.id, primary_email='*****@*****.**')

    user_rights = UserPermission(role_id=dev_role.id,
                                 permission_id=intellij_ide.id)

    session.add_all([emails, user_rights])
    session.commit()

    devops = Group(name='DevOps Team')
    aws_permission = Permission(name='AWS_ACCOUNT')

    session.add_all([devops, aws_permission])
    session.commit()

    devops_member = GroupMember(group_id=devops.id, user_id=prem.id)
    group_rights = GroupPermission(group_id=devops.id,
                                   permission_id=aws_permission.id)
    session.add_all([devops_member, group_rights])
    session.commit()
Пример #6
0
class SalTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app(TestingConfig)
        self.client = self.app.test_client
        # seed data
        self.role = Role('general')
        self.role.insert()
        self.user = User('Ahmed', 'Hamed', '*****@*****.**',
                         'ahmedhrayyan', 'secret', self.role.id)
        self.user.insert()
        self.question = Question(self.user.id, 'Is sal the best QA engine')
        self.question.insert()
        self.answer = Answer(self.user.id, self.question.id, 'Yes it is')
        self.answer.insert()
        self.token = gen_token(self.app.config['SECRET_KEY'], self.user)

    def tearDown(self):
        db.drop_all()

    def test_422_upload(self):
        res = self.client().post('api/upload',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 data={'file': (BytesIO(b'IMAGE DATA'), 'file.jpg')}) # fake data
        json_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_404_view_uploaded(self):
        res = self.client().get('/uploads/x')
        self.assertEqual(res.status_code, 404)

    def test_422_register(self):
        res = self.client().post('/api/register',
                                 json={
                                     'first_name': 'ahmed',
                                     'last_name': 'hamed',
                                     'email': '*****@*****.**',
                                     'username': self.user.username,  # username already exists
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(res_data['success'])
        self.assertTrue(res_data['message'])

    def test_register(self):
        res = self.client().post('/api/register',
                                 json={
                                     'first_name': 'ahmed',
                                     'last_name': 'hamed',
                                     'email': '*****@*****.**',
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['username'], 'test')

    def test_patch_user(self):
        res = self.client().patch('/api/user',
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'job': 'test',
                                  })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['job'], 'test')

    def test_422_login(self):
        res = self.client().post('/api/login',
                                 json={
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 422)
        self.assertFalse(res_data['success'])
        self.assertTrue(res_data['message'])

    def test_login(self):
        res = self.client().post('/api/login',
                                 json={
                                     'username': '******',
                                     'password': '******'
                                 })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertEqual(res_data['data']['username'], 'ahmedhrayyan')

    def test_get_notifications(self):
        res = self.client().get('/api/notifications',
                                headers={
                                    'Authorization': 'Bearer %s' % self.token
                                })
        res_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(res_data['success'])
        self.assertGreaterEqual(res_data['unread_count'], 0)

    def test_get_questions(self):
        res = self.client().get('/api/questions')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_404_show_question(self):
        res = self.client().get('/api/questions/232482')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_question(self):
        res = self.client().get('/api/questions/%i' % self.question.id)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.question.id, json_data['data']['id'])

    def test_400_post_question(self):
        res = self.client().post('/api/questions',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 400)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_post_question(self):
        content = 'Is this great or what'
        res = self.client().post('/api/questions',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'user_id': self.user.id,
                                     'content': content
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_patch_question(self):
        res = self.client().patch('/api/questions/%i' % self.question.id,
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'accepted_answer': self.answer.id
                                  })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['data']['accepted_answer'])

    def test_404_delete_question(self):
        res = self.client().delete('/api/questions/10000',
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_delete_question(self):
        res = self.client().delete('/api/questions/%i' % self.question.id,
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.question.id, json_data['deleted_id'])

    def test_404_show_answer(self):
        res = self.client().get('/api/answers/10420')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_answer(self):
        res = self.client().get('/api/answers/%i' % self.answer.id)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['data']['id'])

    def test_400_post_answer(self):
        res = self.client().post('/api/answers',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 content_type='application/json')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 400)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_post_answer(self):
        content = 'answer'
        res = self.client().post('/api/answers',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'user_id': self.user.id,
                                     'question_id': self.question.id,
                                     'content': content
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_patch_answer(self):
        content = 'new answer'
        res = self.client().patch('/api/answers/%i' % self.answer.id,
                                  headers={
                                      'Authorization': 'Bearer %s' % self.token
                                  },
                                  json={
                                      'content': content
                                  })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertIn(content, json_data['data']['content'])

    def test_404_delete_answer(self):
        res = self.client().delete('/api/answers/10000',
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_delete_answer(self):
        res = self.client().delete('/api/answers/%i' % self.answer.id,
                                   headers={
                                       'Authorization': 'Bearer %s' % self.token
                                   },
                                   )
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(self.answer.id, json_data['deleted_id'])

    def test_404_show_user(self):
        res = self.client().get('/api/users/x')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_show_user(self):
        res = self.client().get('/api/users/%s' % self.user.username)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
        self.assertEqual(json_data['data']['username'], self.user.username)

    def test_404_get_user_questions(self):
        res = self.client().get('/api/users/x/questions')
        json_data = res.get_json()
        self.assertEqual(res.status_code, 404)
        self.assertFalse(json_data['success'])
        self.assertTrue(json_data['message'])

    def test_get_user_questions(self):
        res = self.client().get('/api/users/%s/questions' % self.user.username)
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_report_question(self):
        res = self.client().post('/api/report/question',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'question_id': self.question.id
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])

    def test_report_answer(self):
        res = self.client().post('/api/report/answer',
                                 headers={
                                     'Authorization': 'Bearer %s' % self.token
                                 },
                                 json={
                                     'answer_id': self.answer.id
                                 })
        json_data = res.get_json()
        self.assertEqual(res.status_code, 200)
        self.assertTrue(json_data['success'])
Пример #7
0
def role_uri():
    args = request.args
    args = request.get_json()

    if args is None:
        response = create_error('missing_argument')
        return (response, 404)

    role_id = args.get('id')
    if request.method == 'GET':
        try:
            role = query.get_role_by_id(role_id)

            if role:
                return get_json('role', role)
            else:
                response = create_error('role_not_found')
                return (response, 404)

        except Exception as e:
            response = create_error('unexpected_error', e)
            return (response, 500)

    elif request.method == 'PUT':
        try:
            name = args.get('name')
            description = args.get('description')
            group_ids = args.get('groups')

            # Update the role with the provided info
            if role_id:
                role = query.get_role_by_id(role_id)
                if role:
                    if query.does_role_name_exist(name):
                        response = create_error('name_taken')
                        return (response, 400)

                    if name:
                        role.name = name
                    if description:
                        role.description = description

                    if group_ids:
                        groups = get_groups_with_ids(group_ids)
                        role.groups = groups

                    is_updated = query.update_role(role)
                    if is_updated:
                        return (get_json('role', role), 200)

                    response = create_error('unexpected_error')
                    return (response, 500)
                else:
                    response = create_error('role_not_found')
                    return (response, 404)
            # Insert the new role, when it doesn't exist
            else:
                # Check for required arguments

                if query.does_role_name_exist(name):
                    response = create_error('email_taken')
                    return (response, 400)
                elif name:
                    groups = get_groups_with_ids(group_ids)
                    role = Role(name=name, description=description)
                    role.groups = groups
                    is_added = query.add_role(role)
                    if is_added:
                        response = get_json('role', role)
                        return (response, 200)
                    else:
                        raise Exception('Database operation failed: %s' %
                                        'add into employee table')

                else:
                    response = create_error('missing_argument')
                    return (response, 400)

        except Exception as e:
            print(e)
            response = create_error('unexpected_error', e)
            return (response, 500)

    elif request.method == 'DELETE':
        # role = query.get_role_by_id(role_id)
        print(role_id)
        try:
            if role_id:
                for x in role_id:
                    query.remove_role(role_id[0])
                return (json.dumps({}), 200)
            else:
                response = create_error('role_not_found')
                return (response, 404)
        except Exception as e:
            response = create_error('unexpected_error', e)
            return (response, 500)
Пример #8
0
def role2model(role: RoleIn, model: Role = None) -> Role:
    result = model if model else Role()
    result.name = role.name
    return result
Пример #9
0
print('Count User before truncate: ', count_user)
#Truncate table User
User.objects.all().delete()
count_user = User.objects.all().count()
print('Count User after truncate: ', count_user)

print('Truncating roles...')
#Truncate table Roles
count_role = Role.objects.all().count()
print('Count Role before truncate: ', count_role)
Role.objects.all().delete()
count_role = Role.objects.all().count()
print('Count Role before truncate: ', count_role)

#Create Roles
role_admin = Role()
role_admin.name = 'Admin'
role_admin.status = 'Active'
role_admin.save()

role_client = Role()
role_client.name = 'Client'
role_client.status = 'Active'
role_client.save()

role_worker = Role()
role_worker.name = 'Worker'
role_worker.status = 'Active'
role_worker.save()

role_fake = Role()