从有权访问所有记录的管理员 role/user 查询时,获取与用户对应的记录

Fetching records corresponding to a user, when queried from admin role/user which has access to all records

我需要获取特定的 class(比如说 Class A)记录,当使用管理员角色查询时,该记录对应于我的解析服务器中的每个用户,该角色可以访问该特定中的所有记录class (Class 个).

我该怎么做?

快速帮助将不胜感激。 :-)

我假设您想要客户端上的这些记录,但客户端没有 "permission" 来获取所有 class 条记录?

如果我解决了问题,那么这里有一个解决方案。创建一个可以使用主键查询对象的云代码功能 class a.

// this is the cloud function that you can call with
// whichever client SDK you are using....
const fetchClassA = function (request, response) {
  const result = [];
  const userId = request.params.fetchForUser;
  // the test here should be against role, just an example....
  if (request.user.get('username') !== 'admin') {
    response.error('you are not authorized.');
    return;
  }
  if (!userId) {
    response.error('no user supplied');
    return;
  }

  const user = new Parse.User();
  user.id = userId;

  new Parse.Query('ClassA')
    .equalTo('user', user)
    // depending on the use case, you may want to use 
    // find here instead?
    .each((object) => {
      result.push(object);
    }, { useMasterKey: true })
    .then(() => response.success(result))
    .catch(response.error);
}

// the rest of this is just a unit test to "lightly" test
// our cloud function....
describe('fetch record with a cloud function', () => {
  const userA = new Parse.User();
  const userB = new Parse.User();

  beforeEach((done) => {
    userA.setUsername('userA');
    userA.setPassword('abc');
    userB.setUsername('userB');
    userB.setPassword('def');
    Parse.Object.saveAll([userA, userB])
      .then(() => Parse.Object.saveAll([
        new Parse.Object('ClassA').set('user', userA),
        new Parse.Object('ClassA').set('user', userA),
        new Parse.Object('ClassA').set('user', userA),
        new Parse.Object('ClassA').set('user', userB),
        new Parse.Object('ClassA').set('user', userB),
        new Parse.Object('ClassA').set('user', userB),
      ]))
      .then(() => Parse.User.signUp('admin', 'foo'))
      .then(done)
      .catch(done.fail);
  });

  it('should fetch class a', (done) => {
    Parse.Cloud.define('fetchClassA', fetchClassA);
    Parse.Cloud.run('fetchClassA', { foo: 'bar', fetchForUser: userA.id })
      .then(result => expect(result.length).toBe(3))
      .then(done)
      .catch(done.fail);
  });
});