2015-11-10 3 views
0

У меня возникли проблемы с взаимодействием с моими данными анализа в node.js. Я могу войти в систему успешно, но Parse.User.current() возвращает null. После выполнения приведенного ниже кода я хотел бы запросить данные, которые имеют чтение/запись ACL только для этого пользователя. В настоящее время этот запрос возвращает пустой, но если я изменил эти данные на общедоступное чтение/запись, я могу увидеть результаты вывода запроса в терминале.Parse Войти в node.js - Войти успешно, но «Нет текущего пользователя»

Вот мой node.js код:

Prompt.get([{ 
name: 'username', 
required: true}, { 
name: 'password', 
hidden: true}], function (err, result) { 
    if (err) { 
     console.log('Error: ' + err); 
    } else { 
     Parse.User.logIn(result.username, result.password, { 
     success: function(user) { 
      console.log('LOGGED IN'); 
      console.log(user); 
      console.log(Parse.Session.current()); 
      console.log(Parse.User.current()); 

      ... (query happens below this) 

И мой вывод консоли:

prompt: username: pablo 
prompt: password: 
LOGGED IN 
ParseUser { _objCount: 0, className: '_User', id: 'EXyg99egkv' } 
ParsePromise { 
    _resolved: false, 
    _rejected: true, 
    _resolvedCallbacks: [], 
    _rejectedCallbacks: [], 
    _error: 'There is no current user.' } 
null 

Спасибо заранее.

ответ

2

Разве это не тайна для Parse.User.become()? Из синтаксического анализа документации:

If you’ve created your own authentication routines, or otherwise logged in a user on the server side, you can now pass the session token to the client and use the become method. This method will ensure the session token is valid before setting the current user.

Parse.User.become("session-token-here").then(function (user) { 
    // The current user is now set to user. 
}, function (error) { 
    // The token could not be validated. 
}); 
+0

Прямая реализация привела к ошибке: Ошибка: Не памяти безопасно, чтобы стать пользователем в серверной среде Чтение немного больше в документации показывает: enableUnsafeCurrentUser() Включает использование стать или текущего пользователя в среде сервера. Эти функции по умолчанию отключены, поскольку они зависят от глобальных объектов, которые не являются безопасными для памяти для большинства серверов. Так что мне удалось добиться успеха, добавив Parse.User.enableUnsafeCurrentUser() перед Parse.User.become Спасибо! – Pablo

0

Я имел аналогичные проблемы и нашел это Разбирает blog, объясняющий вопрос:

Also in Cloud Code, the concept of a method that returns the current user makes sense, as it does in JavaScript on a web page, because there’s only one active request and only one user. However in a context like node.js, there can’t be a global current user, which requires explicit passing of the session token. Version 1.6 and higher of the Parse JavaScript SDK already requires this, so if you’re at that version, you’re safe in your library usage.

Вы можете выполнять запросы с учетными данными пользователя в Node.js среде как это:

query.find({ sessionToken: request.user.getSessionToken() }).then(function(data) { 
// do stuff with data 
}, function(error) { 
// do stuff with error 
}); 

Если вы хотите проверить этот токен перед его использованием, введите explanation, как вы могли бы идти об этом, что:

one way would be to query for an object known to be only readable by the user. You could have a class that stores such objects, and have each one of them use an ACL that restricts read permissions to the user itself. If running a find query over this class returns 0 objects with a given sessionToken, you know it's not valid. You can take it a step further and also compare the user object id to make sure it belongs to the right user.

Session tokens cannot be queried even with the master key.

Смежные вопросы