Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat(api): return education verification as a status-discriminated result (#45165)

yyh749754fcd911
diff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.py
index 772b78ff6d7..4da163c1976 100644
--- a/api/controllers/console/workspace/account.py
+++ b/api/controllers/console/workspace/account.py
@@ -6,7 +6,7 @@ from typing import Annotated, Literal
from flask import request
from flask_restx import Resource
-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, RootModel, field_validator, model_validator
from pydantic.json_schema import SkipJsonSchema
from werkzeug.exceptions import NotFound
@@ -203,10 +203,26 @@ class AccountIntegrateListResponse(ResponseModel):
data: list[AccountIntegrateResponse]
-class EducationVerifyResponse(ResponseModel):
+class EducationVerifyEligibleResponse(ResponseModel):
+ status: Literal["eligible"]
token: str
+class EducationVerifyNotEligibleResponse(ResponseModel):
+ status: Literal["not_eligible"]
+
+
+class EducationVerifyResponse(
+ RootModel[
+ Annotated[
+ EducationVerifyEligibleResponse | EducationVerifyNotEligibleResponse,
+ Field(discriminator="status"),
+ ]
+ ]
+):
+ """Education verification result: a token for an eligible account, none for an ineligible one."""
+
+
class EducationActivateResponse(ResponseModel):
message: str
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 2ce595e7631..14515e8b59f 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -25413,6 +25413,13 @@ Rate limit exceeded
| is_student | boolean | | Yes |
| result | boolean | | Yes |
+#### EducationVerifyEligibleResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| status | string | | Yes |
+| token | string | | Yes |
+
#### EducationVerifyLimitError
Rate limit exceeded
@@ -25421,11 +25428,19 @@ Rate limit exceeded
| ---- | ---- | ----------- | -------- |
| EducationVerifyLimitError | | Rate limit exceeded | |
+#### EducationVerifyNotEligibleResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| status | string | | Yes |
+
#### EducationVerifyResponse
+Education verification result: a token for an eligible account, none for an ineligible one.
+
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| token | string | | Yes |
+| EducationVerifyResponse | [EducationVerifyEligibleResponse](#educationverifyeligibleresponse)<br>[EducationVerifyNotEligibleResponse](#educationverifynoteligibleresponse) | Education verification result: a token for an eligible account, none for an ineligible one. | |
#### EmailAlreadyInUseError
diff --git a/api/services/account/adapters.py b/api/services/account/adapters.py
index 364305c70a1..8780e7afe0b 100644
--- a/api/services/account/adapters.py
+++ b/api/services/account/adapters.py
@@ -4,9 +4,9 @@ import logging
import secrets
import uuid
from collections.abc import Sequence
-from datetime import UTC, datetime, timedelta
+from datetime import timedelta
from hashlib import sha256
-from typing import override
+from typing import assert_never, override
from pydantic import TypeAdapter, ValidationError
from redis import RedisError
@@ -62,6 +62,8 @@ from services.entities.account_entities import (
AccountDeletionChallenge,
AccountEducationActivation,
AccountEducationAutocomplete,
+ AccountEducationEligible,
+ AccountEducationNotEligible,
AccountEducationStatus,
AccountEducationVerification,
)
@@ -269,7 +271,13 @@ class BillingAccountEducationGateway(AccountEducationGateway):
@override
def verify(self, *, account_id: str) -> AccountEducationVerification:
result = BillingService.EducationIdentity.verify(account_id=account_id)
- return AccountEducationVerification(token=result.token)
+ match result.status:
+ case "eligible":
+ return AccountEducationEligible(token=result.token)
+ case "not_eligible":
+ return AccountEducationNotEligible()
+ case _:
+ assert_never(result.status)
@override
def activate(
@@ -293,11 +301,10 @@ class BillingAccountEducationGateway(AccountEducationGateway):
@override
def status(self, account_id: str) -> AccountEducationStatus:
result = BillingService.EducationIdentity.status(account_id)
- expire_at = result.expire_at
return AccountEducationStatus(
result=result.result,
is_student=result.is_student,
- expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if expire_at else None,
+ expire_at=result.expire_at,
allow_refresh=result.allow_refresh,
)
diff --git a/api/services/billing_client/billing.openapi.json b/api/services/billing_client/billing.openapi.json
index 01e528e6101..4386c5085c4 100644
--- a/api/services/billing_client/billing.openapi.json
+++ b/api/services/billing_client/billing.openapi.json
@@ -4,7 +4,7 @@
"title": "",
"version": "0.0.1"
},
- "x-dify-saas-commit": "16c5186fecc57e802bf69673f58093bf0dcb77c2",
+ "x-dify-saas-commit": "04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a",
"paths": {
"/v1/subscription/info": {
"get": {
@@ -833,16 +833,21 @@
"type": "object",
"properties": {
"result": {
- "type": "boolean"
+ "type": "boolean",
+ "description": "True when the account has an education identity that has not expired yet. False when it has\n none or its latest identity has expired."
},
"is_student": {
- "type": "boolean"
+ "type": "boolean",
+ "description": "Always equal to `result`."
},
"expire_at": {
- "type": "string"
+ "type": "string",
+ "description": "Expiry of the account's latest education identity, as an RFC 3339 UTC timestamp\n (for example `2027-10-30T08:00:00Z`). `1997-01-01T00:00:00Z` when the account has no education identity.",
+ "format": "date-time"
},
"allow_refresh": {
- "type": "boolean"
+ "type": "boolean",
+ "description": "True when the latest education identity expires within the configured number of refresh days\n before or after now. False when the account has no education identity."
}
},
"required": [
@@ -1408,11 +1413,21 @@
"type": "object",
"properties": {
"token": {
- "type": "string"
+ "type": "string",
+ "description": "Verification token to pass to CreateEducationIdentity. Empty when status is `not_eligible`."
+ },
+ "status": {
+ "enum": [
+ "eligible",
+ "not_eligible"
+ ],
+ "type": "string",
+ "description": "`eligible`: the account email matches an education institution domain and `token` is set.\n `not_eligible`: the account email matches no education institution domain and `token` is empty."
}
},
"required": [
- "token"
+ "token",
+ "status"
]
}
}
diff --git a/api/services/billing_client/billing.py b/api/services/billing_client/billing.py
index f910945c592..20d1c755273 100644
--- a/api/services/billing_client/billing.py
+++ b/api/services/billing_client/billing.py
@@ -1,5 +1,5 @@
# Code generated by api/dev/generate_billing_client.py from billing.openapi.json. DO NOT EDIT.
-# dify-saas commit: 16c5186fecc57e802bf69673f58093bf0dcb77c2
+# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a
from datetime import datetime
from typing import Literal
@@ -62,7 +62,7 @@ class DownloadComplianceDocumentReq(BillingModel):
class GetEducationIdentityStatusReply(BillingModel):
result: bool
is_student: bool
- expire_at: str
+ expire_at: datetime
allow_refresh: bool
@@ -209,6 +209,7 @@ class QuotaReserveReq(BillingModel):
class VerifyEducationIdentityReply(BillingModel):
token: str
+ status: Literal["eligible", "not_eligible"]
def subscription_get_subscription_info(*, tenant_id: str, exclude_vector_space: bool) -> GetSubscriptionInfoReply:
diff --git a/api/services/billing_client/saas.openapi.json b/api/services/billing_client/saas.openapi.json
index 1a1245f6799..1fe53165268 100644
--- a/api/services/billing_client/saas.openapi.json
+++ b/api/services/billing_client/saas.openapi.json
@@ -4,7 +4,7 @@
"title": "",
"version": "0.0.1"
},
- "x-dify-saas-commit": "16c5186fecc57e802bf69673f58093bf0dcb77c2",
+ "x-dify-saas-commit": "04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a",
"paths": {
"/v1/account": {
"delete": {
diff --git a/api/services/billing_client/saas.py b/api/services/billing_client/saas.py
index 20d716090dd..cb836378245 100644
--- a/api/services/billing_client/saas.py
+++ b/api/services/billing_client/saas.py
@@ -1,5 +1,5 @@
# Code generated by api/dev/generate_billing_client.py from saas.openapi.json. DO NOT EDIT.
-# dify-saas commit: 16c5186fecc57e802bf69673f58093bf0dcb77c2
+# dify-saas commit: 04f8d88cc15c5f62f14f8843a54f3e2e7e09ee5a
from datetime import datetime
from typing import Literal
diff --git a/api/services/billing_client/transport.py b/api/services/billing_client/transport.py
index d81619ac721..e429fd061e3 100644
--- a/api/services/billing_client/transport.py
+++ b/api/services/billing_client/transport.py
@@ -55,6 +55,9 @@ ENFORCED_RESPONSE_PATHS: frozenset[str] = frozenset(
"/quota/release",
"/quota/balance",
"/quota/consume-capped",
+ # A salvaged `status` or `expire_at` would misreport eligibility or break the expiry timestamp.
+ "/education/verify",
+ "/education/status",
# Network access replies already required validation and gate access control.
"/tenants/{tenant_id}/network-access-groups",
"/tenants/{tenant_id}/network-access-groups/{group_id}",
diff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.py
index cbd9f7355c3..e31e331db26 100644
--- a/api/services/entities/account_entities.py
+++ b/api/services/entities/account_entities.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
+from typing import Literal
@dataclass(frozen=True, slots=True)
@@ -238,8 +239,17 @@ type AccountChangeEmailTokenData = (
@dataclass(frozen=True, slots=True)
-class AccountEducationVerification:
+class AccountEducationEligible:
token: str
+ status: Literal["eligible"] = "eligible"
+
+
+@dataclass(frozen=True, slots=True)
+class AccountEducationNotEligible:
+ status: Literal["not_eligible"] = "not_eligible"
+
+
+type AccountEducationVerification = AccountEducationEligible | AccountEducationNotEligible
@dataclass(frozen=True, slots=True)
@@ -251,7 +261,7 @@ class AccountEducationActivation:
class AccountEducationStatus:
result: bool
is_student: bool
- expire_at: datetime | None
+ expire_at: datetime
allow_refresh: bool
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_account.py b/api/tests/unit_tests/controllers/console/workspace/test_account.py
index 19b5dd14030..c80753fd53d 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_account.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_account.py
@@ -84,6 +84,9 @@ from services.account_errors import (
)
from services.entities.account_entities import (
AccountEducationActivation,
+ AccountEducationEligible,
+ AccountEducationNotEligible,
+ AccountEducationVerification,
AccountIntegrationStatus,
AccountProfileChanges,
ChangeEmailVerification,
@@ -225,6 +228,43 @@ class TestWorkspaceAccountCases:
role="Student",
)
+ @pytest.mark.parametrize(
+ ("verification", "expected"),
+ [
+ (
+ AccountEducationEligible(token="education-token"),
+ {"status": "eligible", "token": "education-token"},
+ ),
+ (AccountEducationNotEligible(), {"status": "not_eligible"}),
+ ],
+ )
+ def test_verify_returns_status_discriminated_result(
+ self,
+ app: Flask,
+ account_application_services: ApplicationServices,
+ verification: AccountEducationVerification,
+ expected: dict[str, str],
+ ) -> None:
+ request_context = RequestContext(
+ request_id="request-1",
+ trace_id=None,
+ account_id="account-1",
+ active_workspace_id="workspace-1",
+ )
+
+ with (
+ app.test_request_context("/account/education/verify", method="GET"),
+ patch(
+ "controllers.console.workspace.account.application_services",
+ return_value=account_application_services,
+ ),
+ patch.object(account_application_services.accounts.education, "verify", lambda _context: verification),
+ ):
+ api = EducationVerifyApi()
+ result = inspect.unwrap(api.get)(api, request_context)
+
+ assert result == expected
+
def test_verify_maps_rate_limit_error(self, app: Flask) -> None:
education = MagicMock()
education.verify.side_effect = account_errors.EducationRateLimitExceededError
diff --git a/api/tests/unit_tests/services/account/test_adapters.py b/api/tests/unit_tests/services/account/test_adapters.py
index 042fb72e98d..c2b9b7858d1 100644
--- a/api/tests/unit_tests/services/account/test_adapters.py
+++ b/api/tests/unit_tests/services/account/test_adapters.py
@@ -1,7 +1,9 @@
+from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from hashlib import sha256
from unittest.mock import MagicMock, call, create_autospec, patch
+import httpx
import pytest
from redis import RedisError
from sqlalchemy import select
@@ -27,14 +29,18 @@ from services.account.adapters import (
TokenManagerChangeEmailTokenGateway,
)
from services.account_errors import AccountDeletionRateLimitError
-from services.billing_client import billing
+from services.billing_client import billing, transport
from services.entities.account_activation_entities import InvitationLookup, InvitationToken
from services.entities.account_entities import (
AccountChangeEmailNewEmailToken,
AccountEducationActivation,
AccountEducationAutocomplete,
+ AccountEducationEligible,
+ AccountEducationNotEligible,
AccountEducationStatus,
+ AccountEducationVerification,
)
+from services.errors.billing import BillingUpstreamInvalidResponseError
from tests.helpers.unit.account_domain import AccountDomain
@@ -191,13 +197,61 @@ def test_rbac_member_access_sync_enqueues_joined_member_sync_when_enabled() -> N
delay.assert_called_once_with("workspace-1", "account-1", operator_account_id=None)
-def test_education_gateway_normalizes_billing_status_timestamp() -> None:
+ ("reply", "expected"),
+ [
+ (
+ billing.VerifyEducationIdentityReply(token="education-token", status="eligible"),
+ AccountEducationEligible(token="education-token"),
+ ),
+ (billing.VerifyEducationIdentityReply(token="", status="not_eligible"), AccountEducationNotEligible()),
+ ],
+)
+def test_education_gateway_maps_verification_status(
+ reply: billing.VerifyEducationIdentityReply, expected: AccountEducationVerification
+) -> None:
+ gateway = BillingAccountEducationGateway()
+
+ with patch("services.account.adapters.BillingService.EducationIdentity.verify", return_value=reply):
+ result = gateway.verify(account_id="account-1")
+
+ assert result == expected
+
+
+ ("read", "body"),
+ [
+ (lambda gateway: gateway.verify(account_id="account-1"), {"token": ""}),
+ (
+ lambda gateway: gateway.status("account-1"),
+ {"result": False, "is_student": False, "expire_at": "", "allow_refresh": False},
+ ),
+ ],
+)
+def test_education_gateway_rejects_invalid_billing_replies(
+ monkeypatch: pytest.MonkeyPatch,
+ config_overrides: Callable[..., None],
+ read: Callable[[BillingAccountEducationGateway], object],
+ body: dict[str, object],
+) -> None:
+ config_overrides(BILLING_API_URL="http://billing/v1")
+ monkeypatch.setattr(
+ transport,
+ "_http_client",
+ httpx.Client(transport=httpx.MockTransport(lambda _request: httpx.Response(200, json=body))),
+ )
+
+ with pytest.raises(BillingUpstreamInvalidResponseError):
+ read(BillingAccountEducationGateway())
+
+
+def test_education_gateway_reads_billing_status_timestamp() -> None:
gateway = BillingAccountEducationGateway()
with patch(
"services.account.adapters.BillingService.EducationIdentity.status",
return_value=billing.GetEducationIdentityStatusReply(
- result=True, is_student=True, expire_at="2027-01-01T00:00:00+00:00", allow_refresh=False
+ result=True, is_student=True, expire_at="2027-01-01T00:00:00Z", allow_refresh=False
),
):
result = gateway.status("account-1")
@@ -249,16 +303,16 @@ def test_education_gateway_maps_autocomplete_reply() -> None:
assert result == AccountEducationAutocomplete(data=("Example University",), curr_page=0, has_next=True)
-def test_education_gateway_reads_empty_expiry_as_none() -> None:
+def test_education_gateway_reads_no_identity_expiry() -> None:
gateway = BillingAccountEducationGateway()
with patch(
"services.account.adapters.BillingService.EducationIdentity.status",
return_value=billing.GetEducationIdentityStatusReply(
- result=False, is_student=False, expire_at="", allow_refresh=False
+ result=False, is_student=False, expire_at="1997-01-01T00:00:00Z", allow_refresh=False
),
):
- assert gateway.status("account-1").expire_at is None
+ assert gateway.status("account-1").expire_at == datetime(1997, 1, 1, tzinfo=UTC)
def test_billing_email_policy_preserves_suspended_domain_reason() -> None:
diff --git a/api/tests/unit_tests/services/test_account_education_service.py b/api/tests/unit_tests/services/test_account_education_service.py
index fd32bd0c97d..33a903ec492 100644
--- a/api/tests/unit_tests/services/test_account_education_service.py
+++ b/api/tests/unit_tests/services/test_account_education_service.py
@@ -19,8 +19,9 @@ from services.billing_service import BillingService
from services.entities.account_entities import (
AccountEducationActivation,
AccountEducationAutocomplete,
+ AccountEducationEligible,
+ AccountEducationNotEligible,
AccountEducationStatus,
- AccountEducationVerification,
)
from tests.helpers.unit.model_factories import make_account
@@ -76,16 +77,26 @@ def test_verify_reads_account_before_billing_gateway_call(
def verify(*, account_id: str) -> billing.VerifyEducationIdentityReply:
lookup.assert_called_once_with(account_id)
events.append("verify")
- return billing.VerifyEducationIdentityReply(token="education-token")
+ return billing.VerifyEducationIdentityReply(token="education-token", status="eligible")
billing_call = mocker.patch.object(BillingService.EducationIdentity, "verify", side_effect=verify)
- assert service.verify(_context()) == AccountEducationVerification(token="education-token")
+ assert service.verify(_context()) == AccountEducationEligible(token="education-token")
assert events == ["check", "increment", "verify"]
billing_call.assert_called_once_with(account_id="account-1")
assert all(call.args[1] == "verification:[email protected]" for call in commands.call_args_list)
+def test_verify_returns_not_eligible_without_token(service: AccountEducationService, mocker: MockerFixture) -> None:
+ mocker.patch.object(
+ BillingService.EducationIdentity,
+ "verify",
+ return_value=billing.VerifyEducationIdentityReply(token="", status="not_eligible"),
+ )
+
+ assert service.verify(_context()) == AccountEducationNotEligible()
+
+
def test_status_and_autocomplete_delegate_framework_neutral_contracts(
service: AccountEducationService, mocker: MockerFixture
) -> None:
diff --git a/api/tests/unit_tests/services/test_billing_service.py b/api/tests/unit_tests/services/test_billing_service.py
index cb810b557b0..18114137a62 100644
--- a/api/tests/unit_tests/services/test_billing_service.py
+++ b/api/tests/unit_tests/services/test_billing_service.py
@@ -321,7 +321,7 @@ class TestBillingServiceAccountAndEducation:
)
def test_education_reads_return_the_generated_replies(self):
- verify = billing.VerifyEducationIdentityReply(token="token")
+ verify = billing.VerifyEducationIdentityReply(token="token", status="eligible")
status = billing.GetEducationIdentityStatusReply(
result=True, is_student=True, expire_at="2027-01-01T00:00:00+00:00", allow_refresh=False
)
diff --git a/packages/contracts/generated/api/console/account/types.gen.ts b/packages/contracts/generated/api/console/account/types.gen.ts
index 8d6853690a8..d640b59cf58 100644
--- a/packages/contracts/generated/api/console/account/types.gen.ts
+++ b/packages/contracts/generated/api/console/account/types.gen.ts
@@ -168,9 +168,13 @@ export type EducationAutocompleteResponse = {
has_next: boolean
}
-export type EducationVerifyResponse = {
- token: string
-}
+export type EducationVerifyResponse =
+ | ({
+ status: 'eligible'
+ } & EducationVerifyEligibleResponse)
+ | ({
+ status: 'not_eligible'
+ } & EducationVerifyNotEligibleResponse)
export type EducationVerifyLimitError = ErrorResponse & {
code: 'education_verify_limit'
@@ -226,6 +230,15 @@ export type AccountProfilePatchPayload = {
timezone?: string
}
+export type EducationVerifyEligibleResponse = {
+ status: 'eligible'
+ token: string
+}
+
+export type EducationVerifyNotEligibleResponse = {
+ status: 'not_eligible'
+}
+
export type AccountIntegrateResponse = {
created_at?: number | null
is_bound: boolean
diff --git a/packages/contracts/generated/api/console/account/zod.gen.ts b/packages/contracts/generated/api/console/account/zod.gen.ts
index fbd4e6558e6..8629ed80134 100644
--- a/packages/contracts/generated/api/console/account/zod.gen.ts
+++ b/packages/contracts/generated/api/console/account/zod.gen.ts
@@ -308,13 +308,6 @@ export const zEducationAutocompleteResponse = z.object({
has_next: z.boolean(),
})
-/**
- * EducationVerifyResponse
- */
-export const zEducationVerifyResponse = z.object({
- token: z.string(),
-})
-
/**
* EducationVerifyLimitError
*
@@ -418,6 +411,31 @@ export const zAccountProfilePatchPayload = z
})
.strict()
+/**
+ * EducationVerifyEligibleResponse
+ */
+export const zEducationVerifyEligibleResponse = z.object({
+ status: z.literal('eligible'),
+ token: z.string(),
+})
+
+/**
+ * EducationVerifyNotEligibleResponse
+ */
+export const zEducationVerifyNotEligibleResponse = z.object({
+ status: z.literal('not_eligible'),
+})
+
+/**
+ * EducationVerifyResponse
+ *
+ * Education verification result: a token for an eligible account, none for an ineligible one.
+ */
+export const zEducationVerifyResponse = z.discriminatedUnion('status', [
+ zEducationVerifyEligibleResponse,
+ zEducationVerifyNotEligibleResponse,
+])
+
/**
* AccountIntegrateResponse
*/
diff --git a/web/app/education/verify/__tests__/verify-flow.spec.tsx b/web/app/education/verify/__tests__/verify-flow.spec.tsx
index db171057e40..905be996b6c 100644
--- a/web/app/education/verify/__tests__/verify-flow.spec.tsx
+++ b/web/app/education/verify/__tests__/verify-flow.spec.tsx
@@ -45,7 +45,7 @@ function renderFlow({
describe('EducationVerifyFlow', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockRequestVerification.mockResolvedValue({ token: 'education-token' })
+ mockRequestVerification.mockResolvedValue({ status: 'eligible', token: 'education-token' })
})
it('shows an already verified account', () => {
@@ -61,7 +61,7 @@ describe('EducationVerifyFlow', () => {
})
it('requests one token on entry and replaces the route with the application form', async () => {
- mockRequestVerification.mockResolvedValue({ token: 'education token' })
+ mockRequestVerification.mockResolvedValue({ status: 'eligible', token: 'education token' })
const { queryClient, wrapper } = createConsoleQueryWrapper({
accountProfile: { email: '[email protected]' },
educationStatus: { allow_refresh: false, is_student: false },
@@ -81,8 +81,8 @@ describe('EducationVerifyFlow', () => {
})
})
- it('renders the rejection state when verification returns no token', async () => {
- mockRequestVerification.mockResolvedValue({ token: null })
+ it('renders the rejection state when the account is not eligible', async () => {
+ mockRequestVerification.mockResolvedValue({ status: 'not_eligible' })
renderFlow({})
@@ -102,7 +102,7 @@ describe('EducationVerifyFlow', () => {
expect(
await screen.findByRole('heading', { name: 'common.errorBoundary.title' }),
).toBeInTheDocument()
- mockRequestVerification.mockResolvedValue({ token: 'retry-token' })
+ mockRequestVerification.mockResolvedValue({ status: 'eligible', token: 'retry-token' })
await user.click(screen.getByRole('button', { name: 'common.errorBoundary.tryAgain' }))
await waitFor(() =>
expect(mockReplace).toHaveBeenCalledWith('/education/apply?token=retry-token'),
diff --git a/web/app/education/verify/verify-flow.tsx b/web/app/education/verify/verify-flow.tsx
index a4429be2eb4..352d0fa8c06 100644
--- a/web/app/education/verify/verify-flow.tsx
+++ b/web/app/education/verify/verify-flow.tsx
@@ -1,6 +1,9 @@
'use client'
-import type { EducationStatusResponse } from '@dify/contracts/api/console/account/types.gen'
+import type {
+ EducationStatusResponse,
+ EducationVerifyResponse,
+} from '@dify/contracts/api/console/account/types.gen'
import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen'
import type { ReactNode } from 'react'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
@@ -16,9 +19,7 @@ import { consoleClient, consoleQuery } from '@/service/console'
import { EducationStatusCard } from '../status-card'
import UserInfo from '../user-info'
-class EducationVerificationRejectedError extends Error {}
-
-type EducationVerificationRequest = () => Promise<{ token?: string | null }>
+type EducationVerificationRequest = () => Promise<EducationVerifyResponse>
const selectEducationStatus = ({ allow_refresh, is_student }: EducationStatusResponse) => ({
allowRefresh: allow_refresh,
@@ -30,15 +31,6 @@ const selectEducationPlanEnabled = ({ education }: GetFeaturesResponse) => educa
const requestEducationVerification: EducationVerificationRequest = () =>
consoleClient.account.education.verify.get({}, { context: { silent: true } })
-async function requestEducationVerificationToken(
- requestVerification: EducationVerificationRequest,
-) {
- const response = await requestVerification()
- if (!response.token) throw new EducationVerificationRejectedError()
-
- return response.token
-}
-
export default function EducationVerifyPage() {
return <EducationVerifyFlow />
}
@@ -67,13 +59,13 @@ export function EducationVerifyFlow({
}),
)
const {
- error: verificationError,
+ data: verification,
isError: isVerificationError,
mutate: verifyEducation,
reset: resetVerification,
} = useMutation({
- mutationKey: ['education', 'verification-token'],
- mutationFn: () => requestEducationVerificationToken(requestVerification),
+ mutationKey: ['education', 'verification'],
+ mutationFn: () => requestVerification(),
})
const startVerification = useCallback(() => {
@@ -81,8 +73,9 @@ export function EducationVerifyFlow({
verificationStartedRef.current = true
verifyEducation(undefined, {
- onSuccess: (token) => {
- router.replace(`/education/apply?token=${encodeURIComponent(token)}`)
+ onSuccess: (result) => {
+ if (result.status === 'eligible')
+ router.replace(`/education/apply?token=${encodeURIComponent(result.token)}`)
},
})
}, [router, verifyEducation])
@@ -116,7 +109,7 @@ export function EducationVerifyFlow({
if (isAlreadyVerified) return <EducationVerifiedContent />
- if (verificationError instanceof EducationVerificationRejectedError) {
+ if (verification?.status === 'not_eligible') {
return (
<EducationVerifyContent>
<EducationStatusCard