summaryrefslogtreecommitdiffstats
path: root/apps/settings/src/store/authtoken.ts
blob: daf5583ab8c978065cb00acb84b2f6929e0b9382 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
import { showError } from '@nextcloud/dialogs'
import { loadState } from '@nextcloud/initial-state'
import { translate as t } from '@nextcloud/l10n'
import { confirmPassword } from '@nextcloud/password-confirmation'
import { generateUrl } from '@nextcloud/router'
import { defineStore } from 'pinia'

import axios from '@nextcloud/axios'
import logger from '../logger'

import '@nextcloud/password-confirmation/dist/style.css'

const BASE_URL = generateUrl('/settings/personal/authtokens')

const confirm = () => {
	return new Promise(resolve => {
		window.OC.dialogs.confirm(
			t('settings', 'Do you really want to wipe your data from this device?'),
			t('settings', 'Confirm wipe'),
			resolve,
			true,
		)
	})
}

export enum TokenType {
	TEMPORARY_TOKEN = 0,
	PERMANENT_TOKEN = 1,
	WIPING_TOKEN = 2,
}

export interface IToken {
	id: number
	canDelete: boolean
	canRename: boolean
	current?: true
	/**
	 * Last activity as UNIX timestamp (in seconds)
	 */
	lastActivity: number
	name: string
	type: TokenType
	scope: Record<string, boolean>
}

export interface ITokenResponse {
	/**
	 * The device token created
	 */
	deviceToken: IToken
	/**
	 * User who is assigned with this token
	 */
	loginName: string
	/**
	 * The token for authentication
	 */
	token: string
}

export const useAuthTokenStore = defineStore('auth-token', {
	state() {
		return {
			tokens: loadState<IToken[]>('settings', 'app_tokens', []),
		}
	},
	actions: {
		/**
		 * Update a token on server
		 * @param token Token to update
		 */
		async updateToken(token: IToken) {
			const { data } = await axios.put(`${BASE_URL}/${token.id}`, token)
			return data
		},

		/**
		 * Add a new token
		 * @param name The token name
		 */
		async addToken(name: string) {
			logger.debug('Creating a new app token')

			try {
				await confirmPassword()

				const { data } = await axios.post<ITokenResponse>(BASE_URL, { name })
				this.tokens.push(data.deviceToken)
				logger.debug('App token created')
				return data
			} catch (error) {
				return null
			}
		},

		/**
		 * Delete a given app token
		 * @param token Token to delete
		 */
		async deleteToken(token: IToken) {
			logger.debug('Deleting app token', { token })

			this.tokens = this.tokens.filter(({ id }) => id !== token.id)

			try {
				await axios.delete(`${BASE_URL}/${token.id}`)
				logger.debug('App token deleted')
				return true
			} catch (error) {
				logger.error('Could not delete app token', { error })
				showError(t('settings', 'Could not delete the app token'))
				// Restore
				this.tokens.push(token)
			}
			return false
		},

		/**
		 * Wipe a token and the connected device
		 * @param token Token to wipe
		 */
		async wipeToken(token: IToken) {
			logger.debug('Wiping app token', { token })

			try {
				await confirmPassword()

				if (!(await confirm())) {
					logger.debug('Wipe aborted by user')
					return
				}

				await axios.post(`${BASE_URL}/wipe/${token.id}`)
				logger.debug('App token marked for wipe', { token })

				token.type = TokenType.WIPING_TOKEN
				token.canRename = false // wipe tokens can not be renamed
				return true
			} catch (error) {
				logger.error('Could not wipe app token', { error })
				showError(t('settings', 'Error while wiping the device with the token'))
			}
			return false
		},

		/**
		 * Rename an existing token
		 * @param token The token to rename
		 * @param newName The new name to set
		 */
		async renameToken(token: IToken, newName: string) {
			logger.debug(`renaming app token ${token.id} from ${token.name} to '${newName}'`)

			const oldName = token.name
			token.name = newName

			try {
				await this.updateToken(token)
				logger.debug('App token name updated')
				return true
			} catch (error) {
				logger.error('Could not update app token name', { error })
				showError(t('settings', 'Error while updating device token name'))
				// Restore
				token.name = oldName
			}
			return false
		},

		/**
		 * Set scope of the token
		 * @param token Token to set scope
		 * @param scope scope to set
		 * @param value value to set
		 */
		async setTokenScope(token: IToken, scope: string, value: boolean) {
			logger.debug('Updating app token scope', { token, scope, value })

			const oldVal = token.scope[scope]
			token.scope[scope] = value

			try {
				await this.updateToken(token)
				logger.debug('app token scope updated')
				return true
			} catch (error) {
				logger.error('could not update app token scope', { error })
				showError(t('settings', 'Error while updating device token scope'))
				// Restore
				token.scope[scope] = oldVal
			}
			return false
		},
	},

})