auth-backend: switch client to look up single users

This commit is contained in:
Patrik Oldsberg
2020-09-29 11:10:37 +02:00
parent f9fa53153e
commit 0fa06d9e6e
2 changed files with 36 additions and 24 deletions
@@ -16,7 +16,11 @@
import fetch from 'node-fetch';
import { UserEntity } from '@backstage/catalog-model';
import { PluginEndpointDiscovery } from '@backstage/backend-common';
import {
ConflictError,
NotFoundError,
PluginEndpointDiscovery,
} from '@backstage/backend-common';
type UserQuery = {
annotations: Record<string, string>;
@@ -32,7 +36,12 @@ export class CatalogIdentityClient {
this.discovery = options.discovery;
}
async findUser(query: UserQuery): Promise<UserEntity[]> {
/**
* Looks up a single user using a query.
*
* Throws a NotFoundError or ConflictError if 0 or multiple users are found.
*/
async findUser(query: UserQuery): Promise<UserEntity> {
const params = new URLSearchParams();
params.append('kind', 'User');
@@ -50,6 +59,16 @@ export class CatalogIdentityClient {
);
}
return response.json();
const users: UserEntity[] = await response.json();
if (users.length !== 1) {
if (users.length > 1) {
throw new ConflictError('User lookup resulted in multiple matches');
} else {
throw new NotFoundError('User not found');
}
}
return users[0];
}
}
@@ -149,35 +149,28 @@ export class GoogleAuthProvider implements OAuthHandlers {
throw new Error('Google profile contained no email');
}
const users = await this.identityClient.findUser({
annotations: {
'google.com/email': profile.email,
},
});
if (users.length !== 1) {
if (users.length > 1) {
this.logger.info(
`Multiple identities found for Google user ${profile.email}`,
);
} else {
this.logger.info(`No identity found for Google user ${profile.email}`);
}
try {
const user = await this.identityClient.findUser({
annotations: {
'google.com/email': profile.email,
},
});
return {
...response,
backstageIdentity: {
id: user.metadata.name,
},
};
} catch (error) {
this.logger.warn(
`Falling back to allowing login based on email pattern, this will probably break in the future`,
`Failed to look up user, ${error}, falling back to allowing login based on email pattern, this will probably break in the future`,
);
return {
...response,
backstageIdentity: { id: profile.email.split('@')[0] },
};
}
return {
...response,
backstageIdentity: {
id: users[0].metadata.name,
},
};
}
}