Created
December 7, 2022 10:07
-
-
Save lopinho/5e696bf7eb2aab8ef2ad96cf3d87c5e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Logger } from '@nestjs/common'; | |
import { google } from 'googleapis'; | |
import { firebaseId } from '../commons/helpers/firebase-id.function'; | |
import { AuthorizeDomainDTO } from './dtos'; | |
@Injectable() | |
export class OrganizationAuthManagementService { | |
async getAuth(): Promise<any> { | |
return new google.auth.GoogleAuth({ | |
scopes: [ | |
'https://www.googleapis.com/auth/identitytoolkit', | |
'https://www.googleapis.com/auth/cloud-platform', | |
'https://www.googleapis.com/auth/firebase', | |
], | |
}); | |
} | |
async getAuthorizedDomains({ id }: { id: string }): Promise<string[]> { | |
Logger.debug('[organization-auth-management] geting authorized domains'); | |
const url = `https://identitytoolkit.googleapis.com/admin/v2/projects/${id}/config`; | |
const client = await (await this.getAuth()).getClient(); | |
const response = await client.request({ | |
url, | |
method: 'GET', | |
}); | |
const domains = response.data.authorizedDomains; | |
Logger.debug( | |
`[organization-auth-management] AuthorizeDomains ${JSON.stringify( | |
domains, | |
)}`, | |
); | |
return domains; | |
} | |
async addDomain({ domainName, organizationId }: AuthorizeDomainDTO) { | |
Logger.debug(`[organization-auth-management] Add Domain ${domainName}`); | |
const id = firebaseId({ organizationId }); | |
const url = `https://identitytoolkit.googleapis.com/admin/v2/projects/${id}/config?updateMask=authorizedDomains`; | |
const client = await (await this.getAuth()).getClient(); | |
const authorizedDomains = await this.getAuthorizedDomains({ id }); | |
if (!authorizedDomains.includes(domainName)) { | |
authorizedDomains.push(domainName); | |
const response = await client.request({ | |
url, | |
method: 'PATCH', | |
data: { | |
authorizedDomains, | |
}, | |
}); | |
Logger.debug( | |
`[organization-auth-management] Domain ${domainName} added, domains ${JSON.stringify( | |
response.data.authorizedDomains, | |
)}`, | |
); | |
} else { | |
Logger.debug( | |
`[organization-auth-management] Domain ${domainName} alredy exists`, | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment