verify passcode on the OAuth 2.0 callback page if user enable 2FA

This commit is contained in:
MaysWind
2025-10-26 15:18:40 +08:00
parent c854dbaab4
commit fd4036f0c8
22 changed files with 73 additions and 4 deletions
+29
View File
@@ -2,6 +2,7 @@ package api
import ( import (
"encoding/json" "encoding/json"
"errors"
"github.com/pquerna/otp/totp" "github.com/pquerna/otp/totp"
@@ -427,6 +428,34 @@ func (a *AuthorizationsApi) OAuth2CallbackAuthorizeHandler(c *core.WebContext) (
return nil, errs.ErrUserPasswordWrong return nil, errs.ErrUserPasswordWrong
} }
if a.CurrentConfig().EnableTwoFactor {
twoFactorSetting, err := a.twoFactorAuthorizations.GetUserTwoFactorSettingByUid(c, uid)
if err != nil && !errors.Is(err, errs.ErrTwoFactorIsNotEnabled) {
log.Errorf(c, "[authorizations.OAuth2CallbackAuthorizeHandler] failed to check two-factor setting for user \"uid:%d\", because %s", user.Uid, err.Error())
return nil, errs.Or(err, errs.ErrSystemError)
}
if twoFactorSetting != nil {
if credential.Passcode == "" {
return nil, errs.ErrPasscodeEmpty
}
if !totp.Validate(credential.Passcode, twoFactorSetting.Secret) {
log.Warnf(c, "[authorizations.OAuth2CallbackAuthorizeHandler] passcode is invalid for user \"uid:%d\"", uid)
err = a.CheckAndIncreaseFailureCount(c, uid)
if err != nil {
log.Warnf(c, "[authorizations.OAuth2CallbackAuthorizeHandler] cannot auth for user \"uid:%d\", because %s", uid, err.Error())
return nil, errs.Or(err, errs.ErrFailureCountLimitReached)
}
return nil, errs.ErrPasscodeInvalid
}
}
}
userExternalAuth := &models.UserExternalAuth{ userExternalAuth := &models.UserExternalAuth{
Uid: user.Uid, Uid: user.Uid,
ExternalAuthType: tokenContext.ExternalAuthType, ExternalAuthType: tokenContext.ExternalAuthType,
+1
View File
@@ -9,4 +9,5 @@ var (
ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NormalSubcategoryTwofactor, 2, http.StatusUnauthorized, "two-factor backup code does not exist") ErrTwoFactorRecoveryCodeNotExist = NewNormalError(NormalSubcategoryTwofactor, 2, http.StatusUnauthorized, "two-factor backup code does not exist")
ErrTwoFactorIsNotEnabled = NewNormalError(NormalSubcategoryTwofactor, 3, http.StatusBadRequest, "two-factor is not enabled") ErrTwoFactorIsNotEnabled = NewNormalError(NormalSubcategoryTwofactor, 3, http.StatusBadRequest, "two-factor is not enabled")
ErrTwoFactorAlreadyEnabled = NewNormalError(NormalSubcategoryTwofactor, 4, http.StatusBadRequest, "two-factor has already been enabled") ErrTwoFactorAlreadyEnabled = NewNormalError(NormalSubcategoryTwofactor, 4, http.StatusBadRequest, "two-factor has already been enabled")
ErrPasscodeEmpty = NewNormalError(NormalSubcategoryTwofactor, 5, http.StatusUnauthorized, "passcode is empty")
) )
+1
View File
@@ -17,4 +17,5 @@ type OAuth2CallbackRequest struct {
// OAuth2CallbackLoginRequest represents all parameters of OAuth 2.0 callback login request // OAuth2CallbackLoginRequest represents all parameters of OAuth 2.0 callback login request
type OAuth2CallbackLoginRequest struct { type OAuth2CallbackLoginRequest struct {
Password string `json:"password" binding:"omitempty,min=6,max=128"` Password string `json:"password" binding:"omitempty,min=6,max=128"`
Passcode string `json:"passcode" binding:"omitempty,notBlank,len=6"`
} }
+1
View File
@@ -18,6 +18,7 @@ export enum KnownErrorCode {
ApiNotFound = 100001, ApiNotFound = 100001,
ValidatorError = 200000, ValidatorError = 200000,
UserEmailNotVerified = 201020, UserEmailNotVerified = 201020,
TwoFactorAuthorizationPasscodeEmpty = 203005,
TransactionCannotCreateInThisTime = 205017, TransactionCannotCreateInThisTime = 205017,
TransactionCannotModifyInThisTime = 205018, TransactionCannotModifyInThisTime = 205018,
TransactionPictureNotFound = 211001 TransactionPictureNotFound = 211001
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Zwei-Faktor-Authentifizierung ist nicht aktiviert", "two-factor is not enabled": "Zwei-Faktor-Authentifizierung ist nicht aktiviert",
"two-factor has already been enabled": "Zwei-Faktor-Authentifizierung ist bereits aktiviert", "two-factor has already been enabled": "Zwei-Faktor-Authentifizierung ist bereits aktiviert",
"two-factor backup code does not exist": "Zwei-Faktor-Backup-Code existiert nicht", "two-factor backup code does not exist": "Zwei-Faktor-Backup-Code existiert nicht",
"passcode is empty": "Passcode is empty",
"account id is invalid": "Konto-ID ist ungültig", "account id is invalid": "Konto-ID ist ungültig",
"account not found": "Konto nicht gefunden", "account not found": "Konto nicht gefunden",
"account type is invalid": "Kontotyp ist ungültig", "account type is invalid": "Kontotyp ist ungültig",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Two-factor is not enabled", "two-factor is not enabled": "Two-factor is not enabled",
"two-factor has already been enabled": "Two-factor has already been enabled", "two-factor has already been enabled": "Two-factor has already been enabled",
"two-factor backup code does not exist": "Two-factor backup code does not exist", "two-factor backup code does not exist": "Two-factor backup code does not exist",
"passcode is empty": "Passcode is empty",
"account id is invalid": "Account ID is invalid", "account id is invalid": "Account ID is invalid",
"account not found": "Account is not found", "account not found": "Account is not found",
"account type is invalid": "Account type is invalid", "account type is invalid": "Account type is invalid",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "El doble factor no está habilitado", "two-factor is not enabled": "El doble factor no está habilitado",
"two-factor has already been enabled": "Ya se ha habilitado el doble factor", "two-factor has already been enabled": "Ya se ha habilitado el doble factor",
"two-factor backup code does not exist": "El código de respaldo de dos factores no existe", "two-factor backup code does not exist": "El código de respaldo de dos factores no existe",
"passcode is empty": "Passcode is empty",
"account id is invalid": "El ID de cuenta no es válido", "account id is invalid": "El ID de cuenta no es válido",
"account not found": "No se encuentra la cuenta", "account not found": "No se encuentra la cuenta",
"account type is invalid": "El tipo de cuenta no es válido", "account type is invalid": "El tipo de cuenta no es válido",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "L'authentification à deux facteurs n'est pas activée", "two-factor is not enabled": "L'authentification à deux facteurs n'est pas activée",
"two-factor has already been enabled": "L'authentification à deux facteurs a déjà été activée", "two-factor has already been enabled": "L'authentification à deux facteurs a déjà été activée",
"two-factor backup code does not exist": "Le code de sauvegarde à deux facteurs n'existe pas", "two-factor backup code does not exist": "Le code de sauvegarde à deux facteurs n'existe pas",
"passcode is empty": "Passcode is empty",
"account id is invalid": "L'ID du compte est invalide", "account id is invalid": "L'ID du compte est invalide",
"account not found": "Compte non trouvé", "account not found": "Compte non trouvé",
"account type is invalid": "Le type de compte est invalide", "account type is invalid": "Le type de compte est invalide",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "L'autenticazione a due fattori non è abilitata", "two-factor is not enabled": "L'autenticazione a due fattori non è abilitata",
"two-factor has already been enabled": "L'autenticazione a due fattori è già abilitata", "two-factor has already been enabled": "L'autenticazione a due fattori è già abilitata",
"two-factor backup code does not exist": "Il codice di backup a due fattori non esiste", "two-factor backup code does not exist": "Il codice di backup a due fattori non esiste",
"passcode is empty": "Passcode is empty",
"account id is invalid": "ID conto non valido", "account id is invalid": "ID conto non valido",
"account not found": "Conto non trovato", "account not found": "Conto non trovato",
"account type is invalid": "Tipo di conto non valido", "account type is invalid": "Tipo di conto non valido",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "二要素が有効になっていません", "two-factor is not enabled": "二要素が有効になっていません",
"two-factor has already been enabled": "二要素はすでに有効になっています", "two-factor has already been enabled": "二要素はすでに有効になっています",
"two-factor backup code does not exist": "二要素バックアップコードが存在しません", "two-factor backup code does not exist": "二要素バックアップコードが存在しません",
"passcode is empty": "Passcode is empty",
"account id is invalid": "口座IDは無効です", "account id is invalid": "口座IDは無効です",
"account not found": "口座が見つかりません", "account not found": "口座が見つかりません",
"account type is invalid": "口座タイプは無効です", "account type is invalid": "口座タイプは無効です",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "2단계 인증이 활성화되지 않았습니다", "two-factor is not enabled": "2단계 인증이 활성화되지 않았습니다",
"two-factor has already been enabled": "2단계 인증이 이미 활성화되었습니다", "two-factor has already been enabled": "2단계 인증이 이미 활성화되었습니다",
"two-factor backup code does not exist": "2단계 백업 코드가 존재하지 않습니다", "two-factor backup code does not exist": "2단계 백업 코드가 존재하지 않습니다",
"passcode is empty": "Passcode is empty",
"account id is invalid": "계좌 ID가 유효하지 않습니다", "account id is invalid": "계좌 ID가 유효하지 않습니다",
"account not found": "계좌를 찾을 수 없습니다", "account not found": "계좌를 찾을 수 없습니다",
"account type is invalid": "계좌 유형이 유효하지 않습니다", "account type is invalid": "계좌 유형이 유효하지 않습니다",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Twee-stapsverificatie is niet ingeschakeld", "two-factor is not enabled": "Twee-stapsverificatie is niet ingeschakeld",
"two-factor has already been enabled": "Twee-stapsverificatie is al ingeschakeld", "two-factor has already been enabled": "Twee-stapsverificatie is al ingeschakeld",
"two-factor backup code does not exist": "Back-upcode voor twee-stapsverificatie bestaat niet", "two-factor backup code does not exist": "Back-upcode voor twee-stapsverificatie bestaat niet",
"passcode is empty": "Passcode is empty",
"account id is invalid": "Rekening-ID is ongeldig", "account id is invalid": "Rekening-ID is ongeldig",
"account not found": "Rekening niet gevonden", "account not found": "Rekening niet gevonden",
"account type is invalid": "Rekeningtype is ongeldig", "account type is invalid": "Rekeningtype is ongeldig",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Autenticação em duas etapas não está ativada", "two-factor is not enabled": "Autenticação em duas etapas não está ativada",
"two-factor has already been enabled": "Autenticação em duas etapas já foi ativada", "two-factor has already been enabled": "Autenticação em duas etapas já foi ativada",
"two-factor backup code does not exist": "Código de backup de duas etapas não existe", "two-factor backup code does not exist": "Código de backup de duas etapas não existe",
"passcode is empty": "Passcode is empty",
"account id is invalid": "ID da conta é inválido", "account id is invalid": "ID da conta é inválido",
"account not found": "Conta não encontrada", "account not found": "Conta não encontrada",
"account type is invalid": "Tipo de conta é inválido", "account type is invalid": "Tipo de conta é inválido",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Двухфакторная аутентификация не включена", "two-factor is not enabled": "Двухфакторная аутентификация не включена",
"two-factor has already been enabled": "Двухфакторная аутентификация уже включена", "two-factor has already been enabled": "Двухфакторная аутентификация уже включена",
"two-factor backup code does not exist": "Резервный код двухфакторной аутентификации не существует", "two-factor backup code does not exist": "Резервный код двухфакторной аутентификации не существует",
"passcode is empty": "Passcode is empty",
"account id is invalid": "ID счета недействителен", "account id is invalid": "ID счета недействителен",
"account not found": "Счет не найден", "account not found": "Счет не найден",
"account type is invalid": "Тип счета недействителен", "account type is invalid": "Тип счета недействителен",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "ยังไม่ได้เปิดใช้งานการยืนยันสองขั้นตอน", "two-factor is not enabled": "ยังไม่ได้เปิดใช้งานการยืนยันสองขั้นตอน",
"two-factor has already been enabled": "การยืนยันสองขั้นตอนถูกเปิดใช้งานแล้ว", "two-factor has already been enabled": "การยืนยันสองขั้นตอนถูกเปิดใช้งานแล้ว",
"two-factor backup code does not exist": "รหัสสำรองสองขั้นตอนไม่พบ", "two-factor backup code does not exist": "รหัสสำรองสองขั้นตอนไม่พบ",
"passcode is empty": "Passcode is empty",
"account id is invalid": "รหัสบัญชีไม่ถูกต้อง", "account id is invalid": "รหัสบัญชีไม่ถูกต้อง",
"account not found": "ไม่พบบัญชี", "account not found": "ไม่พบบัญชี",
"account type is invalid": "ประเภทบัญชีไม่ถูกต้อง", "account type is invalid": "ประเภทบัญชีไม่ถูกต้อง",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Двофакторна автентифікація не увімкнена", "two-factor is not enabled": "Двофакторна автентифікація не увімкнена",
"two-factor has already been enabled": "Двофакторна автентифікація вже увімкнена", "two-factor has already been enabled": "Двофакторна автентифікація вже увімкнена",
"two-factor backup code does not exist": "Резервного коду двофакторної автентифікації не існує", "two-factor backup code does not exist": "Резервного коду двофакторної автентифікації не існує",
"passcode is empty": "Passcode is empty",
"account id is invalid": "ID рахунку недійсний", "account id is invalid": "ID рахунку недійсний",
"account not found": "Рахунок не знайдено", "account not found": "Рахунок не знайдено",
"account type is invalid": "Тип рахунку недійсний", "account type is invalid": "Тип рахунку недійсний",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "Xác thực hai yếu tố chưa được bật", "two-factor is not enabled": "Xác thực hai yếu tố chưa được bật",
"two-factor has already been enabled": "Xác thực hai yếu tố đã được bật", "two-factor has already been enabled": "Xác thực hai yếu tố đã được bật",
"two-factor backup code does not exist": "Mã sao lưu hai yếu tố không tồn tại", "two-factor backup code does not exist": "Mã sao lưu hai yếu tố không tồn tại",
"passcode is empty": "Passcode is empty",
"account id is invalid": "ID tài khoản không hợp lệ", "account id is invalid": "ID tài khoản không hợp lệ",
"account not found": "Không tìm thấy tài khoản", "account not found": "Không tìm thấy tài khoản",
"account type is invalid": "Loại tài khoản không hợp lệ", "account type is invalid": "Loại tài khoản không hợp lệ",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "两步验证没有启用", "two-factor is not enabled": "两步验证没有启用",
"two-factor has already been enabled": "两步验证已经启用", "two-factor has already been enabled": "两步验证已经启用",
"two-factor backup code does not exist": "两步验证备用码不存在", "two-factor backup code does not exist": "两步验证备用码不存在",
"passcode is empty": "验证码为空",
"account id is invalid": "账户ID无效", "account id is invalid": "账户ID无效",
"account not found": "账户不存在", "account not found": "账户不存在",
"account type is invalid": "账户类型无效", "account type is invalid": "账户类型无效",
+1
View File
@@ -1110,6 +1110,7 @@
"two-factor is not enabled": "二步驟驗證沒有啟用", "two-factor is not enabled": "二步驟驗證沒有啟用",
"two-factor has already been enabled": "二步驟驗證已經啟用", "two-factor has already been enabled": "二步驟驗證已經啟用",
"two-factor backup code does not exist": "二步驟驗證備用碼不存在", "two-factor backup code does not exist": "二步驟驗證備用碼不存在",
"passcode is empty": "驗證碼為空",
"account id is invalid": "帳戶ID無效", "account id is invalid": "帳戶ID無效",
"account not found": "帳戶不存在", "account not found": "帳戶不存在",
"account type is invalid": "帳戶類型無效", "account type is invalid": "帳戶類型無效",
+1
View File
@@ -1,3 +1,4 @@
export interface OAuth2CallbackLoginRequest { export interface OAuth2CallbackLoginRequest {
readonly password?: string; readonly password?: string;
readonly passcode?: string;
} }
+3 -2
View File
@@ -191,11 +191,12 @@ export const useRootStore = defineStore('root', () => {
}); });
} }
function authorizeOAuth2({ password, token }: { password?: string, token: string }): Promise<AuthResponse> { function authorizeOAuth2({ password, passcode, token }: { password?: string, passcode?: string, token: string }): Promise<AuthResponse> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
services.authorizeOAuth2({ services.authorizeOAuth2({
req: { req: {
password password,
passcode
}, },
token token
}).then(response => { }).then(response => {
+22 -2
View File
@@ -39,7 +39,7 @@
type="password" type="password"
autocomplete="password" autocomplete="password"
:autofocus="true" :autofocus="true"
:disabled="loggingInByOAuth2" :disabled="show2faInput || loggingInByOAuth2"
:label="tt('Password')" :label="tt('Password')"
:placeholder="tt('Your password')" :placeholder="tt('Your password')"
v-model="password" v-model="password"
@@ -47,6 +47,19 @@
/> />
</v-col> </v-col>
<v-col cols="12" v-show="show2faInput">
<v-text-field
type="number"
autocomplete="one-time-code"
ref="passcodeInput"
:disabled="loggingInByOAuth2"
:label="tt('Passcode')"
:placeholder="tt('Passcode')"
v-model="passcode"
@keyup.enter="verifyAndLogin"
/>
</v-col>
<v-col cols="12"> <v-col cols="12">
<v-btn block type="submit" :disabled="!password || loggingInByOAuth2" @click="verifyAndLogin"> <v-btn block type="submit" :disabled="!password || loggingInByOAuth2" @click="verifyAndLogin">
{{ tt('Continue') }} {{ tt('Continue') }}
@@ -97,7 +110,7 @@
<script setup lang="ts"> <script setup lang="ts">
import SnackBar from '@/components/desktop/SnackBar.vue'; import SnackBar from '@/components/desktop/SnackBar.vue';
import { computed, useTemplateRef } from 'vue'; import { ref, computed, useTemplateRef } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useTheme } from 'vuetify'; import { useTheme } from 'vuetify';
@@ -153,6 +166,9 @@ const {
const snackbar = useTemplateRef<SnackBarType>('snackbar'); const snackbar = useTemplateRef<SnackBarType>('snackbar');
const passcode = ref<string>('');
const show2faInput = ref<boolean>(false);
const isDarkMode = computed<boolean>(() => theme.global.name.value === ThemeType.Dark); const isDarkMode = computed<boolean>(() => theme.global.name.value === ThemeType.Dark);
const oauth2ProviderDisplayName = computed<string>(() => getLocalizedOAuth2ProviderName(props.provider ?? '', getOIDCCustomDisplayNames())); const oauth2ProviderDisplayName = computed<string>(() => getLocalizedOAuth2ProviderName(props.provider ?? '', getOIDCCustomDisplayNames()));
const oauth2LoginDisplayName = computed<string>(() => getLocalizedOAuth2LoginText(props.provider ?? '', getOIDCCustomDisplayNames())); const oauth2LoginDisplayName = computed<string>(() => getLocalizedOAuth2LoginText(props.provider ?? '', getOIDCCustomDisplayNames()));
@@ -195,6 +211,7 @@ function verifyAndLogin(): void {
rootStore.authorizeOAuth2({ rootStore.authorizeOAuth2({
password: password.value, password: password.value,
passcode: passcode.value,
token: props.token || '' token: props.token || ''
}).then(authResponse => { }).then(authResponse => {
loggingInByOAuth2.value = false; loggingInByOAuth2.value = false;
@@ -206,6 +223,9 @@ function verifyAndLogin(): void {
if (isUserVerifyEmailEnabled() && error.error && error.error.errorCode === KnownErrorCode.UserEmailNotVerified && error.error.context && error.error.context.email) { if (isUserVerifyEmailEnabled() && error.error && error.error.errorCode === KnownErrorCode.UserEmailNotVerified && error.error.context && error.error.context.email) {
router.push(`/verify_email?email=${encodeURIComponent(error.error.context.email)}&emailSent=${error.error.context.hasValidEmailVerifyToken || false}`); router.push(`/verify_email?email=${encodeURIComponent(error.error.context.email)}&emailSent=${error.error.context.hasValidEmailVerifyToken || false}`);
return; return;
} else if (error.error && error.error.errorCode === KnownErrorCode.TwoFactorAuthorizationPasscodeEmpty) {
show2faInput.value = true;
return;
} }
if (!error.processed) { if (!error.processed) {