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