2013-02-16 76 views
0

按照this answer我創建了我自己的路線,以便我可以處理文件上傳。下面是我得到了什麼:如何在自定義路線中獲取當前用戶?

var router = Connect.middleware.router(function(route) { 
    route.post('/upload', function(req, res) { 
     var filename = req.headers['x-filename']; 
     var path = Path.join('.uploads', filename); 
     var writeStream = FileSystem.createWriteStream(path); 
     writeStream.on('error', function(e) { 
      console.error(e); 
      res.writeHead(500); 
      res.end(); 
     }).on('close', function() { 
      Fiber(function() { 
       console.log(Meteor.user()); 
      }).run(); 
      res.writeHead(200); 
      res.end(); 
     }); 
     req.pipe(writeStream); 
    }); 
}); 
app.use(router); 

這個偉大的工程上傳文件,但是當我嘗試接取Meteor.user()它給了我:

app/server/main.js:24 
      }).run(); 
      ^
Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions. 
    at Object.Meteor.userId (app/packages/accounts-base/accounts_server.js:95:13) 
    at Object.Meteor.user (app/packages/accounts-base/accounts_server.js:100:25) 
    at app/server/main.js:23:36 
Exited with code: 1 

我不能看到req對象任何可能會幫助我。

有沒有什麼辦法讓訪問用戶對象?


暫時,我得到了用戶ID的客戶端,並沿使其通過頭,然後我用它來查找服務器端:

route.post('/upload', function(req, res) { 
    Fiber(function() { 
     var userId = req.headers['x-userid']; 
     var user = Meteor.users.findOne({_id:userId}); 
     if(user) { 
      ... 
     } else { 
      res.writeHead(403,'User not logged in'); 
      res.end(); 
     } 
    }).run(); 
}); 

我不喜歡這是因爲它一點都不安全。在不同用戶的帳戶下上傳內容會很容易。

編輯:沒關係。打電話給Meteor.users.findOne({_id:userId});的行爲在某種程度上破壞了上傳流。每當我放入文件時,每個文件都會腐敗;他們上傳了大約700 KB,然後停止並關閉連接,沒有錯誤。

回答

1

如果它仍然是有效的問題。

的問題是,有沒有辦法如何在這部分代碼得到Meteor.user()。

但你總是可以達到Meteor.userId ..如果用戶登錄它不是空..所以你只能上傳登錄的用戶。 (如果req.headers ['x-userid'] == Meteor.userId)

調用Meteor.users.findOne({_ id:userId});以某種方式 打破上傳流。

因爲它的反應部分..所以如果Meteor.users收集更新的這部分代碼每次被再次執行。

所以,如果你只能使用Meteor.userId(這是改變只有在輸入/輸出用戶登錄),它應該工作的罰款。

+0

是的,這個問題仍然有效:-)我認爲這可能適用於這種用例,如果我確實可以訪問'Meteor.userId',但我不確定這對於路上的任何事情都足夠靈活。 「如果Meteor.users集合已更新」 - 爲什麼要提取更新? – mpen 2013-04-19 15:50:53

1

我碰到的這個好幾次,這是令人沮喪的。我不認爲你可以從光纖內部撥打Meteor.userId()來電。在我調用光纖之前,我通常會做一個var userId = Meteor.userId();,然後引用該變量。