# Add Google Login to an Express and Mongoose API

Yes. An agent adds Sign in with Google to your Express and Mongoose API with passport-google-oauth20, links accounts by verified email, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-google-login/mongoose/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the authentication the API already has. In an API laid out like hagopj13/node-express-boilerplate, `src/app.js` calls `passport.initialize()` and registers one strategy, `passport.use('jwt', jwtStrategy)` from `src/config/passport.js`, where `passport-jwt` reads a bearer token and loads the user by `payload.sub`. `src/controllers/auth.controller.js` answers `register` and `login` with `{ user, tokens }` from `tokenService.generateAuthTokens`, which signs an access JWT and a refresh JWT and stores the refresh token in the `Token` collection. `src/models/user.model.js` requires `password` with a letter-and-number rule and hashes it in a `pre('save')` hook; `isEmailVerified` defaults to false. `src/config/config.js` validates the environment with Joi and throws on a missing key, `src/routes/v1/index.js` mounts `/auth` and `/users`, and `src/docs` holds the swagger components. `package.json` pins `passport ^0.4.0`, `passport-jwt ^4.0.0` and `mongoose ^5.7.7`, and the tests are jest with supertest against a MongoDB server named by `MONGODB_URL` in `.env.example`.

The strategy is `passport-google-oauth20` 2.0.0, registered beside the JWT one as `passport.use('google', googleStrategy)`. Its options come from three new settings in `config.js`, `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` and `GOOGLE_CALLBACK_URL`, declared optional in the Joi schema so an environment without them still boots and the strategy is registered only when all three are set. The verify function, exported as `googleVerify` so it can be unit-tested without Google, receives `accessToken`, `refreshToken`, `profile` and `done`; it takes `profile.id` and the first entry of `profile.emails`, refuses a profile whose email is missing or not marked verified, finds a user by `googleId`, else by that email to link an existing account, else creates one with `name` from `profile.displayName`, `isEmailVerified: true` and no password. For that last case `password` becomes `required: function () { return !this.googleId; }`, `googleId` gets a `unique` and `sparse` index, and `isPasswordMatch` returns false when there is no password so a Google-only account cannot log in through the password route.

Two routes join `src/routes/v1/auth.route.js`. `GET /v1/auth/google` is `passport.authenticate('google', { scope: ['profile', 'email'], session: false })`, which redirects to Google. `GET /v1/auth/google/callback` runs the same strategy with `session: false` and a custom callback so a refusal becomes the API's own `401` through `ApiError` rather than passport's default, then answers with the same `{ user, tokens }` shape as `login`. The API has no session middleware, so the agent does not set `state: true`, which would need one; instead it passes a `store` to the strategy that signs a short-lived JWT with `config.jwt.secret` as the `state` parameter and verifies it on return, which `passport-oauth2` accepts in place of its session store. The swagger comments above both routes and `src/docs/components.yml` describe the redirect and the response.

Tests stay inside the repository's own suite. A unit test for `googleVerify` under `tests/unit` feeds it fake profiles: a new verified email creates a user with `isEmailVerified` true and no password, a known email links `googleId` to the existing user, and an unverified email calls `done` with an error. Integration tests in `tests/integration/auth.test.js` assert `GET /v1/auth/google` answers `302` with a `Location` on `accounts.google.com` carrying the configured client id and both scopes, and that the callback with `error=access_denied` answers `401`. In its sandbox the agent starts a MongoDB server on the address from `.env.example`, sets the three Google variables to placeholders for the test run, and runs `yarn test`, `yarn lint` and `yarn prettier`.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add Sign in with Google to this Express and Mongoose API. Read package.json, src/app.js, src/config/config.js, src/config/passport.js, src/models/user.model.js, src/services/auth.service.js, src/services/token.service.js, src/controllers/auth.controller.js, src/routes/v1/auth.route.js, src/validations/auth.validation.js, src/docs/components.yml, tests/utils/setupTestDB.js and tests/integration/auth.test.js first. Use passport-google-oauth20 registered beside the existing jwt strategy, with GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and GOOGLE_CALLBACK_URL as optional config so the app boots without them. Export the verify function and make it refuse unverified emails, link by verified email, and otherwise create a user with no password; make password required only when there is no googleId, index googleId unique and sparse, and make isPasswordMatch false without a password. Add GET /v1/auth/google and its callback with session false, answering the same user and tokens shape as login and a 401 on refusal; since there is no session, pass a state store that signs and verifies a short-lived JWT. Update the swagger comments and components. Write a unit test for the verify function and integration tests for the redirect and the refused callback, start a MongoDB server in the sandbox, run yarn test, yarn lint and yarn prettier, and open a pull request that quotes the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `package.json`, `src/config/config.js`, `.env.example`, `src/config/passport.js`, `src/app.js`, `src/models/user.model.js`, `src/controllers/auth.controller.js`, `src/routes/v1/auth.route.js`, `src/docs/components.yml` and the README's environment table, and adds `tests/unit/googleVerify.test.js` plus new cases in `tests/integration/auth.test.js`. Its description quotes the jest summary and the lint result and shows the redirect URL the first route produces with placeholder credentials.

