Пример #1
0
    def get(self):
        schema = UserSchema(many=True)

        args = request.args
        page_id = int(args["page"]) if args.get("page") else 1
        page_size = int(args["page_size"]) if args.get("page_size") and args.get("page_size") < 1 \
                else 10

        try:

            users = User.objects()
            count = users.count()
            if count == 0:
                return resp_does_not_exist_resources("User", "usuário")

            if count <= ((page_id-1)*page_size):
                page_id = ceil(count/page_size)
            users = users.paginate(page_id, page_size)

        except FieldDoesNotExist as e:
            return resp_exception("Users", description=e.__str__()+"field")

        except Exception as e:
            return resp_exception("Users", description=e.__str__())

        extra = {
            "page": users.page, "pages": users.pages, "total": users.total, 
            "params": {"page_size":page_size}
        }

        result = schema.dump(users.items)
        return resp_ok(
                "Users", MSG_RESOURCE_FETCHED_PAGINATED.format("Usuários"), result, **extra)
Пример #2
0
    def post(self, *args, **kwargs):
        """
        Rota para login na API
        """
        req_data = request.get_json() or None
        user = None
        login_schema = LoginSchema()
        user_schema = UserSchema(exclude=["address"])

        if req_data is None:
            return resp_data_invalid("Users", [], msg=MSG_NO_DATA)

        try:
            data = login_schema.load(req_data)

        except MarshmallowValidationError as e:
            return resp_data_invalid("Users", desc=e.__str__())

        user = get_user_by_user_name(data["user_name"])
        if not isinstance(user, User):
            return user

        if checkpw(
                data.get("password").encode("utf-8"),
                user.password.encode("utf-8")):
            extras = {
                "token": create_access_token(identity=user.user_name),
                "refresh": create_refresh_token(identity=user.user_name)
            }

            result = user_schema.dump(user)

            return resp_ok("Auth", MSG_TOKEN_CREATED, data=result, **extras)

        return resp_notallowed_user("Auth")
Пример #3
0
    def get(username):
        schema = UserSchema()
        user = get_user_by_user_name(username)
        if not isinstance(user, User):
            return user

        result = schema.dump(user)

        return resp_ok("Users",
                       MSG_RESOURCE_FETCHED.format("Usuário",
                                                   username), result)
Пример #4
0
    def post(self, *args, **kwargs):
        '''
        Route to do login in API
        '''
        req_data = request.get_json() or None
        user = None
        login_schema = LoginSchema()
        schema = UserSchema()

        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        data, errors = login_schema.load(req_data)

        if errors:
            return resp_data_invalid('Users', errors)

        # Buscamos nosso usuário pelo email
        user = get_user_by_email(data.get('email'))

        # Em caso de exceção ou não é uma instancia do Modelo de User
        # retornamos a resposta
        if not isinstance(user, User):
            return user

        # Verificamos se o usuário está ativo na plataforma. Se não ele
        # não podera autenticar e não ter acesso a nada
        if not user.is_active():
            return resp_notallowed_user('Auth')

        # Conferimos a senha informada no payload de dados com a senha cadastrada
        # em nosso banco.
        if checkpw(
                data.get('password').encode('utf-8'),
                user.password.encode('utf-8')):

            # Chamamos os metodos para criar os tokens passando como identidade
            # o email do nosso usuario
            extras = {
                'token': create_access_token(identity=user.email),
                'refresh': create_refresh_token(identity=user.email)
            }

            result = schema.dump(user)

            return resp_ok('Auth',
                           MSG_TOKEN_CREATED,
                           data=result.data,
                           **extras)

        return resp_notallowed_user('Auth')
Пример #5
0
class DoctorController(Resource):

    schema = UserSchema()   
    def get(self, *args, **kwargs):

        id = kwargs.get('id', None)
        if id == None:
            print('resource::userController::get::id::None')
        else:
            print('resource::userController::get::id::'+str(id))

        return {'resource': 'userController::get::'}, 200    

    def post(self, *args, **kwargs):

        print('resource::userController::post::'+str(request.get_json()))
        req_data = request.get_json() or None        
        result = self.schema.load(req_data)
        user = result.dump()
        print(result)
        return req_data, 201

    def put(self, *args, **kwargs):

        print('resource::userController::put::'+str(request.get_json()))
        req_data = request.get_json() or None        
        return req_data, 200

    def delete(self, id):

        print('resource::userController::delete::'+str(id))
        return {'id': id}, 200    
Пример #6
0
    def put(self, *args, **kwargs):

        print('resource::userController::put::'+str(request.get_json()))
        req_data = request.get_json() or None   
        result = UserSchema().load(req_data)
        response = self.service.put(result)     
        return req_data, 200
Пример #7
0
    def delete(username):
        schema = UserSchema()
        user = get_user_by_user_name(username)
        if not isinstance(user, User):
            return user

        user.delete()

        return resp_ok_no_content()
Пример #8
0
    def post(self, *args, **kwargs):
        payload = request.get_json() or None

        login_schema = LoginSchema()
        schema = UserSchema()

        if payload is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        try:
            data = login_schema.load(payload)
        except ValidationError as error:
            return resp_data_invalid('Users', error.messages)

        user = get_user_by_email(data.get('email'))

        # if not instance of User return response error
        if not isinstance(user, User):
            log.info('%s failed to log in, email not found', data.get('email'))
            return user

        if not user.is_active:
            log.info('%s failed to log in, inactive user', user.email)
            return resp_notallowed_user('Auth')

        # trick for test pass
        password = user.password
        if isinstance(password, str):
            password = password.encode('utf-8')

        if checkpw(data.get('password').encode('utf-8'), password):

            extras = {
                'token': create_access_token(identity=user.email),
                'refresh': create_refresh_token(identity=user.email)
            }

            result = schema.dump(user)
            log.info('%s logged in successfully', user.email)
            return resp_ok('Auth', MSG_TOKEN_CREATED, data=result, **extras)

        log.info('%s failed to log in', user.email)
        return resp_authenticated_user('Auth')
