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

时间:2017-04-10 19:54:10

标签: parse-server

我需要获取与我的解析服务器中每个用户相对应的特定类(比如A类)记录,当使用admin角色查询时,可以访问该特定类中的所有记录(A类)。

我该怎么做?

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

1 个答案:

答案 0 :(得分:1)

我假设你想在客户端上记录这些记录,但是客户端没有“权限”来获取所有类的记录?

如果我的问题正确,那么这是一个解决方案。创建一个云代码函数,可以使用主密钥查询类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);
  });
});
相关问题