|
3 | 3 | * SPDX-License-Identifier: GPL-3.0-or-later |
4 | 4 | */ |
5 | 5 | import { getBuilder } from '@nextcloud/browser-storage' |
| 6 | +import { NextcloudUser } from './user' |
| 7 | +import { emit } from '@nextcloud/event-bus' |
6 | 8 |
|
7 | 9 | const browserStorage = getBuilder('public').persist().build() |
8 | 10 |
|
| 11 | +class GuestUser implements NextcloudUser { |
| 12 | + |
| 13 | + private _displayName: string | null |
| 14 | + readonly uid: string |
| 15 | + readonly isAdmin: boolean |
| 16 | + |
| 17 | + constructor() { |
| 18 | + if (!browserStorage.getItem('guestUid')) { |
| 19 | + browserStorage.setItem('guestUid', self.crypto.randomUUID()) |
| 20 | + } |
| 21 | + |
| 22 | + this._displayName = browserStorage.getItem('guestNickname') || '' |
| 23 | + this.uid = browserStorage.getItem('guestUid') || self.crypto.randomUUID() |
| 24 | + this.isAdmin = false |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + get displayName(): string | null { |
| 29 | + return this._displayName |
| 30 | + } |
| 31 | + |
| 32 | + set displayName(displayName: string) { |
| 33 | + this._displayName = displayName |
| 34 | + browserStorage.setItem('guestNickname', displayName) |
| 35 | + emit('user:info:changed', this) |
| 36 | + } |
| 37 | + |
| 38 | +} |
| 39 | + |
| 40 | +let currentUser: GuestUser | undefined |
| 41 | + |
| 42 | +/** |
| 43 | + * Get the currently Guest user or null if not logged in |
| 44 | + */ |
| 45 | +export function getGuestUser(): GuestUser { |
| 46 | + if (!currentUser) { |
| 47 | + currentUser = new GuestUser() |
| 48 | + } |
| 49 | + |
| 50 | + return currentUser |
| 51 | +} |
| 52 | + |
9 | 53 | /** |
10 | 54 | * Get the guest nickname for public pages |
11 | 55 | */ |
12 | 56 | export function getGuestNickname(): string | null { |
13 | | - return browserStorage.getItem('guestNickname') |
| 57 | + return getGuestUser()?.displayName || null |
14 | 58 | } |
15 | 59 |
|
16 | 60 | /** |
17 | 61 | * Set the guest nickname for public pages |
18 | 62 | * @param nickname The nickname to set |
19 | 63 | */ |
20 | 64 | export function setGuestNickname(nickname: string): void { |
21 | | - browserStorage.setItem('guestNickname', nickname) |
| 65 | + if (!nickname || nickname.trim().length === 0) { |
| 66 | + throw new Error('Nickname cannot be empty') |
| 67 | + } |
| 68 | + |
| 69 | + getGuestUser().displayName = nickname |
22 | 70 | } |
0 commit comments