Meteor.user() on iron-router server side

前端 未结 2 2031
余生分开走
余生分开走 2021-01-04 21:28

How can check, on server side route, if user is logged?

I would add check on \'before\', but Metor.user() don\'t work here.

thanks in advance.

p.s. I

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 21:42

    If what you're looking to do is to authenticate the Meteor.user making the request, I'm currently doing this within the context of IronRouter.route(). The request must be made with a valid user ID and auth token in the header. I call this function from within Router.route(), which then gives me access to this.user:

    ###
      Verify the request is being made by an actively logged in user
      @context: IronRouter.Router.route()
    ###
    authenticate = ->
      # Get the auth info from header
      userId = this.request.headers['x-user-id']
      loginToken = this.request.headers['x-auth-token']
    
      # Get the user from the database
      if userId and loginToken
        user = Meteor.users.findOne {'_id': userId, 'services.resume.loginTokens.token': loginToken}
    
      # Return an error if the login token does not match any belonging to the user
      if not user
        respond.call this, {success: false, message: "You must be logged in to do this."}, 401
    
      # Attach the user to the context so they can be accessed at this.user within route
      this.user = user
    
      ###
        Respond to an HTTP request
        @context: IronRouter.Router.route()
      ###
      respond = (body, statusCode=200, headers={'Content-Type':'text/json'}) ->
        this.response.writeHead statusCode, headers
        this.response.write(JSON.stringify(body))
        this.response.end()
    

    This code was heavily inspired by RestStop and RestStop2. It's part of a meteor package for writing REST APIs in Meteor 0.9.0+ (built on top of Iron Router). You can check out the complete source code here:

    https://github.com/krose72205/meteor-restivus

提交回复
热议问题