| 1 | import { type Database, schema } from '@ghost/db'; |
| 2 | import { Inject, Injectable |
| 3 | import { ConfigService } |
| 4 | import { eq } |
| 5 | |
| 6 | import { DATABASE } |
| 7 | import { |
| 8 | CouldNotResolveError, |
| 9 | RequiresAuthenticationError, |
| 10 | } from '../../../lib/github/github.errors.js'; |
| 11 | import { githubOrigins } |
| 12 | import { toUserRest } |
| 13 | import type { SshKeyDTO |
| 14 | import { SshKeysService } |
| 15 | import { UsersService } |
| 16 | import type { GithubViewer |
| 17 | import { requireScope } |
| 18 | import type { GithubAddKeyDTO |
| 19 | |
| 20 | /** GitHub's REST users and the authenticated user's SSH keys. */ |
| 21 | @Injectable() |
| 22 | export class GithubUsersService |
| 23 | constructor( |
| 24 | @Inject(DATABASE) |
| 25 | private readonly users |
| 26 | private readonly config |
| 27 | private readonly sshKeys |
| 28 | ) {} |
| 29 | |
| 30 | async me(viewer |
| 31 | if (!viewer) |
| 32 | const user = |
| 33 | return { ...this |
| 34 | } |
| 35 | |
| 36 | /** A user, or else an organization, by login. */ |
| 37 | async byLogin(login |
| 38 | const [user] |
| 39 | .select() |
| 40 | .from(schema.user |
| 41 | .where(eq(schema |
| 42 | if (user) return |
| 43 | const [organization] |
| 44 | .select() |
| 45 | .from(schema.organization |
| 46 | .where(eq(schema |
| 47 | if (!organization) |
| 48 | throw new CouldNotResolveError( |
| 49 | `Could not resolve to a User or Organization with the login of '${login}'.` |
| 50 | ); |
| 51 | return { |
| 52 | ...toUserRest( |
| 53 | { |
| 54 | ghostId: organization.id |
| 55 | numericId: organization.numericId |
| 56 | login: organization.slug |
| 57 | avatarUrl: organization.logo |
| 58 | }, |
| 59 | githubOrigins(this.config |
| 60 | 'Organization', |
| 61 | ), |
| 62 | name: organization.name |
| 63 | created_at: organization.createdAt |
| 64 | }; |
| 65 | } |
| 66 | |
| 67 | async keys(viewer |
| 68 | if (!viewer) |
| 69 | requireScope(viewer, ' |
| 70 | const { keys |
| 71 | return keys.map |
| 72 | } |
| 73 | |
| 74 | async addKey(viewer |
| 75 | if (!viewer) |
| 76 | requireScope(viewer, ' |
| 77 | return this.restKey |
| 78 | await this.sshKeys |
| 79 | viewer.userId, |
| 80 | body.key, |
| 81 | body.title, |
| 82 | viewer.oauthClientId, |
| 83 | ), |
| 84 | ); |
| 85 | } |
| 86 | |
| 87 | private restKey(key |
| 88 | return { |
| 89 | id: null, |
| 90 | key: key.publicKey |
| 91 | title: key.title |
| 92 | created_at: key.createdAt |
| 93 | read_only: false, |
| 94 | verified: true, |
| 95 | }; |
| 96 | } |
| 97 | |
| 98 | private restUser(user |
| 99 | return { |
| 100 | ...toUserRest( |
| 101 | { |
| 102 | ghostId: user.id |
| 103 | numericId: user.numericId |
| 104 | login: user.username |
| 105 | avatarUrl: user.image |
| 106 | }, |
| 107 | githubOrigins(this.config |
| 108 | ), |
| 109 | name: user.name |
| 110 | created_at: user.createdAt |
| 111 | updated_at: user.updatedAt |
| 112 | }; |
| 113 | } |
| 114 | } |