Files
cloudron-box/dashboard/src/components/ProfileView.vue
T
2025-01-17 14:02:05 +01:00

317 lines
12 KiB
Vue

<template>
<div class="content">
<InputDialog ref="inputDialog" />
<Dialog ref="twoFADialog"
:title="$t('profile.enable2FA.title')">
<div style="text-align: center; max-width: 420px">
<p v-show="mandatory2FAHelp">{{ $t('profile.enable2FA.description') }}</p>
<p v-html="$t('profile.enable2FA.authenticatorAppDescription', { googleAuthenticatorPlayStoreLink: 'https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2', googleAuthenticatorITunesLink: 'https://itunes.apple.com/us/app/google-authenticator/id388497605', freeOTPPlayStoreLink: 'https://play.google.com/store/apps/details?id=org.fedorahosted.freeotp', freeOTPITunesLink: 'https://itunes.apple.com/us/app/freeotp-authenticator/id872559395'})"></p>
<img :src="twoFAQRCode" style="border-radius: 10px; margin-bottom: 10px"/>
<small>{{ twoFASecret }}</small>
<br/>
<br/>
<p class="has-error" v-show="twoFAEnableError">{{ twoFAEnableError }} </p>
<form @submit.prevent="onTwoFAEnable()">
<input type="submit" style="display: none;" :disabled="!twoFATotpToken"/>
<FormGroup>
<label for="totpTokenInput">{{ $t('profile.enable2FA.token') }}</label>
<TextInput v-model="twoFATotpToken" id="totpTokenInput" />
</FormGroup>
<Button @click="onTwoFAEnable()" :disabled="!twoFATotpToken">{{ $t('profile.enable2FA.enable') }}</Button>
</form>
</div>
</Dialog>
<Section :title="$t('profile.title')">
<template #header-buttons>
<Button @click="profileModel.logout()" icon="fa fa-sign-out">{{ $t('main.logout') }}</Button>
</template>
<div style="display: flex;">
<div style="width: 150px;">
<input type="file" ref="avatarFileInput" style="display: none" accept="image/*" @change="onAvatarChanged()"/>
<div class="settings-avatar" :style="`background-image: url('${user.avatarUrl}');`" @click="avatarFileInput.click()">
<i class="picture-edit-indicator fa fa-pencil-alt"></i>
</div>
</div>
<div style="flex-grow: 1;">
<table style="width: 100%;">
<tbody>
<tr>
<td class="text-muted">{{ $t('main.username') }}</td>
<td style="width: 100px; height: 34px;">{{ user.username }}</td>
<td style="width: 32px"></td>
</tr>
<tr>
<td class="text-muted">{{ $t('main.displayName') }}</td>
<td style="white-space: nowrap;">{{ user.displayName }}</td>
<td><Button small tool outline @click="onChangeDisplayName(user.displayName)" v-show="!user.source && !config.profileLocked" icon="fa fa-edit text-small" /></td>
</tr>
<tr>
<td class="text-muted">{{ $t('profile.primaryEmail') }}</td>
<td style="white-space: nowrap;">{{ user.email }}</td>
<td><Button small tool outline @click="onChangeEmail(user.email)" v-show="!user.source && !config.profileLocked" icon="fa fa-edit text-small" /></td>
</tr>
<tr>
<td class="text-muted">{{ $t('profile.passwordRecoveryEmail') }}</td>
<td style="white-space: nowrap;">{{ user.fallbackEmail }}</td>
<td><Button small tool outline @click="onChangeFallbackEmail(user.fallbackEmail)" v-show="!user.source && !config.profileLocked" icon="fa fa-edit text-small" /></td>
</tr>
<tr>
<td class="text-muted">{{ $t('profile.language') }}</td>
<td colspan="2" class="text-right"><Dropdown small tool outline v-model="language" :options="languages" option-label="display" option-key="id" @select="onSelectLanguage"/></td>
</tr>
<tr v-show="!user.source">
<td colspan="3" class="text-right">
<!-- <Button tool @click="onPasswordReset()">{{ $t('profile.passwordResetAction') }}</Button> -->
<Button tool @click="onPasswordChange()">{{ $t('profile.changePasswordAction') }}</Button>
<Button tool v-show="!user.source && !config.external2FA" @click="user.twoFactorAuthenticationEnabled ? onTwoFADisable() : onOpenTwoFASetupDialog()">{{ $t(user.twoFactorAuthenticationEnabled ? 'profile.disable2FAAction' : 'profile.enable2FAAction') }}</Button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</Section>
<AppPasswords/>
<ApiTokens v-show="user.isAtLeastAdmin"/>
<Section :title="$t('profile.loginTokens.title')">
<p>{{ $t('profile.loginTokens.description', { webadminTokenCount: webadminTokens.length, cliTokenCount: cliTokens.length }) }}</p>
<Button danger :loading="revokeTokensBusy" :disabled="revokeTokensBusy" @click="onRevokeAllWebAndCliTokens()">{{ $t('profile.loginTokens.logoutAll') }}</Button>
</Section>
</div>
</template>
<script setup>
const API_ORIGIN = import.meta.env.VITE_API_ORIGIN ? import.meta.env.VITE_API_ORIGIN : window.location.origin;
import { useI18n } from 'vue-i18n';
const i18n = useI18n();
const t = i18n.t;
import { ref, onMounted, useTemplateRef } from 'vue';
import { Button, Dropdown, Dialog, InputDialog, TextInput } from 'pankow';
import { TOKEN_TYPES } from '../constants.js';
import AppPasswords from './AppPasswords.vue';
import Section from './Section.vue';
import ApiTokens from './ApiTokens.vue';
import ProfileModel from '../models/ProfileModel.js';
import CloudronModel from '../models/CloudronModel.js';
import TokensModel from '../models/TokensModel.js';
const profileModel = ProfileModel.create(API_ORIGIN, localStorage.token);
const cloudronModel = CloudronModel.create(API_ORIGIN, localStorage.token);
const tokensModel = TokensModel.create(API_ORIGIN, localStorage.token);
const config = ref({}); // TODO what is this?
const user = ref({});
const inputDialog = useTemplateRef('inputDialog');
// Language selector
const languages = ref([]);
const language = ref('');
async function onSelectLanguage(lang) {
window.localStorage.NG_TRANSLATE_LANG_KEY = lang.id;
const error = await profileModel.setLanguage(lang.id);
if (error) console.error('Failed to set language', error);
else window.location.reload();
// TODO dynamically change lange instead of reloading
}
// Profile edits
async function onChangeDisplayName(currentDisplayName) {
const displayName = await inputDialog.value.prompt({
message: t('profile.changeDisplayName.title'),
modal: false,
value: currentDisplayName,
confirmStyle: 'success',
confirmLabel: t('main.dialog.save'),
rejectLabel: t('main.dialog.cancel')
});
if (!displayName || currentDisplayName === displayName) return;
const error = await profileModel.setDisplayName(displayName);
if (error) return console.error('Failed to set displayName', error);
user.value = await profileModel.get();
}
async function onChangeEmail(currentEmail) {
const result = await inputDialog.value.prompt({
message: [ t('profile.changeEmail.title'), t('profile.changeEmail.password') ],
type: [ 'email', 'password' ],
modal: false,
value: [ currentEmail, '' ],
confirmStyle: 'success',
confirmLabel: t('main.dialog.save'),
rejectLabel: t('main.dialog.cancel')
});
if (!result || !result[0] || !result[1] || currentEmail === result[0]) return;
const error = await profileModel.setEmail(result[0], result[1]);
if (error) return console.error('Failed to set email', error);
user.value = await profileModel.get();
}
async function onChangeFallbackEmail(currentFallbackEmail) {
const result = await inputDialog.value.prompt({
message: [ t('profile.changeFallbackEmail.title'), t('profile.changeEmail.password') ],
type: [ 'email', 'password' ],
modal: false,
value: [ currentFallbackEmail, '' ],
confirmStyle: 'success',
confirmLabel: t('main.dialog.save'),
rejectLabel: t('main.dialog.cancel')
});
if (!result || !result[1] || currentFallbackEmail === result[0]) return;
const error = await profileModel.setFallbackEmail(result[0], result[1]);
if (error) return console.error('Failed to set fallback email', error);
user.value = await profileModel.get();
}
const avatarFileInput = useTemplateRef('avatarFileInput');
async function onAvatarChanged() {
if (!avatarFileInput.value.files[0]) return;
await profileModel.setAvatar(avatarFileInput.value.files[0]);
// invalidate and refresh profile avatar url
const u = new URL(user.value.avatarUrl);
u.searchParams.set('ts', Date.now());
user.value.avatarUrl = u.toString();
}
// Password changes
async function onPasswordChange() {
const result = await inputDialog.value.prompt({
message: [ t('profile.changePassword.newPassword'), t('profile.changePassword.newPasswordRepeat'), t('profile.changePassword.currentPassword') ],
type: [ 'password', 'password', 'password' ],
modal: false,
confirmStyle: 'success',
confirmLabel: t('main.dialog.save'),
rejectLabel: t('main.dialog.cancel')
});
if (!result || !result[0] || !result[1] || !result[2] || result[0] === result[1]) return;
const error = await profileModel.setPassword(result[2], result[0]);
if (error) return console.error('Failed to change password', error);
}
async function onPasswordReset() {
const error = await profileModel.sendPasswordReset(user.value.email);
if (error) return console.error('Failed to reset password:', error);
window.pankow.notify({ type: 'success', timeout: 5000, text: t('profile.passwordResetNotification.title') + '. ' + t('profile.passwordResetNotification.body', { email: user.value.fallbackEmail || user.value.email }) });
}
// Tokens
const webadminTokens = ref([]);
const cliTokens = ref([]);
const revokeTokensBusy = ref(false);
async function onRevokeAllWebAndCliTokens() {
revokeTokensBusy.value = true;
// filter current access token to be able to logout still
const tokens = webadminTokens.value.concat(cliTokens.value).filter(t => t.accessToken !== localStorage.token);
for (const token of tokens) {
const [error] = await tokensModel.remove(token.id);
if (error) console.error(error);
}
await profileModel.logout();
}
// 2fa
const mandatory2FAHelp = ref('');
const twoFASecret = ref('');
const twoFATotpToken = ref('');
const twoFAQRCode = ref('');
const twoFAEnableError = ref('');
const twoFADialog = useTemplateRef('twoFADialog');
async function onOpenTwoFASetupDialog() {
const [error, result] = await profileModel.setTwoFASecret();
if (error) return console.error(error);
twoFAEnableError.value = '';
twoFATotpToken.value = '';
twoFASecret.value = result.secret;
twoFAQRCode.value = result.qrcode;
twoFADialog.value.open();
}
async function onTwoFAEnable() {
const [error] = await profileModel.enableTwoFA(twoFATotpToken.value);
if (error) return twoFAEnableError.value = error.body ? error.body.message : 'Internal error';
user.value = await profileModel.get();
twoFADialog.value.close();
}
async function onTwoFADisable() {
const password = await inputDialog.value.prompt({
message: t('profile.disable2FA.title'),
modal: true,
placeholder: t('appstore.accountDialog.password'),
type: 'password',
confirmStyle: 'danger',
confirmLabel: t('main.dialog.yes'),
rejectLabel: t('main.dialog.no')
});
if (!password) return;
const [error] = await profileModel.disableTwoFA(password);
if (error) return onTwoFADisable();
user.value = await profileModel.get();
}
// Init
onMounted(async () => {
user.value = await profileModel.get();
const langs = await cloudronModel.languages();
languages.value = langs.map(l => {
return {
id: l,
display: t(`lang.${l}`)
};
}).sort((a, b) => {
return a.display.localeCompare(b.display);
});
const usedLang = window.localStorage.NG_TRANSLATE_LANG_KEY || 'en';
language.value = languages.value.find(l => l.id === usedLang).id;
const [error, tokens] = await tokensModel.list();
if (error) return console.error(error);
// dashboard and development clientIds were issued with 7.5.0
webadminTokens.value = tokens.filter(function (c) { return c.clientId === TOKEN_TYPES.ID_WEBADMIN || c.clientId === TOKEN_TYPES.ID_DEVELOPMENT || c.clientId === 'dashboard' || c.clientId === 'development'; });
cliTokens.value = tokens.filter(function (c) { return c.clientId === TOKEN_TYPES.ID_CLI; });
});
</script>