Ayeye Brazo
Ayeye Brazo

Reputation: 3476

Meteor, React, authentication and authorization issues

I'm building a small app using Meteor and React. I'm not using the awesome Meteor accounts library to handle user authentication because I need to consume an external API.

Basically the server side of Meteor is used as a Proxy to communicate with the API.

I created the authentication from Meteor to the API:

Meteor.methods({
  'user.authentication': function (email, password) {   
    try {
      const res = request.postSync(authenticate, {
        method: 'POST',
        json: true,
        body: {
          email, password
        }
      });

      if (res.response.statusCode === 200) {
        return res.body;
      }

      throw new Meteor.Error(res.response.statusCode, res.response.body.error.message);
    } catch (err) {
      throw new Meteor.Error(400, err.message);
    }
  }
});

This is working fine... The Login Components send and receive the successful data an what I'm trying to do to "save" the user session is using Meteor Session:

Login.js:

onSubmit(e) {
  e.preventDefault();

  const email = this.refs.email.value.trim();
  const password = this.refs.password.value.trim();

  Meteor.call('user.authentication', email, password, (error, res) => {
    if (error) {
      console.error(error.reason);
    } else {
      Session.set({
        user_id: res.response.user_id,
        token: res.response.token
      });
      history.push('/account');
    }
  });

}

Unfortunately I don't see the session values correctly saved, so I can not create controls to redirect authenticated or unauthenticated users to the correct pages...

I don't know if my approach is the correct one... I would like to know what I'm doing wrong and in case if there is a better solution to handle it.

For example I don't like to save token and user_id in the client, I would like to save it server side like Meteor do for his user collection and be able handling all my API request without passing token every time...

Upvotes: 0

Views: 227

Answers (1)

Jankapunkt
Jankapunkt

Reputation: 8413

Unfortunately I don't see the session values correctly saved, so I can not create controls to redirect authenticated or unauthenticated users to the correct pages...

Meteor Session requires a key-value pair.

Therefore you may rather try:

Session.set("userAuth",{
    user_id: res.response.user_id,
    token: res.response.token
});

or

Session.set("userId", res.response.user_id);
Session.set("userToken",res.response.token);

For example I don't like to save token and user_id in the client, I would like to save it server side like Meteor do for his user collection and be able handling all my API request without passing token every time...

Actually Meteor stores the user token after a successful login on the client using your browser's localStorage.

Login with a Meteor app using accounts and check your localStorage ;-)

Upvotes: 1

Related Questions