refactor(editor): Migrate AuthView and associated components to composition api (#10713)
Some checks are pending
Test Master / install-and-build (push) Waiting to run
Test Master / Unit tests (18.x) (push) Blocked by required conditions
Test Master / Unit tests (20.x) (push) Blocked by required conditions
Test Master / Unit tests (22.4) (push) Blocked by required conditions
Test Master / Lint (push) Blocked by required conditions
Test Master / Notify Slack on failure (push) Blocked by required conditions

This commit is contained in:
Milorad FIlipović 2024-09-19 05:38:45 +02:00 committed by GitHub
parent ee7147c6b3
commit 91008b2676
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 577 additions and 572 deletions

View file

@ -1,44 +1,37 @@
<script lang="ts">
import { type PropType, defineComponent } from 'vue';
import Logo from '@/components/Logo.vue';
<script setup lang="ts">
import SSOLogin from '@/components/SSOLogin.vue';
import type { IFormBoxConfig } from '@/Interface';
export default defineComponent({
name: 'AuthView',
components: {
Logo,
SSOLogin,
withDefaults(
defineProps<{
form: IFormBoxConfig;
formLoading?: boolean;
subtitle?: string;
withSso?: boolean;
}>(),
{
formLoading: false,
withSso: false,
},
props: {
form: {
type: Object as PropType<IFormBoxConfig>,
},
formLoading: {
type: Boolean,
default: false,
},
subtitle: {
type: String,
},
withSso: {
type: Boolean,
default: false,
},
},
methods: {
onUpdate(e: { name: string; value: string }) {
this.$emit('update', e);
},
onSubmit(values: { [key: string]: string }) {
this.$emit('submit', values);
},
onSecondaryClick() {
this.$emit('secondaryClick');
},
},
});
);
const emit = defineEmits<{
update: [{ name: string; value: string }];
submit: [values: { [key: string]: string }];
secondaryClick: [];
}>();
const onUpdate = (e: { name: string; value: string }) => {
emit('update', e);
};
const onSubmit = (values: { [key: string]: string }) => {
emit('submit', values);
};
const onSecondaryClick = () => {
emit('secondaryClick');
};
</script>
<template>

View file

@ -1,163 +1,164 @@
<script lang="ts">
import AuthView from '@/views/AuthView.vue';
import { useToast } from '@/composables/useToast';
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { defineComponent } from 'vue';
import type { IFormBoxConfig } from '@/Interface';
import { MFA_AUTHENTICATION_TOKEN_INPUT_MAX_LENGTH, VIEWS } from '@/constants';
import { mapStores } from 'pinia';
import AuthView from '@/views/AuthView.vue';
import { useI18n } from '@/composables/useI18n';
import { useToast } from '@/composables/useToast';
import { useUsersStore } from '@/stores/users.store';
export default defineComponent({
name: 'ChangePasswordView',
components: {
AuthView,
},
setup() {
return {
...useToast(),
};
},
data() {
return {
password: '',
loading: false,
config: null as null | IFormBoxConfig,
};
},
computed: {
...mapStores(useUsersStore),
},
async mounted() {
const form: IFormBoxConfig = {
title: this.$locale.baseText('auth.changePassword'),
buttonText: this.$locale.baseText('auth.changePassword'),
redirectText: this.$locale.baseText('auth.signin'),
redirectLink: '/signin',
inputs: [
{
name: 'password',
properties: {
label: this.$locale.baseText('auth.newPassword'),
type: 'password',
required: true,
validationRules: [{ name: 'DEFAULT_PASSWORD_RULES' }],
infoText: this.$locale.baseText('auth.defaultPasswordRequirements'),
autocomplete: 'new-password',
capitalize: true,
},
},
{
name: 'password2',
properties: {
label: this.$locale.baseText('auth.changePassword.reenterNewPassword'),
type: 'password',
required: true,
validators: {
TWO_PASSWORDS_MATCH: {
validate: this.passwordsMatch,
},
},
validationRules: [{ name: 'TWO_PASSWORDS_MATCH' }],
autocomplete: 'new-password',
capitalize: true,
},
},
],
};
import type { IFormBoxConfig } from '@/Interface';
import { MFA_AUTHENTICATION_TOKEN_INPUT_MAX_LENGTH, VIEWS } from '@/constants';
const token = this.getResetToken();
const mfaEnabled = this.getMfaEnabled();
const usersStore = useUsersStore();
if (mfaEnabled) {
form.inputs.push({
name: 'mfaToken',
initialValue: '',
properties: {
required: true,
label: this.$locale.baseText('mfa.code.input.label'),
placeholder: this.$locale.baseText('mfa.code.input.placeholder'),
maxlength: MFA_AUTHENTICATION_TOKEN_INPUT_MAX_LENGTH,
capitalize: true,
validateOnBlur: true,
},
const locale = useI18n();
const toast = useToast();
const router = useRouter();
const password = ref('');
const loading = ref(false);
const config = ref<IFormBoxConfig | null>(null);
const passwordsMatch = (value: string | number | boolean | null | undefined) => {
if (typeof value !== 'string') {
return false;
}
if (value !== password.value) {
return {
messageKey: 'auth.changePassword.passwordsMustMatchError',
};
}
return false;
};
const getResetToken = () => {
return !router.currentRoute.value.query.token ||
typeof router.currentRoute.value.query.token !== 'string'
? null
: router.currentRoute.value.query.token;
};
const getMfaEnabled = () => {
if (!router.currentRoute.value.query.mfaEnabled) return null;
return router.currentRoute.value.query.mfaEnabled === 'true' ? true : false;
};
const isFormWithMFAToken = (values: { [key: string]: string }): values is { mfaToken: string } => {
return 'mfaToken' in values;
};
const onSubmit = async (values: { [key: string]: string }) => {
if (!isFormWithMFAToken(values)) return;
try {
loading.value = true;
const token = getResetToken();
if (token) {
const changePasswordParameters = {
token,
password: password.value,
...(values.mfaToken && { mfaToken: values.mfaToken }),
};
await usersStore.changePassword(changePasswordParameters);
toast.showMessage({
type: 'success',
title: locale.baseText('auth.changePassword.passwordUpdated'),
message: locale.baseText('auth.changePassword.passwordUpdatedMessage'),
});
await router.push({ name: VIEWS.SIGNIN });
} else {
toast.showError(
new Error(locale.baseText('auth.validation.missingParameters')),
locale.baseText('auth.changePassword.error'),
);
}
} catch (error) {
toast.showError(error, locale.baseText('auth.changePassword.error'));
}
loading.value = false;
};
const onInput = (e: { name: string; value: string }) => {
if (e.name === 'password') {
password.value = e.value;
}
};
onMounted(async () => {
const form: IFormBoxConfig = {
title: locale.baseText('auth.changePassword'),
buttonText: locale.baseText('auth.changePassword'),
redirectText: locale.baseText('auth.signin'),
redirectLink: '/signin',
inputs: [
{
name: 'password',
properties: {
label: locale.baseText('auth.newPassword'),
type: 'password',
required: true,
validationRules: [{ name: 'DEFAULT_PASSWORD_RULES' }],
infoText: locale.baseText('auth.defaultPasswordRequirements'),
autocomplete: 'new-password',
capitalize: true,
},
},
{
name: 'password2',
properties: {
label: locale.baseText('auth.changePassword.reenterNewPassword'),
type: 'password',
required: true,
validators: {
TWO_PASSWORDS_MATCH: {
validate: passwordsMatch,
},
},
validationRules: [{ name: 'TWO_PASSWORDS_MATCH' }],
autocomplete: 'new-password',
capitalize: true,
},
},
],
};
const token = getResetToken();
const mfaEnabled = getMfaEnabled();
if (mfaEnabled) {
form.inputs.push({
name: 'mfaToken',
initialValue: '',
properties: {
required: true,
label: locale.baseText('mfa.code.input.label'),
placeholder: locale.baseText('mfa.code.input.placeholder'),
maxlength: MFA_AUTHENTICATION_TOKEN_INPUT_MAX_LENGTH,
capitalize: true,
validateOnBlur: true,
},
});
}
config.value = form;
try {
if (!token) {
throw new Error(locale.baseText('auth.changePassword.missingTokenError'));
}
this.config = form;
try {
if (!token) {
throw new Error(this.$locale.baseText('auth.changePassword.missingTokenError'));
}
await this.usersStore.validatePasswordToken({ token });
} catch (e) {
this.showError(e, this.$locale.baseText('auth.changePassword.tokenValidationError'));
void this.$router.replace({ name: VIEWS.SIGNIN });
}
},
methods: {
passwordsMatch(value: string | number | boolean | null | undefined) {
if (typeof value !== 'string') {
return false;
}
if (value !== this.password) {
return {
messageKey: 'auth.changePassword.passwordsMustMatchError',
};
}
return false;
},
onInput(e: { name: string; value: string }) {
if (e.name === 'password') {
this.password = e.value;
}
},
getResetToken() {
return !this.$route.query.token || typeof this.$route.query.token !== 'string'
? null
: this.$route.query.token;
},
getMfaEnabled() {
if (!this.$route.query.mfaEnabled) return null;
return this.$route.query.mfaEnabled === 'true' ? true : false;
},
async onSubmit(values: { mfaToken: string }) {
try {
this.loading = true;
const token = this.getResetToken();
if (token) {
const changePasswordParameters = {
token,
password: this.password,
...(values.mfaToken && { mfaToken: values.mfaToken }),
};
await this.usersStore.changePassword(changePasswordParameters);
this.showMessage({
type: 'success',
title: this.$locale.baseText('auth.changePassword.passwordUpdated'),
message: this.$locale.baseText('auth.changePassword.passwordUpdatedMessage'),
});
await this.$router.push({ name: VIEWS.SIGNIN });
} else {
this.showError(
new Error(this.$locale.baseText('auth.validation.missingParameters')),
this.$locale.baseText('auth.changePassword.error'),
);
}
} catch (error) {
this.showError(error, this.$locale.baseText('auth.changePassword.error'));
}
this.loading = false;
},
},
await usersStore.validatePasswordToken({ token });
} catch (e) {
toast.showError(e, locale.baseText('auth.changePassword.tokenValidationError'));
void router.replace({ name: VIEWS.SIGNIN });
}
});
</script>

View file

@ -1,108 +1,102 @@
<script lang="ts">
<script setup lang="ts">
import AuthView from './AuthView.vue';
import { useToast } from '@/composables/useToast';
import { defineComponent } from 'vue';
import type { IFormBoxConfig } from '@/Interface';
import { mapStores } from 'pinia';
import { useI18n } from '@/composables/useI18n';
import { useToast } from '@/composables/useToast';
import { useSettingsStore } from '@/stores/settings.store';
import { useUsersStore } from '@/stores/users.store';
import { computed, ref } from 'vue';
export default defineComponent({
name: 'ForgotMyPasswordView',
components: {
AuthView,
},
setup() {
return {
...useToast(),
};
},
data() {
return {
loading: false,
};
},
computed: {
...mapStores(useSettingsStore, useUsersStore),
formConfig(): IFormBoxConfig {
const EMAIL_INPUTS: IFormBoxConfig['inputs'] = [
{
name: 'email',
properties: {
label: this.$locale.baseText('auth.email'),
type: 'email',
required: true,
validationRules: [{ name: 'VALID_EMAIL' }],
autocomplete: 'email',
capitalize: true,
},
},
];
const settingsStore = useSettingsStore();
const usersStore = useUsersStore();
const NO_SMTP_INPUTS: IFormBoxConfig['inputs'] = [
{
name: 'no-smtp-warning',
properties: {
label: this.$locale.baseText('forgotPassword.noSMTPToSendEmailWarning'),
type: 'info',
},
},
];
const toast = useToast();
const locale = useI18n();
const DEFAULT_FORM_CONFIG = {
title: this.$locale.baseText('forgotPassword.recoverPassword'),
redirectText: this.$locale.baseText('forgotPassword.returnToSignIn'),
redirectLink: '/signin',
};
const loading = ref(false);
if (this.settingsStore.isSmtpSetup) {
return {
...DEFAULT_FORM_CONFIG,
buttonText: this.$locale.baseText('forgotPassword.getRecoveryLink'),
inputs: EMAIL_INPUTS,
};
}
return {
...DEFAULT_FORM_CONFIG,
inputs: NO_SMTP_INPUTS,
};
const formConfig = computed(() => {
const EMAIL_INPUTS: IFormBoxConfig['inputs'] = [
{
name: 'email',
properties: {
label: locale.baseText('auth.email'),
type: 'email',
required: true,
validationRules: [{ name: 'VALID_EMAIL' }],
autocomplete: 'email',
capitalize: true,
},
},
},
methods: {
async onSubmit(values: { email: string }) {
try {
this.loading = true;
await this.usersStore.sendForgotPasswordEmail(values);
];
this.showMessage({
type: 'success',
title: this.$locale.baseText('forgotPassword.recoveryEmailSent'),
message: this.$locale.baseText('forgotPassword.emailSentIfExists', {
interpolate: { email: values.email },
}),
});
} catch (error) {
let message = this.$locale.baseText('forgotPassword.smtpErrorContactAdministrator');
if (error.httpStatusCode) {
const { httpStatusCode: status } = error;
if (status === 429) {
message = this.$locale.baseText('forgotPassword.tooManyRequests');
} else if (error.httpStatusCode === 422) {
message = this.$locale.baseText(error.message);
}
this.showMessage({
type: 'error',
title: this.$locale.baseText('forgotPassword.sendingEmailError'),
message,
});
}
}
this.loading = false;
const NO_SMTP_INPUTS: IFormBoxConfig['inputs'] = [
{
name: 'no-smtp-warning',
properties: {
label: locale.baseText('forgotPassword.noSMTPToSendEmailWarning'),
type: 'info',
},
},
},
];
const DEFAULT_FORM_CONFIG = {
title: locale.baseText('forgotPassword.recoverPassword'),
redirectText: locale.baseText('forgotPassword.returnToSignIn'),
redirectLink: '/signin',
};
if (settingsStore.isSmtpSetup) {
return {
...DEFAULT_FORM_CONFIG,
buttonText: locale.baseText('forgotPassword.getRecoveryLink'),
inputs: EMAIL_INPUTS,
};
}
return {
...DEFAULT_FORM_CONFIG,
inputs: NO_SMTP_INPUTS,
};
});
const isFormWithEmail = (values: { [key: string]: string }): values is { email: string } => {
return 'email' in values;
};
const onSubmit = async (values: { [key: string]: string }) => {
if (!isFormWithEmail(values)) {
return;
}
try {
loading.value = true;
await usersStore.sendForgotPasswordEmail(values);
toast.showMessage({
type: 'success',
title: locale.baseText('forgotPassword.recoveryEmailSent'),
message: locale.baseText('forgotPassword.emailSentIfExists', {
interpolate: { email: values.email },
}),
});
} catch (error) {
let message = locale.baseText('forgotPassword.smtpErrorContactAdministrator');
if (error.httpStatusCode) {
const { httpStatusCode: status } = error;
if (status === 429) {
message = locale.baseText('forgotPassword.tooManyRequests');
} else if (error.httpStatusCode === 422) {
message = locale.baseText(error.message);
}
toast.showMessage({
type: 'error',
title: locale.baseText('forgotPassword.sendingEmailError'),
message,
});
}
}
loading.value = false;
};
</script>
<template>

View file

@ -1,14 +1,17 @@
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElNotification as Notification } from 'element-plus';
import type { IFormBoxConfig } from 'n8n-design-system';
import AuthView from '@/views/AuthView.vue';
import { i18n as locale } from '@/plugins/i18n';
import { useSSOStore } from '@/stores/sso.store';
import { VIEWS } from '@/constants';
import { useI18n } from '@/composables/useI18n';
import { useToast } from '@/composables/useToast';
import { useSSOStore } from '@/stores/sso.store';
const router = useRouter();
const locale = useI18n();
const toast = useToast();
const ssoStore = useSSOStore();
const loading = ref(false);
@ -40,18 +43,22 @@ const FORM_CONFIG: IFormBoxConfig = reactive({
},
],
});
const onSubmit = async (values: { firstName: string; lastName: string }) => {
const isFormWithFirstAndLastName = (values: {
[key: string]: string;
}): values is { firstName: string; lastName: string } => {
return 'firstName' in values && 'lastName' in values;
};
const onSubmit = async (values: { [key: string]: string }) => {
if (!isFormWithFirstAndLastName(values)) return;
try {
loading.value = true;
await ssoStore.updateUser(values);
await router.push({ name: VIEWS.HOMEPAGE });
} catch (error) {
loading.value = false;
Notification.error({
title: 'Error',
message: error.message,
position: 'bottom-right',
});
toast.showError(error, 'Error', error.message);
}
};
</script>

View file

@ -1,129 +1,123 @@
<script lang="ts">
import AuthView from './AuthView.vue';
import { defineComponent } from 'vue';
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from '@/composables/useToast';
import { useI18n } from '@/composables/useI18n';
import { usePostHog } from '@/stores/posthog.store';
import { useSettingsStore } from '@/stores/settings.store';
import { useUIStore } from '@/stores/ui.store';
import { useUsersStore } from '@/stores/users.store';
import type { IFormBoxConfig } from '@/Interface';
import { MORE_ONBOARDING_OPTIONS_EXPERIMENT, VIEWS } from '@/constants';
import { mapStores } from 'pinia';
import { useUIStore } from '@/stores/ui.store';
import { useSettingsStore } from '@/stores/settings.store';
import { useUsersStore } from '@/stores/users.store';
import { usePostHog } from '@/stores/posthog.store';
export default defineComponent({
name: 'SetupView',
components: {
AuthView,
},
setup() {
return useToast();
},
data() {
const FORM_CONFIG: IFormBoxConfig = {
title: this.$locale.baseText('auth.setup.setupOwner'),
buttonText: this.$locale.baseText('auth.setup.next'),
inputs: [
{
name: 'email',
properties: {
label: this.$locale.baseText('auth.email'),
type: 'email',
required: true,
validationRules: [{ name: 'VALID_EMAIL' }],
autocomplete: 'email',
capitalize: true,
},
},
{
name: 'firstName',
properties: {
label: this.$locale.baseText('auth.firstName'),
maxlength: 32,
required: true,
autocomplete: 'given-name',
capitalize: true,
},
},
{
name: 'lastName',
properties: {
label: this.$locale.baseText('auth.lastName'),
maxlength: 32,
required: true,
autocomplete: 'family-name',
capitalize: true,
},
},
{
name: 'password',
properties: {
label: this.$locale.baseText('auth.password'),
type: 'password',
required: true,
validationRules: [{ name: 'DEFAULT_PASSWORD_RULES' }],
infoText: this.$locale.baseText('auth.defaultPasswordRequirements'),
autocomplete: 'new-password',
capitalize: true,
},
},
{
name: 'agree',
properties: {
label: this.$locale.baseText('auth.agreement.label'),
type: 'checkbox',
},
},
],
};
import AuthView from '@/views/AuthView.vue';
return {
FORM_CONFIG,
loading: false,
};
},
computed: {
...mapStores(useSettingsStore, useUIStore, useUsersStore, usePostHog),
},
methods: {
async onSubmit(values: { [key: string]: string | boolean }) {
try {
const forceRedirectedHere = this.settingsStore.showSetupPage;
const isPartOfOnboardingExperiment =
this.posthogStore.getVariant(MORE_ONBOARDING_OPTIONS_EXPERIMENT.name) ===
MORE_ONBOARDING_OPTIONS_EXPERIMENT.variant;
this.loading = true;
await this.usersStore.createOwner(
values as { firstName: string; lastName: string; email: string; password: string },
);
const posthogStore = usePostHog();
const settingsStore = useSettingsStore();
const uiStore = useUIStore();
const usersStore = useUsersStore();
if (values.agree === true) {
try {
await this.uiStore.submitContactEmail(values.email.toString(), values.agree);
} catch {}
}
const toast = useToast();
const locale = useI18n();
const router = useRouter();
if (forceRedirectedHere) {
if (isPartOfOnboardingExperiment) {
await this.$router.push({ name: VIEWS.WORKFLOWS });
} else {
await this.$router.push({ name: VIEWS.NEW_WORKFLOW });
}
} else {
await this.$router.push({ name: VIEWS.USERS_SETTINGS });
}
} catch (error) {
this.showError(error, this.$locale.baseText('auth.setup.settingUpOwnerError'));
}
this.loading = false;
const loading = ref(false);
const formConfig: IFormBoxConfig = reactive({
title: locale.baseText('auth.setup.setupOwner'),
buttonText: locale.baseText('auth.setup.next'),
inputs: [
{
name: 'email',
properties: {
label: locale.baseText('auth.email'),
type: 'email',
required: true,
validationRules: [{ name: 'VALID_EMAIL' }],
autocomplete: 'email',
capitalize: true,
},
},
},
{
name: 'firstName',
properties: {
label: locale.baseText('auth.firstName'),
maxlength: 32,
required: true,
autocomplete: 'given-name',
capitalize: true,
},
},
{
name: 'lastName',
properties: {
label: locale.baseText('auth.lastName'),
maxlength: 32,
required: true,
autocomplete: 'family-name',
capitalize: true,
},
},
{
name: 'password',
properties: {
label: locale.baseText('auth.password'),
type: 'password',
required: true,
validationRules: [{ name: 'DEFAULT_PASSWORD_RULES' }],
infoText: locale.baseText('auth.defaultPasswordRequirements'),
autocomplete: 'new-password',
capitalize: true,
},
},
{
name: 'agree',
properties: {
label: locale.baseText('auth.agreement.label'),
type: 'checkbox',
},
},
],
});
const onSubmit = async (values: { [key: string]: string | boolean }) => {
try {
const forceRedirectedHere = settingsStore.showSetupPage;
const isPartOfOnboardingExperiment =
posthogStore.getVariant(MORE_ONBOARDING_OPTIONS_EXPERIMENT.name) ===
MORE_ONBOARDING_OPTIONS_EXPERIMENT.variant;
loading.value = true;
await usersStore.createOwner(
values as { firstName: string; lastName: string; email: string; password: string },
);
if (values.agree === true) {
try {
await uiStore.submitContactEmail(values.email.toString(), values.agree);
} catch {}
}
if (forceRedirectedHere) {
if (isPartOfOnboardingExperiment) {
await router.push({ name: VIEWS.WORKFLOWS });
} else {
await router.push({ name: VIEWS.NEW_WORKFLOW });
}
} else {
await router.push({ name: VIEWS.USERS_SETTINGS });
}
} catch (error) {
toast.showError(error, locale.baseText('auth.setup.settingUpOwnerError'));
}
loading.value = false;
};
</script>
<template>
<AuthView
:form="FORM_CONFIG"
:form="formConfig"
:form-loading="loading"
data-test-id="setup-form"
@submit="onSubmit"

View file

@ -1,191 +1,207 @@
<script lang="ts">
import { defineComponent } from 'vue';
<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import AuthView from './AuthView.vue';
import MfaView from './MfaView.vue';
import { useToast } from '@/composables/useToast';
import type { IFormBoxConfig } from '@/Interface';
import { MFA_AUTHENTICATION_REQUIRED_ERROR_CODE, VIEWS, MFA_FORM } from '@/constants';
import { mapStores } from 'pinia';
import { useI18n } from '@/composables/useI18n';
import { useTelemetry } from '@/composables/useTelemetry';
import { useUsersStore } from '@/stores/users.store';
import { useSettingsStore } from '@/stores/settings.store';
import { useCloudPlanStore } from '@/stores/cloudPlan.store';
import { useUIStore } from '@/stores/ui.store';
export default defineComponent({
name: 'SigninView',
components: {
AuthView,
MfaView,
},
setup() {
return {
...useToast(),
};
},
data() {
return {
FORM_CONFIG: {} as IFormBoxConfig,
loading: false,
showMfaView: false,
email: '',
password: '',
reportError: false,
};
},
computed: {
...mapStores(useUsersStore, useSettingsStore, useUIStore, useCloudPlanStore),
userHasMfaEnabled() {
return !!this.usersStore.currentUser?.mfaEnabled;
},
},
mounted() {
let emailLabel = this.$locale.baseText('auth.email');
const ldapLoginLabel = this.settingsStore.ldapLoginLabel;
const isLdapLoginEnabled = this.settingsStore.isLdapLoginEnabled;
if (isLdapLoginEnabled && ldapLoginLabel) {
emailLabel = ldapLoginLabel;
}
this.FORM_CONFIG = {
title: this.$locale.baseText('auth.signin'),
buttonText: this.$locale.baseText('auth.signin'),
redirectText: this.$locale.baseText('forgotPassword'),
inputs: [
{
name: 'email',
properties: {
label: emailLabel,
type: 'email',
required: true,
...(!isLdapLoginEnabled && { validationRules: [{ name: 'VALID_EMAIL' }] }),
showRequiredAsterisk: false,
validateOnBlur: false,
autocomplete: 'email',
capitalize: true,
},
},
{
name: 'password',
properties: {
label: this.$locale.baseText('auth.password'),
type: 'password',
required: true,
showRequiredAsterisk: false,
validateOnBlur: false,
autocomplete: 'current-password',
capitalize: true,
},
},
],
};
import type { IFormBoxConfig } from '@/Interface';
import { MFA_AUTHENTICATION_REQUIRED_ERROR_CODE, VIEWS, MFA_FORM } from '@/constants';
if (!this.settingsStore.isDesktopDeployment) {
this.FORM_CONFIG.redirectLink = '/forgot-password';
}
},
methods: {
async onMFASubmitted(form: { token?: string; recoveryCode?: string }) {
await this.login({
email: this.email,
password: this.password,
token: form.token,
recoveryCode: form.recoveryCode,
});
},
async onEmailPasswordSubmitted(form: { email: string; password: string }) {
await this.login(form);
},
isRedirectSafe() {
const redirect = this.getRedirectQueryParameter();
return redirect.startsWith('/') || redirect.startsWith(window.location.origin);
},
getRedirectQueryParameter() {
let redirect = '';
if (typeof this.$route.query?.redirect === 'string') {
redirect = decodeURIComponent(this.$route.query?.redirect);
}
return redirect;
},
async login(form: { email: string; password: string; token?: string; recoveryCode?: string }) {
try {
this.loading = true;
await this.usersStore.loginWithCreds({
email: form.email,
password: form.password,
mfaToken: form.token,
mfaRecoveryCode: form.recoveryCode,
});
this.loading = false;
if (this.settingsStore.isCloudDeployment) {
try {
await this.cloudPlanStore.checkForCloudPlanData();
} catch (error) {
console.warn('Failed to check for cloud plan data', error);
}
}
await this.settingsStore.getSettings();
this.clearAllStickyNotifications();
const usersStore = useUsersStore();
const settingsStore = useSettingsStore();
const cloudPlanStore = useCloudPlanStore();
this.$telemetry.track('User attempted to login', {
result: this.showMfaView ? 'mfa_success' : 'success',
});
const route = useRoute();
const router = useRouter();
if (this.isRedirectSafe()) {
const redirect = this.getRedirectQueryParameter();
if (redirect.startsWith('http')) {
window.location.href = redirect;
return;
}
const toast = useToast();
const locale = useI18n();
const telemetry = useTelemetry();
void this.$router.push(redirect);
return;
}
const loading = ref(false);
const showMfaView = ref(false);
const email = ref('');
const password = ref('');
const reportError = ref(false);
await this.$router.push({ name: VIEWS.HOMEPAGE });
} catch (error) {
if (error.errorCode === MFA_AUTHENTICATION_REQUIRED_ERROR_CODE) {
this.showMfaView = true;
this.cacheCredentials(form);
return;
}
this.$telemetry.track('User attempted to login', {
result: this.showMfaView ? 'mfa_token_rejected' : 'credentials_error',
});
if (!this.showMfaView) {
this.showError(error, this.$locale.baseText('auth.signin.error'));
this.loading = false;
return;
}
this.reportError = true;
}
},
onBackClick(fromForm: string) {
this.reportError = false;
if (fromForm === MFA_FORM.MFA_TOKEN) {
this.showMfaView = false;
this.loading = false;
}
},
onFormChanged(toForm: string) {
if (toForm === MFA_FORM.MFA_RECOVERY_CODE) {
this.reportError = false;
}
},
cacheCredentials(form: { email: string; password: string }) {
this.email = form.email;
this.password = form.password;
},
},
const ldapLoginLabel = computed(() => settingsStore.ldapLoginLabel);
const isLdapLoginEnabled = computed(() => settingsStore.isLdapLoginEnabled);
const emailLabel = computed(() => {
let label = locale.baseText('auth.email');
if (isLdapLoginEnabled.value && ldapLoginLabel.value) {
label = ldapLoginLabel.value;
}
return label;
});
const redirectLink = computed(() => {
if (!settingsStore.isDesktopDeployment) {
return '/forgot-password';
}
return undefined;
});
const formConfig: IFormBoxConfig = reactive({
title: locale.baseText('auth.signin'),
buttonText: locale.baseText('auth.signin'),
redirectText: locale.baseText('forgotPassword'),
redirectLink: redirectLink.value,
inputs: [
{
name: 'email',
properties: {
label: emailLabel.value,
type: 'email',
required: true,
...(!isLdapLoginEnabled.value && { validationRules: [{ name: 'VALID_EMAIL' }] }),
showRequiredAsterisk: false,
validateOnBlur: false,
autocomplete: 'email',
capitalize: true,
},
},
{
name: 'password',
properties: {
label: locale.baseText('auth.password'),
type: 'password',
required: true,
showRequiredAsterisk: false,
validateOnBlur: false,
autocomplete: 'current-password',
capitalize: true,
},
},
],
});
const onMFASubmitted = async (form: { token?: string; recoveryCode?: string }) => {
await login({
email: email.value,
password: password.value,
token: form.token,
recoveryCode: form.recoveryCode,
});
};
const isFormWithEmailAndPassword = (values: {
[key: string]: string;
}): values is { email: string; password: string } => {
return 'email' in values && 'password' in values;
};
const onEmailPasswordSubmitted = async (form: { [key: string]: string }) => {
if (!isFormWithEmailAndPassword(form)) return;
await login(form);
};
const isRedirectSafe = () => {
const redirect = getRedirectQueryParameter();
return redirect.startsWith('/') || redirect.startsWith(window.location.origin);
};
const getRedirectQueryParameter = () => {
let redirect = '';
if (typeof route.query?.redirect === 'string') {
redirect = decodeURIComponent(route.query?.redirect);
}
return redirect;
};
const login = async (form: {
email: string;
password: string;
token?: string;
recoveryCode?: string;
}) => {
try {
loading.value = true;
await usersStore.loginWithCreds({
email: form.email,
password: form.password,
mfaToken: form.token,
mfaRecoveryCode: form.recoveryCode,
});
loading.value = false;
if (settingsStore.isCloudDeployment) {
try {
await cloudPlanStore.checkForCloudPlanData();
} catch (error) {
console.warn('Failed to check for cloud plan data', error);
}
}
await settingsStore.getSettings();
toast.clearAllStickyNotifications();
telemetry.track('User attempted to login', {
result: showMfaView.value ? 'mfa_success' : 'success',
});
if (isRedirectSafe()) {
const redirect = getRedirectQueryParameter();
if (redirect.startsWith('http')) {
window.location.href = redirect;
return;
}
void router.push(redirect);
return;
}
await router.push({ name: VIEWS.HOMEPAGE });
} catch (error) {
if (error.errorCode === MFA_AUTHENTICATION_REQUIRED_ERROR_CODE) {
showMfaView.value = true;
cacheCredentials(form);
return;
}
telemetry.track('User attempted to login', {
result: showMfaView.value ? 'mfa_token_rejected' : 'credentials_error',
});
if (!showMfaView.value) {
toast.showError(error, locale.baseText('auth.signin.error'));
loading.value = false;
return;
}
reportError.value = true;
}
};
const onBackClick = (fromForm: string) => {
reportError.value = false;
if (fromForm === MFA_FORM.MFA_TOKEN) {
showMfaView.value = false;
loading.value = false;
}
};
const onFormChanged = (toForm: string) => {
if (toForm === MFA_FORM.MFA_RECOVERY_CODE) {
reportError.value = false;
}
};
const cacheCredentials = (form: { email: string; password: string }) => {
email.value = form.email;
password.value = form.password;
};
</script>
<template>
<div>
<AuthView
v-if="!showMfaView"
:form="FORM_CONFIG"
:form="formConfig"
:form-loading="loading"
:with-sso="true"
data-test-id="signin-form"