A reviewer checks the linking rule above all: an existing account is attached to a Google identity only when Google marks the email verified, which is what stops someone with an unverified Google account from claiming a user by email. They also decide whether the callback should answer JSON, as the API's other routes do, or redirect to a frontend with the tokens, and whether the password route should keep refusing Google-only accounts or offer a reset.

The JWT strategy, every existing route and the password login are unchanged, and an environment without the three Google variables behaves exactly as before.

## Run it on every new sign-in provider

The same shape repeats for each provider: a strategy, three settings, a verify function and two routes. A handler on your own server sends this body to `POST /o/{org}/sessions` with the provider named in the prompt and the repository in `resources`, and a `request_id` that is a UUID v5 of the provider name and the repository id so a retried call returns the run already started. Each run opens one pull request, and the key's `webhook_url` receives `run.completed`.

To keep the linking rule intact, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` runs read-only with a prompt that checks any change to `src/config/passport.js` still refuses unverified emails before linking, and comments when it does not. The trigger adds the event after the prompt and fills nothing in.

## Why run it on Rush?

OAuth code is mostly glue, and the one line that matters, which emails may link to an existing account, is easy to get wrong in a way no happy-path test shows. The agent writes the verify function so it can be tested without Google, feeds it the unverified case, and runs the whole suite against a MongoDB it starts itself, keeping every command and its output in the run's record beside the pull request.

It also keeps the change additive: optional settings, a strategy registered only when they exist, and the login response the clients already parse. The pull request reads as the sequence a client follows, redirect, consent, callback, tokens, which is how a reviewer wants to check it.

## Frequently asked questions

### Does the app still start without Google credentials?

Yes. The three settings are optional in the Joi schema, and the strategy and its two routes are registered only when all three are present. A test or development environment without them runs exactly as before.

### What happens when the Google email matches an existing user?

If Google reports the email as verified, the existing user gains the `googleId` and signs in; if not, the callback answers `401`. Without that check anyone with an unverified Google account could sign in as the user who owns that address.

### Can a Google user log in with a password?

Not until they set one. A user created through Google has no password, `isPasswordMatch` answers false for them, and the password login route answers the same `401` it gives any wrong password. The reset-password route can set one later.

### Why no state: true?

The strategy's built-in state check stores the value in a session, and this API has none. The agent supplies a `store` that signs a short-lived JWT as the `state` parameter and verifies it on the callback, which `passport-oauth2` accepts in place of its session store and gives the same protection against a forged callback.

### Should the callback return JSON or redirect?

The pull request returns the same `{ user, tokens }` JSON as `login`, because every other route in the API answers JSON and the swagger docs describe it. If a browser frontend starts the flow, the one-line change is a redirect to its URL with the tokens, and the pull request says where that line is.

## More Mongoose jobs

- [Add Graceful Shutdown to an Express and Mongoose API](https://getrush.ai/run/add-graceful-shutdown/mongoose/)
- [Add Health Checks to an Express and Mongoose API](https://getrush.ai/run/add-health-checks/mongoose/)
- [Add OpenTelemetry Tracing to an Express and Mongoose API](https://getrush.ai/run/add-opentelemetry/mongoose/)

## The same job on other stacks

- [Add Google Login to a Next.js App with NextAuth.js](https://getrush.ai/run/add-google-login/next-auth/)
- [Add Google Login to an Express App with Passport](https://getrush.ai/run/add-google-login/passport/)
- [Add Google Login to a Streamlit App](https://getrush.ai/run/add-google-login/streamlit/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
