예제 #1
0
    def put(self, *args, **kwargs):
        """Modifies user in the system
        input_json = {
            'name': 'Max',
            'login': '******',
            'password': '******',
            'email': '*****@*****.**',
            'gender': 0
        }"""
        self.validate_url_params(kwargs)

        # incoming data check scheme
        validate = Schema({
            Optional('name'):
            All(Length(min=2, max=32, msg='`name` length is not enough')),
            Optional('password'):
            All(Length(min=6, max=32, msg='`password` length is not enough')),
            Optional('email'):
            All(Email(msg='`email` did not pass validation')),
            Optional('gender'):
            All(In([0, 1], msg='`gender` have to be defined correctly'))
        })

        data = json_decode(self.request.body)
        validate(data)

        if data.get('email'):
            raise M2Error('You are not allowed to change `login`', True)

        if 'id' in kwargs.keys():
            # edit info by user id
            user = User.load_by_pk(kwargs['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (kwargs['id'], kwargs['access_token']))
        else:
            # edit self info
            user = User.load_by_pk(self.current_user['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (self.current_user['id'],
                       self.current_user['access_token']))

        if 'password' in data.keys():
            password = data.pop('password')
            data['password'] = func.crypt(
                password, func.gen_salt('bf', options.gen_salt))
        user.set(**data)
        user.save()

        self.write_json(code=http_statuses['CREATED']['code'],
                        msg=http_statuses['CREATED']['msg'])
예제 #2
0
    def test_01_user_create(self):
        user = User.load_by_params(email=options.test_email)
        # drop test user from DB if it exists
        if user:
            user.delete()

        for i in range(1, test_data.users_count + 1):
            # create users, first one will be admin
            email = '*****@*****.**' % DataHelper.random_char(6)
            result = self.fetch_data({
                'method':
                'POST',
                'url':
                '%s/users' % domain_name,
                'codes': [
                    http_statuses['CREATED']['code'],
                ],
                'data': {
                    'name':
                    options.test_username
                    if i == 1 else options.test_username + ' %s' % i,
                    'password':
                    options.test_password,
                    'email':
                    options.test_email if i == 1 else email,
                    'gender':
                    0
                }
            })
            data = json_decode(result)['data']
            if i != 1:
                test_data.test_users.append(data['id'])

                result1 = self.fetch_data({
                    'method':
                    'POST',
                    'url':
                    '%s/users/login' % domain_name,
                    'codes': [
                        http_statuses['OK']['code'],
                    ],
                    'data': {
                        'email': email,
                        'password': options.test_password,
                    }
                })
                at = json_decode(result1)['data']['access_token']
                print('at: %s %s' % (data['id'], at))

        user = User.load_by_params(email=options.test_email)
        user.add_role(options.admin_role_name)

        self.report_completed('test_01_user_create')
예제 #3
0
    def post(self):
        """Authorizes user by email+pass, gets token, expire and user info in return
        input_json = {
            'email': '*****@*****.**',
            'password': '******'
        }"""
        # data validation scheme
        validate = Schema({
            Required('email'):
            All(Email(msg='`email` did not pass validation')),
            Required('password'):
            All(Length(min=6, max=32, msg='`password` length is not enough')),
        })

        data = json_decode(self.request.body)
        validate(data)

        access_token = User.authorize(data['email'], data['password'])

        if access_token:
            self.write_json(code=http_statuses['OK']['code'],
                            msg=http_statuses['OK']['msg'],
                            data=access_token)
        else:
            self.write_json(
                code=http_statuses['WRONG_CREDENTIALS']['code'],
                msg=http_statuses['WRONG_CREDENTIALS']['msg'],
            )
예제 #4
0
 def test_00_base_model(self):
     # test auto modification of updated field from CreatedMixin
     modified_user = User.load_or_create(email='*****@*****.**', gender=0)
     updated_date = modified_user.get('updated')
     modified_user.save()
     self.assertNotEqual(updated_date,
                         modified_user.get('updated'),
                         msg='`updated` filed didn\'t update on save()')
     modified_user.delete()
     self.report_completed('test_00_base_model')
예제 #5
0
    def get(self, *args, **kwargs):
        """Get concrete user info by id or return info of your own"""
        self.validate_url_params(kwargs)

        if 'id' in kwargs.keys():
            # for admin handler - return info about every user with `id`
            user = User.load_by_pk(kwargs['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (kwargs['id'], kwargs['access_token']))
        else:
            # id not specified - means request has come from non-admin handler and we simply return self info
            user = User.load_by_pk(self.current_user['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (self.current_user['id'],
                       self.current_user['access_token']))
        self.write_json(data=user.data('password'))
예제 #6
0
    def delete(self, *args, **kwargs):
        """Deletes user from DB"""
        self.validate_url_params(kwargs)

        if 'id' in kwargs.keys():
            # delete user by id
            user = User.load_by_pk(kwargs['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (kwargs['id'], kwargs['access_token']))
        else:
            # delete self account
            user = User.load_by_pk(self.current_user['id'])
            if not user:
                raise M2Error(
                    'User [%s] with access token [%s] could not be found in DB'
                    % (self.current_user['id'],
                       self.current_user['access_token']))

        user.delete()

        self.write_json(code=http_statuses['OK']['code'],
                        msg=http_statuses['OK']['msg'])
예제 #7
0
    def post(self, *args, **kwargs):
        """Creates new user, input JSON has to be like:
        input_json = {
            'name': 'Max',
            'login': '******',
            'password': '******',
            'email': '*****@*****.**',
            'gender': 0
        }"""
        # incoming data check scheme
        validate = Schema({
            Required('name'):
            All(Length(min=2, max=32, msg='`name` length is not enough')),
            Required('password'):
            All(Length(min=6, max=32, msg='`password` length is not enough')),
            Required('email'):
            All(Email(msg='`email` did not pass validation')),
            Required('gender'):
            All(In([0, 1], msg='`gender` have to be defined correctly'))
        })

        data = json_decode(self.request.body)
        validate(data)

        password = data.pop('password')
        # data['password'] = func.crypt(password, func.gen_salt('bf', options.gen_salt))
        bytes_hash = bcrypt.hashpw(str.encode(password),
                                   bcrypt.gensalt(rounds=options.gen_salt))
        data['password'] = bytes_hash.decode()
        user = User.create(**data)

        # add default role
        user.add_role(options.default_role_name)

        self.write_json(code=http_statuses['CREATED']['code'],
                        msg=http_statuses['CREATED']['msg'],
                        data={'id': user.get('id')})
예제 #8
0
 def create(self, request):
     user = User(name=request.form["name"],
                 password=request.form["password"])
     self.session.add(user)
     self.session.commit()
     return http.JsonResponse(user.as_dict())
예제 #9
0
파일: schema.py 프로젝트: idesyatov/m2core
 def get(self, *args, **kwargs):
     """Generates JSON-scheme of DB models"""
     data = User.schema(True)
     self.write_json(data=data)
예제 #10
0
def db():
    try:
        User.create_table()
        Message.create_table()
    except Exception:
        pass