Skip to content

Error: Error sending test message to Cloud PubSub : User not authorized to perform this action. #3593

@qkrdmswl

Description

@qkrdmswl

Hi, I have an issue with gmail.users.watch() function to make system that automatically get new mail from inbox for graduate project.

The error message seems like the user that login google api does not have permissions to access pub/sub service, so I tried to check user inform like below code.

const profile = await this.gmail.users.getProfile({ userId: 'me' });
console.log(profile.data);

Through this console, I found login doesn't have any association with this problem.
And I saw someone's solution that adding 'Service Account User' permission to service account will be work. So I tried it too, but same error arose.

I'll attach my code below, so please let me know the correct solution for this.
Thank you.

@Injectable()
export class GmailService implements OnModuleInit {
  private gmail: gmail_v1.Gmail;
  private pubsubClient: PubSub;

  constructor() {}

  async setWatch() {
    const res = await this.gmail.users.watch({
      userId: 'me', 
      requestBody: {
        topicName: 'my-topic-name', 
        labelIds: ['INBOX'], 
      },
    });
    console.log('Watch set:', res.data);
  }

 
  async startListeningToPubSub() {
    try {
      const subscription = this.pubsubClient.subscription(
        'my-subscriber-name',
      ); 

      subscription.on('message', (message) =>
        this.handlePubSubMessage(message),
      );
      subscription.on('error', (error) =>
        console.error('Pub/Sub error:', error),
      );

      console.log('Pub/Sub start to receive message');
    } catch (error) {
      console.error('Pub/Sub failed to start:', error);
    }
  }

async onModuleInit() {
    const jwt = new google.auth.JWT({
      keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS, 
      scopes: [
        'https://www.googleapis.com/auth/gmail.readonly',
        'https://www.googleapis.com/auth/pubsub',
      ], 
      subject: 'my email address',
    });

    this.gmail = google.gmail({
      version: 'v1',
      auth: jwt,
    });

    const profile = await this.gmail.users.getProfile({ userId: 'me' });
    console.log(profile.data);

    this.pubsubClient = new PubSub({ projectId: 'my-project-id' });

    await this.setWatch();
    await this.startListeningToPubSub(); 
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions