Search code examples
javascriptreact-nativeconnectycube

Where to put API session auth token in SDK request methods?


I am using the ConnectyCube React Native SDK and have obtained an app auth token using their API. This token is required when making further requests - for example when logging in as a user. Their documentation says:

Upgrade session token (user login)

If you have an application session token, you can upgrade it to a user session by calling login method:

var userCredentials = {login: 'cubeuser', password: 'awesomepwd'};

ConnectyCube.login(userCredentials, function(error, user) {

});

The problem is it that when I use this method, I get an error in response saying 'Token is required'.

If I were interfacing with a REST API, I would put the token in the header of the request, but obviously in this instance I can't. So the question is, where do I put the token? I have it, the documentation just doesn't tell you how to use it! Any help appreciated.


Solution

  • Ok I came up with a fix. First of all I just tried passing the auth token in to the userCredntials object in the same way as in the documentation for social auth, that is absent from the description in my above code snippet taken from their docs.

    Then I Promisified the API calls from within useEffect inside an async function to make sure everything was happening in the right order, and it works:

    export default function App() {
    
      const createAppSession = () => {
        return new Promise((resolve, reject) => {
          ConnectyCube.createSession((error, session) => {
            !error
              ? resolve(session.token)
              : reject(error, '=====1=====');
          });
        })
      }
    
      const loginUser = (credentials) => {
        return new Promise((resolve, reject) => {
          ConnectyCube.login(credentials, ((error, user) => {
            !error
              ? resolve(user)
              : reject(error, '=====2=====');
          }));
        })
      }
    
      useEffect(() => {
        const ccFunc = async () => {
          ConnectyCube.init(...config)
          const appSessionToken = await createAppSession();
          const userCredentials = { login: 'xxxxx', password: 'xxxxxxx', keys: { token: appSessionToken } };
          const user = await loginUser(userCredentials);
          console.log(user);
    
        }
        ccFunc()
      }, []);