Access to Meteor.userId from outside the method / post

I am currently writing a server package for Meteor, and the corresponding code looks something like this:

__meteor_bootstrap__.app.stack.unshift({ route: route_final, handle: function (req,res, next) { res.writeHead(200, {'Content-Type': 'text/json'}); res.end("Print current user here"); return; }.future () }); 

This is obviously a relatively hacky way to do something, but I need to create a RESTful API.

How can I access Meteor.userId() from here? Documents say access to it is possible only from a method or publication. Is there any way around this?

Things I tried:

  • Grab it from the publication using Meteor.publish("user", function() { user = this.userId() });
  • Get the token + user ID from cookies and authenticate it yourself using something like Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
  • Create a method called get_user_id and call it from my code below.
+1
source share
2 answers

What you need to migrate is to get what can identify the user from the headers (especially because you want to get the username at the point where javascript cannot work).

Meteor stores session data for entering localStorage , which can only be accessed through javascript. Therefore, he cannot verify who signed up until the page was loaded and the headers were transferred.

To do this, you also need to save the user data as a cookie, as well as on localStorage :

client side js - using setCookie and getCookie from w3schools.com

 Deps.autorun(function() { if(Accounts.loginServicesConfigured() && Meteor.userId()) { setCookie("meteor_userid",Meteor.userId(),30); setCookie("meteor_logintoken",localStorage.getItem("Meteor.loginToken"),30); } }); 

server route

 handle: function (req,res, next) { //Parse cookies using get_cookies function from : http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server var userId = get_cookies(req)['meteor_usserid']; var loginToken = get_cookies(req)['meteor_logintoken']; var user = Meteor.users.findOne({_id:userId, "services.resume.loginTokens.token":loginToken}); var loggedInUser = (user)?user.username : "Not logged in"; res.writeHead(200, {'Content-Type': 'text/json'}); res.end("Print current user here - " + loggedInUser) return; }.future () 

A cookie allows the server to check who is logged in before the page is displayed. It is installed as soon as the user is logged in using Deps.autorun

+2
source

My solution was inspired by the server side of the @Akshat method. Since I am creating a RESTful API, I just pass userId / loginToken every time (either as a parameter, cookie or header).

For everyone who is interested, I bundled it as a package: https://github.com/gkoberger/meteor-reststop

0
source

Source: https://habr.com/ru/post/980338/


All Articles