Authorize my Railway Strapi app with Google Sheets API

jonmikkelhansenHOBBY

a year ago

I'm trying to get my Strapi app's endpoint to fetch data from my Google Sheet.

I've succesfully gotten it to work locally, but when trying to deploy to Railway, I constantly get a 404 error when trying to access my-app-name.up.railway.app/auth/google endpoint to start the authentication process.

I've tried to set up a route

module.exports = {
routes: [
{
method: 'GET',
path: '/auth/google',
handler: 'auth.redirectToGoogle',
config: {
auth: false
}
},
{
method: 'GET',
path: '/auth/google/callback',
handler: 'auth.handleGoogleCallback',
config: {
auth: false
}
}
]
};

and a controller

const { google } = require('googleapis');

module.exports = {
// Redirect to Google's OAuth 2.0 server
async redirectToGoogle(ctx) {
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLECLIENTID,
process.env.GOOGLECLIENTSECRET,
${process.env.BACKEND_URL}/api/auth/google/callback
);

// Generate a url that asks permissions for the email and profile scopes
const url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // offline access type will result in receiving a refresh token
  scope: [
    '[https://www.googleapis.com/auth/userinfo.email](https://www.googleapis.com/auth/userinfo.email)',
    '[https://www.googleapis.com/auth/userinfo.profile](https://www.googleapis.com/auth/userinfo.profile)',
  ],
});

ctx.redirect(url);

},

// Handle the OAuth 2.0 server response
async handleGoogleCallback(ctx) {
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLECLIENTID,
process.env.GOOGLECLIENTSECRET,
${process.env.BACKEND_URL}/api/auth/google/callback
);

const { code } = ctx.query;
try {
  const { tokens } = await oauth2Client.getToken(code);
  oauth2Client.setCredentials(tokens);

  // Here you would typically find or create a user in your database,
  // then create a session or token for that user and return it.
  ctx.body = { message: 'Authentication successful', tokens };
} catch (error) {
  console.error('Failed to exchange the authorization code for tokens:', error);
  ctx.body = { message: 'Authentication failed', error };
  ctx.status = 500;
}

}
};

but nothing works.

1 Replies

a year ago

I've tried to set up a route /auth/google/callback

I constantly get a 404 error when trying to access 'my-app-name.up.railway.app/auth/google'

Those are not the same paths.


Authorize my Railway Strapi app with Google Sheets API - Railway Help Station