|
| 1 | +// |
| 2 | +// Copyright © 2025 Hardcore Engineering Inc. |
| 3 | +// |
| 4 | +// Licensed under the Eclipse Public License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. You may |
| 6 | +// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | + |
| 16 | +import { type WorkspaceLoginInfo, getClient as getAccountClient } from '@hcengineering/account-client' |
| 17 | +import { WorkspaceUuid } from '@hcengineering/core' |
| 18 | +import { AuthOptions } from './types' |
| 19 | +import { loadServerConfig, ServerConfig } from './config' |
| 20 | + |
| 21 | +export interface WorkspaceToken { |
| 22 | + endpoint: string |
| 23 | + token: string |
| 24 | + workspaceId: WorkspaceUuid |
| 25 | + info: WorkspaceLoginInfo |
| 26 | +} |
| 27 | + |
| 28 | +export async function getWorkspaceToken ( |
| 29 | + url: string, |
| 30 | + options: AuthOptions, |
| 31 | + config?: ServerConfig |
| 32 | +): Promise<WorkspaceToken> { |
| 33 | + config ??= await loadServerConfig(url) |
| 34 | + |
| 35 | + let token: string | undefined |
| 36 | + |
| 37 | + if ('token' in options) { |
| 38 | + token = options.token |
| 39 | + } else { |
| 40 | + const { email, password } = options |
| 41 | + const loginInfo = await getAccountClient(config.ACCOUNTS_URL).login(email, password) |
| 42 | + token = loginInfo.token |
| 43 | + } |
| 44 | + |
| 45 | + if (token === undefined) { |
| 46 | + throw new Error('Login failed') |
| 47 | + } |
| 48 | + |
| 49 | + const ws = await getAccountClient(config.ACCOUNTS_URL, token).selectWorkspace(options.workspace) |
| 50 | + if (ws === undefined) { |
| 51 | + throw new Error('Workspace not found') |
| 52 | + } |
| 53 | + |
| 54 | + return { endpoint: ws.endpoint, token: ws.token, workspaceId: ws.workspace, info: ws } |
| 55 | +} |
0 commit comments