Beispiel #1
0
 def post(self):
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         id = user.id
         return {'id': str(id)}, 201
     except FieldDoesNotExist:
         raise SchemaValidationError
     except NotUniqueError:
         raise EmailAlreadyExistsError
     except Exception:
         raise InternalServerError
Beispiel #2
0
    def test_create_user(self):
        """ Create user in db
        Should: return save user in db """

        user = User(username='******',
                    email="*****@*****.**",
                    password="******",
                    provider="Tutubo")
        user.save()

        fresh_user = User.objects().first()
        assert fresh_user.username == 'oli'
        assert fresh_user.email == '*****@*****.**'
        assert fresh_user.password == '123'
        assert fresh_user.provider == 'Tutubo'
Beispiel #3
0
def user(*args, **kwargs):
    args = current_app.config['args']
    headers = current_app.config['headers']

    response = Response()
    route_params = request.view_args
    get_params = request.args.to_dict(flat=False)
    if request.method in ['POST', 'PUT', 'DELETE']:
        body = request.json

    message = []
    data = None
    error = None
    try:
        if request.method == 'POST':
            data = User(**body)
            data.save()
            data = data.to_mongo()
        elif request.method == 'GET':
            data = [obj.to_mongo() for obj in User.objects]
        elif request.method == 'PUT':
            _id = route_params['user_id']
            data = User.objects(id=bson.ObjectId(_id))
            for attr in [
                    'first_name', 'last_name', 'email', 'password',
                    'authorization'
            ]:
                if body.get(attr) is not None:
                    setattr(data, attr, body[attr])
            data.save()
            data = data.to_mongo()
        elif request.method == 'DELETE':
            _id = route_params['user_id']
            data = User.objects(id=bson.ObjectId(_id))
            data.delete()
        elif request.method == 'OPTIONS':
            pass
        else:
            pass

    except Exception as e:
        error = AugmentedException(e).to_dict()
        LOGGER.error('', exc_info=True)

    response = jsonify(message=message, data=data, error=error)
    response = add_headers(response, headers=headers)
    LOGGER.warning(vars(response))
    return response
Beispiel #4
0
    def post(self):
        """
        Add a new user
        """
        body = request.get_json()

        if User.find_by_username(body['username']):
            return custom_response(
                401, 'User {} already exists'.format(body['username']))

        if (body['username'] == '' or body['password'] == ''
                or body['password'] != body['confirm_password']
                or body['full_name'] == '' or body['gender'] > 1
                or body['date_of_birth'] == ''):
            return custom_response(400, "Invalid parameters")

        user = User(
            username=body['username'],
            password=User.generate_hash(body['password']),
            role=USER_ROLE['user'],
            full_name=body['full_name'],
            gender=body['gender'],
            date_of_birth=body['date_of_birth'],
        )
        try:
            user.save()
            access_token = create_access_token(identity=create_identity(user))
            refresh_token = create_refresh_token(
                identity=create_identity(user))
            return custom_response(200,
                                   'User {} was created'.format(user.username),
                                   {
                                       'access_token': access_token,
                                       'refresh_token': refresh_token
                                   })
        except:
            return custom_response(500, 'Something went wrong')