Refactor pleaseLogin to show a sign-in dialog (#8630)

* refactor(client): refactor pleaseLogin to show a sign-in dialog

* Apply review suggestions from @Johann150

Co-authored-by: Johann150 <johann@qwertqwefsday.eu>

Co-authored-by: Johann150 <johann@qwertqwefsday.eu>
Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
This commit is contained in:
Andreas Nedbal 2022-05-19 13:28:08 +02:00 committed by GitHub
parent 992fd76067
commit 1d9a4f68f4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 215 additions and 204 deletions

View File

@ -425,7 +425,7 @@ quoteQuestion: "引用として添付しますか?"
noMessagesYet: "まだチャットはありません" noMessagesYet: "まだチャットはありません"
newMessageExists: "新しいメッセージがあります" newMessageExists: "新しいメッセージがあります"
onlyOneFileCanBeAttached: "メッセージに添付できるファイルはひとつです" onlyOneFileCanBeAttached: "メッセージに添付できるファイルはひとつです"
signinRequired: "ログインしてください" signinRequired: "続行する前に、サインアップまたはサインインが必要です"
invitations: "招待" invitations: "招待"
invitationCode: "招待コード" invitationCode: "招待コード"
checking: "確認しています" checking: "確認しています"

View File

@ -2,12 +2,12 @@
<XModalWindow ref="dialog" <XModalWindow ref="dialog"
:width="370" :width="370"
:height="400" :height="400"
@close="dialog.close()" @close="onClose"
@closed="emit('closed')" @closed="emit('closed')"
> >
<template #header>{{ $ts.login }}</template> <template #header>{{ $ts.login }}</template>
<MkSignin :auto-set="autoSet" @login="onLogin"/> <MkSignin :auto-set="autoSet" :message="message" @login="onLogin"/>
</XModalWindow> </XModalWindow>
</template> </template>
@ -18,17 +18,25 @@ import MkSignin from './signin.vue';
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
autoSet?: boolean; autoSet?: boolean;
message?: string,
}>(), { }>(), {
autoSet: false, autoSet: false,
message: ''
}); });
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'done'): void; (ev: 'done'): void;
(e: 'closed'): void; (ev: 'closed'): void;
(ev: 'cancelled'): void;
}>(); }>();
const dialog = $ref<InstanceType<typeof XModalWindow>>(); const dialog = $ref<InstanceType<typeof XModalWindow>>();
function onClose() {
emit('cancelled');
dialog.close();
}
function onLogin(res) { function onLogin(res) {
emit('done', res); emit('done', res);
dialog.close(); dialog.close();

View File

@ -1,41 +1,44 @@
<template> <template>
<form class="eppvobhk _monolithic_" :class="{ signing, totpLogin }" @submit.prevent="onSubmit"> <form class="eppvobhk _monolithic_" :class="{ signing, totpLogin }" @submit.prevent="onSubmit">
<div class="auth _section _formRoot"> <div class="auth _section _formRoot">
<div v-show="withAvatar" class="avatar" :style="{ backgroundImage: user ? `url('${ user.avatarUrl }')` : null }"></div> <div v-show="withAvatar" class="avatar" :style="{ backgroundImage: user ? `url('${ user.avatarUrl }')` : null, marginBottom: message ? '1.5em' : null }"></div>
<MkInfo v-if="message">
{{ message }}
</MkInfo>
<div v-if="!totpLogin" class="normal-signin"> <div v-if="!totpLogin" class="normal-signin">
<MkInput v-model="username" class="_formBlock" :placeholder="$ts.username" type="text" pattern="^[a-zA-Z0-9_]+$" spellcheck="false" autofocus required data-cy-signin-username @update:modelValue="onUsernameChange"> <MkInput v-model="username" class="_formBlock" :placeholder="i18n.ts.username" type="text" pattern="^[a-zA-Z0-9_]+$" spellcheck="false" autofocus required data-cy-signin-username @update:modelValue="onUsernameChange">
<template #prefix>@</template> <template #prefix>@</template>
<template #suffix>@{{ host }}</template> <template #suffix>@{{ host }}</template>
</MkInput> </MkInput>
<MkInput v-if="!user || user && !user.usePasswordLessLogin" v-model="password" class="_formBlock" :placeholder="$ts.password" type="password" :with-password-toggle="true" required data-cy-signin-password> <MkInput v-if="!user || user && !user.usePasswordLessLogin" v-model="password" class="_formBlock" :placeholder="i18n.ts.password" type="password" :with-password-toggle="true" required data-cy-signin-password>
<template #prefix><i class="fas fa-lock"></i></template> <template #prefix><i class="fas fa-lock"></i></template>
<template #caption><button class="_textButton" type="button" @click="resetPassword">{{ $ts.forgotPassword }}</button></template> <template #caption><button class="_textButton" type="button" @click="resetPassword">{{ i18n.ts.forgotPassword }}</button></template>
</MkInput> </MkInput>
<MkCaptcha v-if="meta.enableHcaptcha" ref="hcaptcha" v-model="hCaptchaResponse" class="_formBlock captcha" provider="hcaptcha" :sitekey="meta.hcaptchaSiteKey"/> <MkCaptcha v-if="meta.enableHcaptcha" ref="hcaptcha" v-model="hCaptchaResponse" class="_formBlock captcha" provider="hcaptcha" :sitekey="meta.hcaptchaSiteKey"/>
<MkCaptcha v-if="meta.enableRecaptcha" ref="recaptcha" v-model="reCaptchaResponse" class="_formBlock captcha" provider="recaptcha" :sitekey="meta.recaptchaSiteKey"/> <MkCaptcha v-if="meta.enableRecaptcha" ref="recaptcha" v-model="reCaptchaResponse" class="_formBlock captcha" provider="recaptcha" :sitekey="meta.recaptchaSiteKey"/>
<MkButton class="_formBlock" type="submit" primary :disabled="signing" style="margin: 0 auto;">{{ signing ? $ts.loggingIn : $ts.login }}</MkButton> <MkButton class="_formBlock" type="submit" primary :disabled="signing" style="margin: 0 auto;">{{ signing ? i18n.ts.loggingIn : i18n.ts.login }}</MkButton>
</div> </div>
<div v-if="totpLogin" class="2fa-signin" :class="{ securityKeys: user && user.securityKeys }"> <div v-if="totpLogin" class="2fa-signin" :class="{ securityKeys: user && user.securityKeys }">
<div v-if="user && user.securityKeys" class="twofa-group tap-group"> <div v-if="user && user.securityKeys" class="twofa-group tap-group">
<p>{{ $ts.tapSecurityKey }}</p> <p>{{ i18n.ts.tapSecurityKey }}</p>
<MkButton v-if="!queryingKey" @click="queryKey"> <MkButton v-if="!queryingKey" @click="queryKey">
{{ $ts.retry }} {{ i18n.ts.retry }}
</MkButton> </MkButton>
</div> </div>
<div v-if="user && user.securityKeys" class="or-hr"> <div v-if="user && user.securityKeys" class="or-hr">
<p class="or-msg">{{ $ts.or }}</p> <p class="or-msg">{{ i18n.ts.or }}</p>
</div> </div>
<div class="twofa-group totp-group"> <div class="twofa-group totp-group">
<p style="margin-bottom:0;">{{ $ts.twoStepAuthentication }}</p> <p style="margin-bottom:0;">{{ i18n.ts.twoStepAuthentication }}</p>
<MkInput v-if="user && user.usePasswordLessLogin" v-model="password" type="password" :with-password-toggle="true" required> <MkInput v-if="user && user.usePasswordLessLogin" v-model="password" type="password" :with-password-toggle="true" required>
<template #label>{{ $ts.password }}</template> <template #label>{{ i18n.ts.password }}</template>
<template #prefix><i class="fas fa-lock"></i></template> <template #prefix><i class="fas fa-lock"></i></template>
</MkInput> </MkInput>
<MkInput v-model="token" type="text" pattern="^[0-9]{6}$" autocomplete="off" spellcheck="false" required> <MkInput v-model="token" type="text" pattern="^[0-9]{6}$" autocomplete="off" spellcheck="false" required>
<template #label>{{ $ts.token }}</template> <template #label>{{ i18n.ts.token }}</template>
<template #prefix><i class="fas fa-gavel"></i></template> <template #prefix><i class="fas fa-gavel"></i></template>
</MkInput> </MkInput>
<MkButton type="submit" :disabled="signing" primary style="margin: 0 auto;">{{ signing ? $ts.loggingIn : $ts.login }}</MkButton> <MkButton type="submit" :disabled="signing" primary style="margin: 0 auto;">{{ signing ? i18n.ts.loggingIn : i18n.ts.login }}</MkButton>
</div> </div>
</div> </div>
</div> </div>
@ -47,25 +50,42 @@
</form> </form>
</template> </template>
<script lang="ts"> <script lang="ts" setup>
import { defineAsyncComponent, defineComponent } from 'vue'; import { defineAsyncComponent } from 'vue';
import { toUnicode } from 'punycode/'; import { toUnicode } from 'punycode/';
import MkButton from '@/components/ui/button.vue'; import MkButton from '@/components/ui/button.vue';
import MkInput from '@/components/form/input.vue'; import MkInput from '@/components/form/input.vue';
import { apiUrl, host } from '@/config'; import MkInfo from '@/components/ui/info.vue';
import { apiUrl, host as configHost } from '@/config';
import { byteify, hexify } from '@/scripts/2fa'; import { byteify, hexify } from '@/scripts/2fa';
import * as os from '@/os'; import * as os from '@/os';
import { login } from '@/account'; import { login } from '@/account';
import { showSuspendedDialog } from '../scripts/show-suspended-dialog'; import { showSuspendedDialog } from '../scripts/show-suspended-dialog';
import { instance } from '@/instance';
import { i18n } from '@/i18n';
export default defineComponent({ const MkCaptcha = defineAsyncComponent(() => import('./captcha.vue'));
components: {
MkButton,
MkInput,
MkCaptcha: defineAsyncComponent(() => import('./captcha.vue')),
},
props: { let signing = $ref(false);
let user = $ref(null);
let username = $ref('');
let password = $ref('');
let token = $ref('');
let host = $ref(toUnicode(configHost));
let totpLogin = $ref(false);
let credential = $ref(null);
let challengeData = $ref(null);
let queryingKey = $ref(false);
let hCaptchaResponse = $ref(null);
let reCaptchaResponse = $ref(null);
const meta = $computed(() => instance);
const emit = defineEmits<{
(ev: 'login', v: any): void;
}>();
const props = defineProps({
withAvatar: { withAvatar: {
type: Boolean, type: Boolean,
required: false, required: false,
@ -75,60 +95,36 @@ export default defineComponent({
type: Boolean, type: Boolean,
required: false, required: false,
default: false, default: false,
},
message: {
type: String,
required: false,
default: ''
} }
},
emits: ['login'],
data() {
return {
signing: false,
user: null,
username: '',
password: '',
token: '',
apiUrl,
host: toUnicode(host),
totpLogin: false,
credential: null,
challengeData: null,
queryingKey: false,
hCaptchaResponse: null,
reCaptchaResponse: null,
};
},
computed: {
meta() {
return this.$instance;
},
},
methods: {
onUsernameChange() {
os.api('users/show', {
username: this.username
}).then(user => {
this.user = user;
}, () => {
this.user = null;
}); });
},
onLogin(res) { function onUsernameChange() {
if (this.autoSet) { os.api('users/show', {
return login(res.i); username: username
} else { }).then(user => {
return; user = user;
}, () => {
user = null;
});
} }
},
queryKey() { function onLogin(res) {
this.queryingKey = true; if (props.autoSet) {
return login(res.i);
}
}
function queryKey() {
queryingKey = true;
return navigator.credentials.get({ return navigator.credentials.get({
publicKey: { publicKey: {
challenge: byteify(this.challengeData.challenge, 'base64'), challenge: byteify(challengeData.challenge, 'base64'),
allowCredentials: this.challengeData.securityKeys.map(key => ({ allowCredentials: challengeData.securityKeys.map(key => ({
id: byteify(key.id, 'hex'), id: byteify(key.id, 'hex'),
type: 'public-key', type: 'public-key',
transports: ['usb', 'nfc', 'ble', 'internal'] transports: ['usb', 'nfc', 'ble', 'internal']
@ -136,83 +132,84 @@ export default defineComponent({
timeout: 60 * 1000 timeout: 60 * 1000
} }
}).catch(() => { }).catch(() => {
this.queryingKey = false; queryingKey = false;
return Promise.reject(null); return Promise.reject(null);
}).then(credential => { }).then(credential => {
this.queryingKey = false; queryingKey = false;
this.signing = true; signing = true;
return os.api('signin', { return os.api('signin', {
username: this.username, username,
password: this.password, password,
'hcaptcha-response': this.hCaptchaResponse,
'g-recaptcha-response': this.reCaptchaResponse,
signature: hexify(credential.response.signature), signature: hexify(credential.response.signature),
authenticatorData: hexify(credential.response.authenticatorData), authenticatorData: hexify(credential.response.authenticatorData),
clientDataJSON: hexify(credential.response.clientDataJSON), clientDataJSON: hexify(credential.response.clientDataJSON),
credentialId: credential.id, credentialId: credential.id,
challengeId: this.challengeData.challengeId, challengeId: challengeData.challengeId,
'hcaptcha-response': hCaptchaResponse,
'g-recaptcha-response': reCaptchaResponse,
}); });
}).then(res => { }).then(res => {
this.$emit('login', res); emit('login', res);
return this.onLogin(res); return onLogin(res);
}).catch(err => { }).catch(err => {
if (err === null) return; if (err === null) return;
os.alert({ os.alert({
type: 'error', type: 'error',
text: this.$ts.signinFailed text: i18n.ts.signinFailed
}); });
this.signing = false; signing = false;
}); });
}, }
onSubmit() { function onSubmit() {
this.signing = true; signing = true;
if (!this.totpLogin && this.user && this.user.twoFactorEnabled) { console.log('submit')
if (window.PublicKeyCredential && this.user.securityKeys) { if (!totpLogin && user && user.twoFactorEnabled) {
if (window.PublicKeyCredential && user.securityKeys) {
os.api('signin', { os.api('signin', {
username: this.username, username,
password: this.password, password,
'hcaptcha-response': this.hCaptchaResponse, 'hcaptcha-response': hCaptchaResponse,
'g-recaptcha-response': this.reCaptchaResponse, 'g-recaptcha-response': reCaptchaResponse,
}).then(res => { }).then(res => {
this.totpLogin = true; totpLogin = true;
this.signing = false; signing = false;
this.challengeData = res; challengeData = res;
return this.queryKey(); return queryKey();
}).catch(this.loginFailed); }).catch(loginFailed);
} else { } else {
this.totpLogin = true; totpLogin = true;
this.signing = false; signing = false;
} }
} else { } else {
os.api('signin', { os.api('signin', {
username: this.username, username,
password: this.password, password,
'hcaptcha-response': this.hCaptchaResponse, 'hcaptcha-response': hCaptchaResponse,
'g-recaptcha-response': this.reCaptchaResponse, 'g-recaptcha-response': reCaptchaResponse,
token: this.user && this.user.twoFactorEnabled ? this.token : undefined, token: user && user.twoFactorEnabled ? token : undefined
}).then(res => { }).then(res => {
this.$emit('login', res); emit('login', res);
this.onLogin(res); onLogin(res);
}).catch(this.loginFailed); }).catch(loginFailed);
}
} }
},
loginFailed(err) { function loginFailed(err) {
switch (err.id) { switch (err.id) {
case '6cc579cc-885d-43d8-95c2-b8c7fc963280': { case '6cc579cc-885d-43d8-95c2-b8c7fc963280': {
os.alert({ os.alert({
type: 'error', type: 'error',
title: this.$ts.loginFailed, title: i18n.ts.loginFailed,
text: this.$ts.noSuchUser text: i18n.ts.noSuchUser
}); });
break; break;
} }
case '932c904e-9460-45b7-9ce6-7ed33be7eb2c': { case '932c904e-9460-45b7-9ce6-7ed33be7eb2c': {
os.alert({ os.alert({
type: 'error', type: 'error',
title: this.$ts.loginFailed, title: i18n.ts.loginFailed,
text: this.$ts.incorrectPassword, text: i18n.ts.incorrectPassword,
}); });
break; break;
} }
@ -221,25 +218,24 @@ export default defineComponent({
break; break;
} }
default: { default: {
console.log(err)
os.alert({ os.alert({
type: 'error', type: 'error',
title: this.$ts.loginFailed, title: i18n.ts.loginFailed,
text: JSON.stringify(err) text: JSON.stringify(err)
}); });
} }
} }
this.challengeData = null; challengeData = null;
this.totpLogin = false; totpLogin = false;
this.signing = false; signing = false;
}, }
resetPassword() { function resetPassword() {
os.popup(defineAsyncComponent(() => import('@/components/forgot-password.vue')), {}, { os.popup(defineAsyncComponent(() => import('@/components/forgot-password.vue')), {}, {
}, 'closed'); }, 'closed');
} }
}
});
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -1,14 +1,21 @@
import { defineAsyncComponent } from 'vue';
import { $i } from '@/account'; import { $i } from '@/account';
import { i18n } from '@/i18n'; import { i18n } from '@/i18n';
import { alert } from '@/os'; import { popup } from '@/os';
export function pleaseLogin() { export function pleaseLogin(path?: string) {
if ($i) return; if ($i) return;
alert({ popup(defineAsyncComponent(() => import('@/components/signin-dialog.vue')), {
title: i18n.ts.signinRequired, autoSet: true,
text: null message: i18n.ts.signinRequired
}); }, {
cancelled: () => {
if (path) {
window.location.href = path;
}
},
}, 'closed');
throw new Error('signin required'); throw new Error('signin required');
} }