Пример #9
0
 def put(self):
     json_data = request.get_json()
     result = UserNameUpdateSchema().load(json_data)
     if result.errors:
         return jsonify(result.errors), 403
     user = User.query.get(current_identity.id)
     parse_json_to_object(user, result.data)
     db.session.add(user)
     db.session.commit()
     result = UserSchema().dump(user)
     return jsonify(result.data)
Пример #10
0
    def put(self, username):
        schema = UserSchema()
        up_schema = UserUpdateSchema()
        req_data = request.get_json() or None

        user = get_user_by_user_name(username)
        if not isinstance(user, User):
            return user

        try:
            user_up = up_schema.load(req_data, unknown=EXCLUDE)
        except MarshmallowValidationError as e:
            return resp_data_invalid("Users", e.messages)

        if user_up.get("user_name") and user_up.get("user_name") != username:
            return resp_data_invalid("Users",
                                     {"user_name": user_up.get("user_name")},
                                     "Nao pode alterar o nome de usuário")

        try:
            for k, v in user_up.items():
                if k == "address":
                    for k_addr, v_addr in v.items():
                        user["address"][k_addr] = v_addr
                else:
                    user[k] = v

        except Exception as e:
            return resp_exception("Users-Aqui", description=e.__str__())

        save_result = save_model(user, "Users", "Usuário")
        if not isinstance(save_result, User):
            return save_result

        result = schema.dump(save_result)

        return resp_ok("Users",
                       MSG_RESOURCE_UPDATED.format("Usuário", username),
                       data=result)
Пример #11
0
    def post(self, *args, **kwargs):

        req_data = request.get_json() or None
        user = None
        login_schema = LoginSchema()
        schema = UserSchema()

        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        data, errors = login_schema.load(req_data)

        if errors:
            return resp_data_invalid('Users', errors)

        user = get_user_by_email(data.get('email'))

        if not isinstance(user, User):
            return user

        if not user.is_active():
            return resp_notallowed_user('Auth')

        if checkpw(
                data.get('senha').encode('utf-8'), user.senha.encode('utf-8')):

            extras = {
                'token': create_access_token(identity=user.email),
                'refresh': create_refresh_token(identity=user.email)
            }

            result = schema.dump(user)

            return resp_ok('Auth',
                           MSG_TOKEN_CREATED,
                           data=result.data,
                           **extras)

        return resp_notallowed_user('Auth')
Пример #12
0
    def get(self):
        data = UserSchema().dump(current_identity).data

        args = request.args
        if args.get('all') == 'true':
            invited_projects_ids = current_identity \
                .invited_projects.with_entities(Project.id)
            projects = Project.query.filter(
                Project.is_deleted.is_(False)).filter(
                    or_(Project.id.in_(invited_projects_ids),
                        Project.owner_id == current_identity.id))
            projects_data = ProjectSchemaAll(many=True).dump(projects).data
            data['projects'] = projects_data

        return jsonify(data)
Пример #13
0
    def post(self, *args, **kwargs):
        req_data = request.get_json() or None
        data, erros, result = None, None, None
        password, confirm_password = None, None
        schema = UserRegistrationSchema()

        if req_data is None:
            return resp_data_invalid("Users", [], msg=MSG_NO_DATA)

        password = req_data.get("password")
        confirm_password = req_data.pop("confirm_password")

        if not check_password_in_signup(password, confirm_password):
            errors = {"password": MSG_CHECK_PASSWORD_FAILED}
            return resp_data_invalid("Users", errors)

        try:
            data = schema.load(req_data)

        except MarshmallowValidationError as e:
            return resp_data_invalid("Users", e.messages)

        hashed = hashpw(password.encode("utf-8"), gensalt(12)).decode("utf-8")

        data["password"] = hashed
        data["email"] = data["email"].lower()
        model = User(**data)
        print(data)
        save_result = save_model(model, "Users", "Usuário")
        if not isinstance(save_result, User):
            return save_result

        schema = UserSchema()
        result = schema.dump(model)

        return resp_ok("Users",
                       MSG_RESOURCE_CREATED.format("Usuário"),
                       data=result)
Пример #14
0
def register_user(payload):
    if payload is None:
        return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

    schema = UserRegistrationSchema()

    try:
        data = schema.load(payload)
    except ValidationError as error:
        return resp_data_invalid('Users', error.messages)

    password = payload.get('password', None)
    data['password'] = hashpw(password.encode('utf-8'), gensalt(12))
    data['email'] = data['email'].lower()
    try:
        full_name, password, email = data['full_name'], data['password'], data[
            'email']
        user = User(full_name=full_name, password=password, email=email)
        save_changes(user)

    except IntegrityError:
        return resp_already_exists('Users', "usuário")

    except Exception as e:
        return resp_exception('Users', description=e)

    schema = UserSchema()
    result = schema.dump(user)

    extras = {
        'token': create_access_token(identity=email),
        'refresh': create_refresh_token(identity=email)
    }

    return resp_ok('Users',
                   MSG_RESOURCE_CREATED.format('Usuário'),
                   data=result,
                   **extras)
Пример #15
0
 def get(self):
     result = UserSchema().dump(current_identity)
     return jsonify(result.data)