Compare commits

...

87 Commits

Author SHA1 Message Date
copilot-swe-agent[bot]
19a179a47c Add missing user items to GetTranslatedUserItems, init.go, init_data.json.template, and UserFields
Co-authored-by: hsluoyz <3787410+hsluoyz@users.noreply.github.com>
2026-02-20 02:15:22 +00:00
copilot-swe-agent[bot]
dff052f1d2 Initial plan 2026-02-20 01:59:53 +00:00
Yang Luo
7b4873734b feat: fix "--config" flag to actually load specified configuration file (#5139) 2026-02-19 02:13:29 +08:00
Yang Luo
8d2290944a fix: add back Payment.ProductName and ProductDisplayName fields for backward compatibility 2026-02-18 19:28:14 +08:00
Yang Luo
6a2bba1627 feat: fix field visibility logic for provider types in ProviderEditPage (#5134) 2026-02-18 15:22:28 +08:00
Yang Luo
07554bbbe5 feat: fix Alipay OAuth provider by loading private key from cert object (#5119) 2026-02-17 14:42:21 +08:00
karatekaneen
a050403ee5 feat: fix bug that PKCE fails when multiple custom OAuth providers are configured (#5117) 2026-02-16 23:32:07 +08:00
IsAurora6
118eb0af80 feat: Optimize the display of payment products. (#5115) 2026-02-16 16:32:02 +08:00
Yang Luo
c16aebe642 fix: update README slogan 2026-02-16 02:33:45 +08:00
Yang Luo
3b8e7c9da2 fix: extend application with reverse proxy fields (#5113) 2026-02-16 02:23:47 +08:00
Yang Luo
4d5de767b0 fix: sync frontend i18n strings 2026-02-16 02:01:48 +08:00
Yang Luo
54bf8eae5c fix: improve category column UI in app list page 2026-02-16 01:46:06 +08:00
IsAurora6
1731b74fa0 fix: fix issue that dummy payments failed when there were too many items in the order (#5108) 2026-02-15 22:35:59 +08:00
Yang Luo
6e1e5dd569 feat: add scope-to-tool permission checking for Casdoor MCP server (#5104) 2026-02-15 22:31:35 +08:00
Yang Luo
b183359daf fix: rename order state PaymentFailed to Failed and improve UI (#5107) 2026-02-15 21:52:24 +08:00
Yang Luo
3cb9df3723 feat: [mcp-5] add Application.Category and Application.Type fields for agent applications (MCP, A2A) (#5102) 2026-02-15 21:28:00 +08:00
Yang Luo
9d1e5c10d0 feat: [mcp-4] implement RFC 8707 Resource Indicators for OAuth 2.0 (#5098) 2026-02-15 18:03:22 +08:00
Yang Luo
ef84c4b0b4 feat: [mcp-3] implement OAuth 2.0 Dynamic Client Registration (RFC 7591) (#5097) 2026-02-15 17:25:44 +08:00
Yang Luo
5a108bd921 fix: [mcp-2] add OAuth 2.0 Authorization Server Metadata endpoints (RFC 8414) (#5094) 2026-02-15 17:00:40 +08:00
Yang Luo
ac671ec1ee fix: rename to wellknown_oidc_discovery.go 2026-02-15 16:42:00 +08:00
Yang Luo
7814caf2ab feat: implement RFC 9728 OAuth 2.0 Protected Resource Metadata for MCP server discovery (#5092) 2026-02-15 16:40:48 +08:00
Yang Luo
f966f4a0f9 feat: fix Dummy payment provider returning zero price in NotifyResult (#5090) 2026-02-15 02:31:56 +08:00
Yang Luo
a4b1a068a8 feat: fix Azure SQL DB panic by migrating to the official go-mssqldb fork (#5082) 2026-02-15 01:52:06 +08:00
Yang Luo
362797678d feat: fix nil pointer panic in update-user API for non-existent account items (#5084) 2026-02-15 01:44:26 +08:00
Yang Luo
7879e1bf09 fix: fix Dummy payment provider to simulate external callback flow (#5080) 2026-02-15 00:18:09 +08:00
IsAurora6
c246f102c9 feat: fix issue that User.Cart cannot be updated without org account items (#5076) 2026-02-14 22:32:58 +08:00
IsAurora6
37d1c4910c feat: Fixed an error when clicking the “delete” button on the cart list page. (#5075) 2026-02-13 20:49:08 +08:00
Yang Luo
3bcde7cb7c feat: add Cart and payment fields to organization account items (#5070) 2026-02-13 10:40:37 +08:00
Yang Luo
6a90d21941 fix: add CreatedTime field to cart items and sort by timestamp (#5066) 2026-02-13 10:36:20 +08:00
Yang Luo
80b4c0b1a7 feat: remove special handling for Dummy payment provider (#5068) 2026-02-13 10:06:14 +08:00
Yang Luo
eb5a422026 feat: replace DisableSsl boolean with SslMode enum for Email providers (#5063) 2026-02-13 02:15:20 +08:00
DacongDA
f7bd70e0a3 feat: improve tab height UI in application edit page (#5055) 2026-02-12 21:57:57 +08:00
Copilot
5e7dbe4b56 feat: fix CAPTCHA rule enforcement in verification code flow (#5009) 2026-02-12 21:22:47 +08:00
Yang Luo
bd1fca2f32 feat: Add LDAP group/OU hierarchy syncing with automatic user membership (#5052) 2026-02-12 17:11:20 +08:00
IsAurora6
3d4cc42f1f feat: mark cart items as invalid when product is removed, renamed, or currency is changed. (#5050) 2026-02-12 00:46:54 +08:00
Yang Luo
1836cab44d feat: fix icons for 5 payment providers 2026-02-11 01:42:37 +08:00
Yang Luo
75b18635f7 feat: fix issue that Webhook records for set-password API were missing user context (#5008) 2026-02-11 01:32:11 +08:00
Yang Luo
47cd44c7ce feat: support "snsapi_privateinfo" scope in WeCom OAuth provider to support fetching Emails (#5034) 2026-02-11 01:21:29 +08:00
Yang Luo
090ca97dcd feat: bind provider IDs in WeCom/DingTalk/Lark syncers (#5033) 2026-02-11 01:04:26 +08:00
Yang Luo
bed01b31f1 feat: add AWS IAM syncer (#5043) 2026-02-11 01:00:41 +08:00
Yang Luo
c8f8f88d85 feat: add "Existing Field" category for token attributes table in application edit page (#5041) 2026-02-11 00:58:50 +08:00
IsAurora6
7acb303995 feat: Fixed cart anomalies when updating product information. (#5039) 2026-02-10 20:58:18 +08:00
IsAurora6
2607f8d3e5 feat: fix DingTalk syncer to fetch nested departments recursively (#5036) 2026-02-10 18:11:03 +08:00
IsAurora6
481db33e58 feat: Optimize the display of rechargeable product content on the ProductStorePage.js. (#5028) 2026-02-09 20:28:18 +08:00
DacongDA
f556c7e11f feat: add PaginateSelect widget to fix non-pagination fetch API issue (#5023) 2026-02-09 20:07:41 +08:00
IsAurora6
f590992f28 feat: update i18n translations (#5021) 2026-02-09 00:05:08 +08:00
Yang Luo
80f9db0fa2 feat: move captcha provider validation from frontend filter to backend check (#5019) 2026-02-08 02:16:47 +08:00
Yang Luo
0748661d2a feat: store OAuth tokens per provider instead of single originalToken field (#5016) 2026-02-08 01:22:24 +08:00
Yang Luo
83552ed143 feat: fix renderRightDropdown() scrollbar UI bug 2026-02-08 00:45:46 +08:00
Yang Luo
8cb8541f96 feat: add Plan.IsExclusive field for single subscription enforcement (#5004) 2026-02-07 01:23:22 +08:00
Yang Luo
5b646a726c fix: fix format issue in DuplicateInfo 2026-02-07 00:51:11 +08:00
Yang Luo
19b9586670 fix: fix broken links for role/plan/user/payment columns (#4999) 2026-02-07 00:46:36 +08:00
Yang Luo
73f8d19c5f fix: de-duplicate i18n translation keys in frontend and backend (#4997) 2026-02-07 00:35:46 +08:00
Yang Luo
04da531df3 fix: sync all i18n strings 2026-02-07 00:18:07 +08:00
Yang Luo
d97558051d fix: add duplicate key detection tests for i18n JSON files (#4994) 2026-02-07 00:17:53 +08:00
Yang Luo
ac55355290 fix: deduplicate the i18n strings 2026-02-06 21:42:10 +08:00
Yang Luo
a2da380be4 feat: add organization sync to DingTalk syncer (#4989) 2026-02-06 20:39:31 +08:00
IsAurora6
ecf8039c5d feat: Add cart icon to ProductStore/ProductBuy and quantity controls to ProductStore/ProductBuy/CartList. (#4984) 2026-02-05 23:07:22 +08:00
Yang Luo
0a6948034c feat: add OAuth 2.0 Token Exchange (RFC 8693) support (#4981) 2026-02-05 19:12:39 +08:00
Yang Luo
442f8fb19e feat: fix DeleteSession to handle missing sessions gracefully (#4979) 2026-02-05 15:41:15 +08:00
Yang Luo
b771add9e3 feat: auto-redirect OAuth signup to callback URL (#4941) 2026-02-05 15:18:33 +08:00
Yang Luo
df8e9fceea feat: disable /forget API when "Forgot Password?" signin item is hidden (#4977) 2026-02-04 23:04:00 +08:00
Yang Luo
d674f0c33d feat: update Swagger docs 2026-02-03 21:34:38 +08:00
buzaslan129
1e1b5273d9 feat: expose get-all-* Casbin endpoints in Swagger (#4952) 2026-02-03 21:32:50 +08:00
IsAurora6
cf5e88915c feat: The order.products display is divided into two parts. Remove the "startTime" and "endTime", and add an updateTime field. (#4968) 2026-02-03 21:12:27 +08:00
Yang Luo
c8973e6c9e feat: add Cloud PNVS SMS provider (#4964) 2026-02-03 02:00:08 +08:00
Yang Luo
87ea451561 feat: support group sync in Google Workspace syncer (#4962) 2026-02-03 01:58:28 +08:00
Yang Luo
8f32779b42 feat: fix invitation code group assignment for OAuth provider signup (#4961) 2026-02-03 01:23:36 +08:00
Yang Luo
aba471b4e8 feat: install lsof in ALLINONE Docker image (#4958) 2026-02-02 23:51:49 +08:00
DacongDA
72b70c3b03 feat: use sqlite DB instead of mariadb for all-in-one Docker image (#4949) 2026-02-02 00:13:14 +08:00
DacongDA
a1c56894c7 feat: add tabs to user edit page (#4945) 2026-02-01 14:01:28 +08:00
Yang Luo
a9ae9394c7 feat: add Linux machine login via LDAP with POSIX attributes (#4944) 2026-01-31 22:37:29 +08:00
Yang Luo
5f0fa5f23e feat: fix properties field xlsx import issue in user list page (#4943) 2026-01-31 01:49:36 +08:00
Yang Luo
f99aa047a9 feat: add Org.AccountItems.Tab field to have tabs in user edit page (#4892) 2026-01-30 21:56:35 +08:00
Yang Luo
1d22b7ebd0 feat: prevent duplicate webhook events from redundant payment notifications (#4936) 2026-01-30 21:56:09 +08:00
IsAurora6
d147053329 feat: Optimize the display of the products column on the order and payment, adjust the color of the “Add to Cart” button. (#4933) 2026-01-30 14:03:15 +08:00
IsAurora6
0f8cd92be4 feat: resolve returnUrl redirection failure of UserEditPage (#4931) 2026-01-29 09:37:47 +08:00
DacongDA
7ea6f1296d feat: fix i18n/generate.go bug in handling "\" (#4930) 2026-01-28 23:35:23 +08:00
Yang Luo
db8c649f5e feat: include payment status in notify-payment webhook payload (#4929) 2026-01-28 19:59:10 +08:00
DacongDA
a06d003589 feat: make codeChallenge dynamic for custom OAuth provider (#4924) 2026-01-28 17:56:28 +08:00
Jacob
33298e44d4 feat(ldap-sync): support syncing phone country code and formatting mobile number (#4919) 2026-01-28 14:09:52 +08:00
IsAurora6
f4d86f8d92 feat: fix incorrect clearing of the returnUrl path parameter in redirects (#4920) 2026-01-28 10:51:44 +08:00
Yang Luo
af4337a1ae feat: add multi-address support to user edit page (#4916) 2026-01-27 21:46:41 +08:00
IsAurora6
81e650df65 feat: Optimize the display of the order price column and improve parameter passing in the OrderPay view mode. (#4912) 2026-01-27 12:17:15 +08:00
Yang Luo
fcea1e4c07 feat: add SCIM 2.0 syncer (#4909) 2026-01-27 01:47:50 +08:00
Yang Luo
639a8a47b1 feat: add Okta syncer (#4908) 2026-01-27 01:19:39 +08:00
Yang Luo
43f61d4426 feat: add Lark syncer (#4897) 2026-01-27 01:00:19 +08:00
182 changed files with 11426 additions and 2791 deletions

View File

@@ -51,22 +51,14 @@ COPY --from=FRONT --chown=$USER:$USER /web/build ./web/build
ENTRYPOINT ["/server"]
FROM debian:latest AS db
RUN apt update \
&& apt install -y \
mariadb-server \
mariadb-client \
&& rm -rf /var/lib/apt/lists/*
FROM db AS ALLINONE
FROM debian:latest AS ALLINONE
LABEL MAINTAINER="https://casdoor.org/"
ARG TARGETOS
ARG TARGETARCH
ENV BUILDX_ARCH="${TARGETOS:-linux}_${TARGETARCH:-amd64}"
RUN apt update
RUN apt install -y ca-certificates && update-ca-certificates
RUN apt install -y ca-certificates lsof && update-ca-certificates
WORKDIR /
COPY --from=BACK /go/src/casdoor/server_${BUILDX_ARCH} ./server

View File

@@ -1,5 +1,5 @@
<h1 align="center" style="border-bottom: none;">📦⚡️ Casdoor</h1>
<h3 align="center">An open-source UI-first Identity and Access Management (IAM) / Single-Sign-On (SSO) platform with web UI supporting OAuth 2.0, OIDC, SAML, CAS, LDAP, SCIM, WebAuthn, TOTP, MFA and RADIUS</h3>
<h3 align="center">An open-source AI-first Identity and Access Management (IAM) /AI MCP gateway and auth server with web UI supporting MCP, A2A, OAuth 2.1, OIDC, SAML, CAS, LDAP, SCIM, WebAuthn, TOTP, MFA, Face ID, Google Workspace, Azure AD</h3>
<p align="center">
<a href="#badge">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">

View File

@@ -59,6 +59,7 @@ p, *, *, GET, /api/get-qrcode, *, *
p, *, *, GET, /api/get-webhook-event, *, *
p, *, *, GET, /api/get-captcha-status, *, *
p, *, *, *, /api/login/oauth, *, *
p, *, *, POST, /api/oauth/register, *, *
p, *, *, GET, /api/get-application, *, *
p, *, *, GET, /api/get-organization-applications, *, *
p, *, *, GET, /api/get-user, *, *

View File

@@ -312,6 +312,29 @@ func (c *ApiController) Signup() {
userId := user.GetId()
util.LogInfo(c.Ctx, "API: [%s] is signed up as new user", userId)
// Check if this is an OAuth flow and automatically generate code
clientId := c.Ctx.Input.Query("clientId")
responseType := c.Ctx.Input.Query("responseType")
redirectUri := c.Ctx.Input.Query("redirectUri")
scope := c.Ctx.Input.Query("scope")
state := c.Ctx.Input.Query("state")
nonce := c.Ctx.Input.Query("nonce")
codeChallenge := c.Ctx.Input.Query("code_challenge")
// If OAuth parameters are present, generate OAuth code and return it
if clientId != "" && responseType == ResponseTypeCode {
code, err := object.GetOAuthCode(userId, clientId, "", "password", responseType, redirectUri, scope, state, nonce, codeChallenge, "", c.Ctx.Request.Host, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error(), nil)
return
}
resp := codeToResponse(code)
c.Data["json"] = resp
c.ServeJSON()
return
}
c.ResponseOk(userId)
}
@@ -665,6 +688,51 @@ func (c *ApiController) GetCaptcha() {
applicationId := c.Ctx.Input.Query("applicationId")
isCurrentProvider := c.Ctx.Input.Query("isCurrentProvider")
// When isCurrentProvider == "true", the frontend passes a provider ID instead of an application ID.
// In that case, skip application lookup and rule evaluation, and just return the provider config.
shouldSkipCaptcha := false
if isCurrentProvider != "true" {
application, err := object.GetApplication(applicationId)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), applicationId))
return
}
// Check the CAPTCHA rule to determine if CAPTCHA should be shown
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
// For Internet-Only rule, we can determine on the backend if CAPTCHA should be shown
// For other rules (Dynamic, Always), we need to return the CAPTCHA config
for _, providerItem := range application.Providers {
if providerItem.Provider == nil || providerItem.Provider.Category != "Captcha" {
continue
}
// For "None" rule, skip CAPTCHA
if providerItem.Rule == "None" || providerItem.Rule == "" {
shouldSkipCaptcha = true
} else if providerItem.Rule == "Internet-Only" {
// For Internet-Only rule, check if the client is from intranet
if !util.IsInternetIp(clientIp) {
// Client is from intranet, skip CAPTCHA
shouldSkipCaptcha = true
}
}
break // Only check the first CAPTCHA provider
}
if shouldSkipCaptcha {
c.ResponseOk(Captcha{Type: "none"})
return
}
}
captchaProvider, err := object.GetCaptchaProviderByApplication(applicationId, isCurrentProvider, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())

View File

@@ -161,12 +161,13 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob
nonce := c.Ctx.Input.Query("nonce")
challengeMethod := c.Ctx.Input.Query("code_challenge_method")
codeChallenge := c.Ctx.Input.Query("code_challenge")
resource := c.Ctx.Input.Query("resource")
if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
c.ResponseError(c.T("auth:Challenge method should be S256"))
return
}
code, err := object.GetOAuthCode(userId, clientId, form.Provider, form.SigninMethod, responseType, redirectUri, scope, state, nonce, codeChallenge, c.Ctx.Request.Host, c.GetAcceptLanguage())
code, err := object.GetOAuthCode(userId, clientId, form.Provider, form.SigninMethod, responseType, redirectUri, scope, state, nonce, codeChallenge, resource, c.Ctx.Request.Host, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error(), nil)
return
@@ -738,7 +739,12 @@ func (c *ApiController) Login() {
}
} else if provider.Category == "OAuth" || provider.Category == "Web3" {
// OAuth
idpInfo := object.FromProviderToIdpInfo(c.Ctx, provider)
idpInfo, err := object.FromProviderToIdpInfo(c.Ctx, provider)
if err != nil {
c.ResponseError(err.Error())
return
}
idpInfo.CodeVerifier = authForm.CodeVerifier
var idProvider idp.IdProvider
idProvider, err = idp.GetIdProvider(idpInfo, authForm.RedirectUri)
if err != nil {
@@ -866,10 +872,16 @@ func (c *ApiController) Login() {
return
}
if application.IsSignupItemRequired("Invitation code") {
c.ResponseError(c.T("check:Invitation code cannot be blank"))
// Check and validate invitation code
invitation, msg := object.CheckInvitationCode(application, organization, &authForm, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
}
invitationName := ""
if invitation != nil {
invitationName = invitation.Name
}
// Handle UseEmailAsUsername for OAuth and Web3
if organization.UseEmailAsUsername && userInfo.Email != "" {
@@ -936,11 +948,16 @@ func (c *ApiController) Login() {
IsDeleted: false,
SignupApplication: application.Name,
Properties: properties,
Invitation: invitationName,
InvitationCode: authForm.InvitationCode,
RegisterType: "Application Signup",
RegisterSource: fmt.Sprintf("%s/%s", application.Organization, application.Name),
}
if providerItem.SignupGroup != "" {
// Set group from invitation code if available, otherwise use provider's signup group
if invitation != nil && invitation.SignupGroup != "" {
user.Groups = []string{invitation.SignupGroup}
} else if providerItem.SignupGroup != "" {
user.Groups = []string{providerItem.SignupGroup}
}
@@ -955,6 +972,16 @@ func (c *ApiController) Login() {
c.ResponseError(fmt.Sprintf(c.T("auth:Failed to create user, user information is invalid: %s"), util.StructToJson(user)))
return
}
// Increment invitation usage count
if invitation != nil {
invitation.UsedCount += 1
_, err = object.UpdateInvitation(invitation.GetId(), invitation, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
}
}
// sync info from 3rd-party if possible

View File

@@ -303,6 +303,13 @@ func (c *ApiController) BatchEnforce() {
c.ResponseOk(res, keyRes)
}
// GetAllObjects
// @Title GetAllObjects
// @Tag Enforcer API
// @Description Get all objects for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-objects [get]
func (c *ApiController) GetAllObjects() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {
@@ -322,6 +329,13 @@ func (c *ApiController) GetAllObjects() {
c.ResponseOk(objects)
}
// GetAllActions
// @Title GetAllActions
// @Tag Enforcer API
// @Description Get all actions for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-actions [get]
func (c *ApiController) GetAllActions() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {
@@ -341,6 +355,13 @@ func (c *ApiController) GetAllActions() {
c.ResponseOk(actions)
}
// GetAllRoles
// @Title GetAllRoles
// @Tag Enforcer API
// @Description Get all roles for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-roles [get]
func (c *ApiController) GetAllRoles() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {

View File

@@ -103,7 +103,7 @@ func (c *ApiController) GetInvitationCodeInfo() {
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The application: %s does not exist"), applicationId))
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), applicationId))
return
}
@@ -230,7 +230,7 @@ func (c *ApiController) SendInvitation() {
return
}
if organization == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The organization: %s does not exist"), invitation.Owner))
c.ResponseError(fmt.Sprintf(c.T("auth:The organization: %s does not exist"), invitation.Owner))
return
}

74
controllers/oauth_dcr.go Normal file
View File

@@ -0,0 +1,74 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"net/http"
"github.com/casdoor/casdoor/object"
)
// DynamicClientRegister
// @Title DynamicClientRegister
// @Tag OAuth API
// @Description Register a new OAuth 2.0 client dynamically (RFC 7591)
// @Param organization query string false "The organization name (defaults to built-in)"
// @Param body body object.DynamicClientRegistrationRequest true "Client registration request"
// @Success 201 {object} object.DynamicClientRegistrationResponse
// @Failure 400 {object} object.DcrError
// @router /api/oauth/register [post]
func (c *ApiController) DynamicClientRegister() {
var req object.DynamicClientRegistrationRequest
err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
if err != nil {
c.Ctx.Output.Status = http.StatusBadRequest
c.Data["json"] = object.DcrError{
Error: "invalid_client_metadata",
ErrorDescription: "invalid request body: " + err.Error(),
}
c.ServeJSON()
return
}
// Get organization from query parameter or default to built-in
organization := c.Ctx.Input.Query("organization")
if organization == "" {
organization = "built-in"
}
// Register the client
response, dcrErr, err := object.RegisterDynamicClient(&req, organization)
if err != nil {
c.Ctx.Output.Status = http.StatusInternalServerError
c.Data["json"] = object.DcrError{
Error: "server_error",
ErrorDescription: err.Error(),
}
c.ServeJSON()
return
}
if dcrErr != nil {
c.Ctx.Output.Status = http.StatusBadRequest
c.Data["json"] = dcrErr
c.ServeJSON()
return
}
// Return 201 Created
c.Ctx.Output.Status = http.StatusCreated
c.Data["json"] = response
c.ServeJSON()
}

View File

@@ -16,6 +16,7 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
@@ -150,6 +151,26 @@ func (c *ApiController) AddSubscription() {
return
}
// Check if plan restricts user to one subscription
if subscription.Plan != "" {
plan, err := object.GetPlan(util.GetId(subscription.Owner, subscription.Plan))
if err != nil {
c.ResponseError(err.Error())
return
}
if plan != nil && plan.IsExclusive {
hasSubscription, err := object.HasActiveSubscriptionForPlan(subscription.Owner, subscription.User, subscription.Plan)
if err != nil {
c.ResponseError(err.Error())
return
}
if hasSubscription {
c.ResponseError(fmt.Sprintf("User already has an active subscription for plan: %s", subscription.Plan))
return
}
}
}
c.Data["json"] = wrapActionResponse(object.AddSubscription(&subscription))
c.ServeJSON()
}

View File

@@ -173,6 +173,10 @@ func (c *ApiController) GetOAuthToken() {
avatar := c.Ctx.Input.Query("avatar")
refreshToken := c.Ctx.Input.Query("refresh_token")
deviceCode := c.Ctx.Input.Query("device_code")
subjectToken := c.Ctx.Input.Query("subject_token")
subjectTokenType := c.Ctx.Input.Query("subject_token_type")
audience := c.Ctx.Input.Query("audience")
resource := c.Ctx.Input.Query("resource")
if clientId == "" && clientSecret == "" {
clientId, clientSecret, _ = c.Ctx.Request.BasicAuth()
@@ -219,6 +223,18 @@ func (c *ApiController) GetOAuthToken() {
if refreshToken == "" {
refreshToken = tokenRequest.RefreshToken
}
if subjectToken == "" {
subjectToken = tokenRequest.SubjectToken
}
if subjectTokenType == "" {
subjectTokenType = tokenRequest.SubjectTokenType
}
if audience == "" {
audience = tokenRequest.Audience
}
if resource == "" {
resource = tokenRequest.Resource
}
}
}
@@ -263,7 +279,7 @@ func (c *ApiController) GetOAuthToken() {
}
host := c.Ctx.Request.Host
token, err := object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, nonce, username, password, host, refreshToken, tag, avatar, c.GetAcceptLanguage())
token, err := object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, nonce, username, password, host, refreshToken, tag, avatar, c.GetAcceptLanguage(), subjectToken, subjectTokenType, audience, resource)
if err != nil {
c.ResponseError(err.Error())
return

View File

@@ -15,16 +15,20 @@
package controllers
type TokenRequest struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
GrantType string `json:"grant_type"`
Code string `json:"code"`
Verifier string `json:"code_verifier"`
Scope string `json:"scope"`
Nonce string `json:"nonce"`
Username string `json:"username"`
Password string `json:"password"`
Tag string `json:"tag"`
Avatar string `json:"avatar"`
RefreshToken string `json:"refresh_token"`
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
GrantType string `json:"grant_type"`
Code string `json:"code"`
Verifier string `json:"code_verifier"`
Scope string `json:"scope"`
Nonce string `json:"nonce"`
Username string `json:"username"`
Password string `json:"password"`
Tag string `json:"tag"`
Avatar string `json:"avatar"`
RefreshToken string `json:"refresh_token"`
SubjectToken string `json:"subject_token"`
SubjectTokenType string `json:"subject_token_type"`
Audience string `json:"audience"`
Resource string `json:"resource"` // RFC 8707 Resource Indicator
}

View File

@@ -942,7 +942,7 @@ func (c *ApiController) VerifyIdentification() {
}
if provider == nil {
c.ResponseError(fmt.Sprintf(c.T("provider:The provider: %s does not exist"), providerName))
c.ResponseError(fmt.Sprintf(c.T("auth:The provider: %s does not exist"), providerName))
return
}

View File

@@ -151,42 +151,33 @@ func (c *ApiController) SendVerificationCode() {
return
}
provider, err := object.GetCaptchaProviderByApplication(vform.ApplicationId, "false", c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
if provider != nil {
if vform.CaptchaType != provider.Type {
c.ResponseError(c.T("verification:Turing test failed."))
return
}
if provider.Type != "Default" {
vform.ClientSecret = provider.ClientSecret
}
if vform.CaptchaType != "none" {
if captchaProvider := captcha.GetCaptchaProvider(vform.CaptchaType); captchaProvider == nil {
c.ResponseError(c.T("general:don't support captchaProvider: ") + vform.CaptchaType)
return
} else if isHuman, err := captchaProvider.VerifyCaptcha(vform.CaptchaToken, provider.ClientId, vform.ClientSecret, provider.ClientId2); err != nil {
c.ResponseError(err.Error())
return
} else if !isHuman {
c.ResponseError(c.T("verification:Turing test failed."))
return
}
}
}
application, err := object.GetApplication(vform.ApplicationId)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), vform.ApplicationId))
return
}
// Check if "Forgot password?" signin item is visible when using forget verification
if vform.Method == ForgetVerification {
isForgotPasswordEnabled := false
for _, item := range application.SigninItems {
if item.Name == "Forgot password?" {
isForgotPasswordEnabled = item.Visible
break
}
}
// Block access if the signin item is not found or is explicitly hidden
if !isForgotPasswordEnabled {
c.ResponseError(c.T("verification:The forgot password feature is disabled"))
return
}
}
organization, err := object.GetOrganization(util.GetId(application.Owner, application.Organization))
if err != nil {
c.ResponseError(c.T(err.Error()))
@@ -198,6 +189,7 @@ func (c *ApiController) SendVerificationCode() {
}
var user *object.User
// Try to resolve user for CAPTCHA rule checking
// checkUser != "", means method is ForgetVerification
if vform.CheckUser != "" {
owner := application.Organization
@@ -215,18 +207,86 @@ func (c *ApiController) SendVerificationCode() {
c.ResponseError(c.T("check:The user is forbidden to sign in, please contact the administrator"))
return
}
}
// mfaUserSession != "", means method is MfaAuthVerification
if mfaUserSession := c.getMfaUserSession(); mfaUserSession != "" {
} else if mfaUserSession := c.getMfaUserSession(); mfaUserSession != "" {
// mfaUserSession != "", means method is MfaAuthVerification
user, err = object.GetUser(mfaUserSession)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if vform.Method == ResetVerification {
// For reset verification, get the current logged-in user
user = c.getCurrentUser()
} else if vform.Method == LoginVerification {
// For login verification, try to find user by email/phone for CAPTCHA check
// This is a preliminary lookup; the actual validation happens later in the switch statement
if vform.Type == object.VerifyTypeEmail && util.IsEmailValid(vform.Dest) {
user, err = object.GetUserByEmail(organization.Name, vform.Dest)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if vform.Type == object.VerifyTypePhone {
// Prefer resolving the user directly by phone, consistent with the later login switch,
// so that Dynamic CAPTCHA is not skipped due to missing/invalid country code.
user, err = object.GetUserByPhone(organization.Name, vform.Dest)
if err != nil {
c.ResponseError(err.Error())
return
}
}
}
// Determine username for CAPTCHA check
username := ""
if user != nil {
username = user.Name
} else if vform.CheckUser != "" {
username = vform.CheckUser
}
// Check if CAPTCHA should be enabled based on the rule (Dynamic/Always/Internet-Only)
enableCaptcha, err := object.CheckToEnableCaptcha(application, organization.Name, username, clientIp)
if err != nil {
c.ResponseError(err.Error())
return
}
// Only verify CAPTCHA if it should be enabled
if enableCaptcha {
captchaProvider, err := object.GetCaptchaProviderByApplication(vform.ApplicationId, "false", c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
if captchaProvider != nil {
if vform.CaptchaType != captchaProvider.Type {
c.ResponseError(c.T("verification:Turing test failed."))
return
}
if captchaProvider.Type != "Default" {
vform.ClientSecret = captchaProvider.ClientSecret
}
if vform.CaptchaType != "none" {
if captchaService := captcha.GetCaptchaProvider(vform.CaptchaType); captchaService == nil {
c.ResponseError(c.T("general:don't support captchaProvider: ") + vform.CaptchaType)
return
} else if isHuman, err := captchaService.VerifyCaptcha(vform.CaptchaToken, captchaProvider.ClientId, vform.ClientSecret, captchaProvider.ClientId2); err != nil {
c.ResponseError(err.Error())
return
} else if !isHuman {
c.ResponseError(c.T("verification:Turing test failed."))
return
}
}
}
}
sendResp := errors.New("invalid dest type")
var provider *object.Provider
switch vform.Type {
case object.VerifyTypeEmail:

View File

@@ -0,0 +1,45 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"github.com/casdoor/casdoor/object"
)
// GetOauthProtectedResourceMetadata
// @Title GetOauthProtectedResourceMetadata
// @Tag OAuth 2.0 API
// @Description Get OAuth 2.0 Protected Resource Metadata (RFC 9728)
// @Success 200 {object} object.OauthProtectedResourceMetadata
// @router /.well-known/oauth-protected-resource [get]
func (c *RootController) GetOauthProtectedResourceMetadata() {
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOauthProtectedResourceMetadata(host)
c.ServeJSON()
}
// GetOauthProtectedResourceMetadataByApplication
// @Title GetOauthProtectedResourceMetadataByApplication
// @Tag OAuth 2.0 API
// @Description Get OAuth 2.0 Protected Resource Metadata for specific application (RFC 9728)
// @Param application path string true "application name"
// @Success 200 {object} object.OauthProtectedResourceMetadata
// @router /.well-known/:application/oauth-protected-resource [get]
func (c *RootController) GetOauthProtectedResourceMetadataByApplication() {
application := c.Ctx.Input.Param(":application")
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOauthProtectedResourceMetadataByApplication(host, application)
c.ServeJSON()
}

View File

@@ -137,3 +137,29 @@ func (c *RootController) GetWebFingerByApplication() {
c.Ctx.Output.ContentType("application/jrd+json")
c.ServeJSON()
}
// GetOAuthServerMetadata
// @Title GetOAuthServerMetadata
// @Tag OAuth API
// @Description Get OAuth 2.0 Authorization Server Metadata (RFC 8414)
// @Success 200 {object} object.OidcDiscovery
// @router /.well-known/oauth-authorization-server [get]
func (c *RootController) GetOAuthServerMetadata() {
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOidcDiscovery(host, "")
c.ServeJSON()
}
// GetOAuthServerMetadataByApplication
// @Title GetOAuthServerMetadataByApplication
// @Tag OAuth API
// @Description Get OAuth 2.0 Authorization Server Metadata for specific application (RFC 8414)
// @Param application path string true "application name"
// @Success 200 {object} object.OidcDiscovery
// @router /.well-known/:application/oauth-authorization-server [get]
func (c *RootController) GetOAuthServerMetadataByApplication() {
application := c.Ctx.Input.Param(":application")
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOidcDiscovery(host, application)
c.ServeJSON()
}

View File

@@ -1,8 +1,10 @@
#!/bin/bash
if [ "${MYSQL_ROOT_PASSWORD}" = "" ] ;then MYSQL_ROOT_PASSWORD=123456 ;fi
service mariadb start
if [ -z "${driverName:-}" ]; then
export driverName=sqlite
fi
if [ -z "${dataSourceName:-}" ]; then
export dataSourceName="file:casdoor.db?cache=shared"
fi
mysqladmin -u root password ${MYSQL_ROOT_PASSWORD}
exec /server --createDatabase=true
exec /server

View File

@@ -18,7 +18,7 @@ type EmailProvider interface {
Send(fromAddress string, fromName string, toAddress []string, subject string, content string) error
}
func GetEmailProvider(typ string, clientId string, clientSecret string, host string, port int, disableSsl bool, endpoint string, method string, httpHeaders map[string]string, bodyMapping map[string]string, contentType string, enableProxy bool) EmailProvider {
func GetEmailProvider(typ string, clientId string, clientSecret string, host string, port int, sslMode string, endpoint string, method string, httpHeaders map[string]string, bodyMapping map[string]string, contentType string, enableProxy bool) EmailProvider {
if typ == "Azure ACS" {
return NewAzureACSEmailProvider(clientSecret, host)
} else if typ == "Custom HTTP Email" {
@@ -26,6 +26,6 @@ func GetEmailProvider(typ string, clientId string, clientSecret string, host str
} else if typ == "SendGrid" {
return NewSendgridEmailProvider(clientSecret, host, endpoint)
} else {
return NewSmtpEmailProvider(clientId, clientSecret, host, port, typ, disableSsl, enableProxy)
return NewSmtpEmailProvider(clientId, clientSecret, host, port, typ, sslMode, enableProxy)
}
}

View File

@@ -25,13 +25,20 @@ type SmtpEmailProvider struct {
Dialer *gomail.Dialer
}
func NewSmtpEmailProvider(userName string, password string, host string, port int, typ string, disableSsl bool, enableProxy bool) *SmtpEmailProvider {
func NewSmtpEmailProvider(userName string, password string, host string, port int, typ string, sslMode string, enableProxy bool) *SmtpEmailProvider {
dialer := gomail.NewDialer(host, port, userName, password)
if typ == "SUBMAIL" {
dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
dialer.SSL = !disableSsl
// Handle SSL mode: "Auto" (or empty) means don't override gomail's default behavior
// "Enable" means force SSL on, "Disable" means force SSL off
if sslMode == "Enable" {
dialer.SSL = true
} else if sslMode == "Disable" {
dialer.SSL = false
}
// If sslMode is "Auto" or empty, don't set dialer.SSL - let gomail decide based on port
if enableProxy {
socks5Proxy := conf.GetConfigString("socks5Proxy")

View File

@@ -46,6 +46,7 @@ type AuthForm struct {
State string `json:"state"`
RedirectUri string `json:"redirectUri"`
Method string `json:"method"`
CodeVerifier string `json:"codeVerifier"`
EmailCode string `json:"emailCode"`
PhoneCode string `json:"phoneCode"`

9
go.mod
View File

@@ -14,8 +14,10 @@ require (
github.com/alibabacloud-go/openapi-util v0.1.0
github.com/alibabacloud-go/tea v1.3.2
github.com/alibabacloud-go/tea-utils/v2 v2.0.7
github.com/aliyun/alibaba-cloud-sdk-go v1.63.107
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible
github.com/aliyun/credentials-go v1.3.10
github.com/aws/aws-sdk-go v1.45.5
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.0
github.com/beego/beego/v2 v2.3.8
github.com/beevik/etree v1.1.0
@@ -28,7 +30,6 @@ require (
github.com/casdoor/xorm-adapter/v3 v3.1.0
github.com/casvisor/casvisor-go-sdk v1.4.0
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
github.com/denisenkom/go-mssqldb v0.9.0
github.com/elimity-com/scim v0.0.0-20230426070224-941a5eac92f3
github.com/fogleman/gg v1.3.0
github.com/go-asn1-ber/asn1-ber v1.5.5
@@ -48,6 +49,7 @@ require (
github.com/lib/pq v1.10.9
github.com/lor00x/goldap v0.0.0-20180618054307-a546dffdd1a3
github.com/markbates/goth v1.82.0
github.com/microsoft/go-mssqldb v1.9.0
github.com/mitchellh/mapstructure v1.5.0
github.com/nyaruka/phonenumbers v1.2.2
github.com/polarsource/polar-go v0.12.0
@@ -111,10 +113,8 @@ require (
github.com/alibabacloud-go/tea-oss-utils v1.1.0 // indirect
github.com/alibabacloud-go/tea-utils v1.3.6 // indirect
github.com/alibabacloud-go/tea-xml v1.1.3 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v1.62.545 // indirect
github.com/apistd/uni-go-sdk v0.0.2 // indirect
github.com/atc0005/go-teams-notify/v2 v2.13.0 // indirect
github.com/aws/aws-sdk-go v1.45.5 // indirect
github.com/aws/smithy-go v1.24.0 // indirect
github.com/baidubce/bce-sdk-go v0.9.156 // indirect
github.com/beorn7/perks v1.0.1 // indirect
@@ -161,7 +161,8 @@ require (
github.com/go-webauthn/x v0.1.9 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect
github.com/golang-sql/sqlexp v0.1.0 // indirect
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/golang/mock v1.6.0 // indirect

32
go.sum
View File

@@ -627,6 +627,16 @@ gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGq
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU=
github.com/Azure/azure-pipeline-go v0.2.3 h1:7U9HBg1JFK3jHl5qmo4CTZKFTVgMwdFHMVtCdfBE21U=
github.com/Azure/azure-pipeline-go v0.2.3/go.mod h1:x841ezTBIMG6O3lAcl8ATHnsOPVl2bqk7S3ta6S6u4k=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0 h1:Gt0j3wceWMwPmiazCa8MzMA0MfhmPIz0Qp0FJ6qcM0U=
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.18.0/go.mod h1:Ot/6aikWnKWi4l9QB7qVSwa8iMphQNqkWALMoNT3rzM=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.10.1 h1:B+blDbyVIG3WaikNxPnhPiJ1MThR03b3vKGtER95TP4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.10.1/go.mod h1:JdM5psgjfBf5fo2uWOZhflPWyDBZ/O/CNAH9CtsuZE4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1 h1:FPKJS1T+clwv+OLGt13a8UjqeRuh0O4SJ3lUriThc+4=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.1/go.mod h1:j2chePtV91HrC22tGoRX3sGY42uF13WzmmV80/OdVAA=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1 h1:Wgf5rZba3YZqeTNJPtvqZoBu1sBN/L4sry+u2U3Y75w=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.3.1/go.mod h1:xxCBG/f/4Vbmh2XQJBsOmNdxWUY5j/s27jujKPbQf14=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1 h1:bFWuoEKg+gImo7pvkiQEFAc8ocibADgXeiLAxWhWmkI=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.1/go.mod h1:Vih/3yc6yac2JzU4hzpaDupBJP0Flaia9rXXrU8xyww=
github.com/Azure/azure-storage-blob-go v0.15.0 h1:rXtgp8tN1p29GvpGgfJetavIG0V7OgcSXPpwp3tx6qk=
github.com/Azure/azure-storage-blob-go v0.15.0/go.mod h1:vbjsVbX0dlxnRc4FFMPsS9BsJWPcne7GB7onqlPvz58=
github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs=
@@ -642,6 +652,8 @@ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUM
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 h1:oygO0locgZJe7PpYPXT5A29ZkwJaPqcva7BVeemZOZs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
@@ -766,8 +778,8 @@ github.com/alibabacloud-go/tea-xml v1.1.1/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCE
github.com/alibabacloud-go/tea-xml v1.1.2/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzYtqw7dgt0=
github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8=
github.com/aliyun/alibaba-cloud-sdk-go v1.62.545 h1:0LfzeUr4quwrrrTHn1kfLA0FBdsChCMs8eK2EzOwXVQ=
github.com/aliyun/alibaba-cloud-sdk-go v1.62.545/go.mod h1:Api2AkmMgGaSUAhmk76oaFObkoeCPc/bKAqcyplPODs=
github.com/aliyun/alibaba-cloud-sdk-go v1.63.107 h1:qagvUyrgOnBIlVRQWOyCZGVKUIYbMBdGdJ104vBpRFU=
github.com/aliyun/alibaba-cloud-sdk-go v1.63.107/go.mod h1:SOSDHfe1kX91v3W5QiBsWSLqeLxImobbMX1mxrFHsVQ=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw=
@@ -917,7 +929,6 @@ github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPc
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 h1:NMZiJj8QnKe1LgsbDayM4UoHwbvwDRwnI3hwNaAHRnc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
github.com/denisenkom/go-mssqldb v0.9.0 h1:RSohk2RsiZqLZ0zCjtfn3S4Gp4exhpBWHyQ7D0yGjAk=
github.com/denisenkom/go-mssqldb v0.9.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
github.com/dghubble/oauth1 v0.7.3 h1:EkEM/zMDMp3zOsX2DC/ZQ2vnEX3ELK0/l9kb+vs4ptE=
github.com/dghubble/oauth1 v0.7.3/go.mod h1:oxTe+az9NSMIucDPDCCtzJGsPhciJV33xocHfcR2sVY=
@@ -1090,8 +1101,11 @@ github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA=
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
@@ -1294,7 +1308,6 @@ github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aW
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/jinzhu/configor v1.2.1 h1:OKk9dsR8i6HPOCZR8BcMtcEImAFjIhbJFZNyn5GCZko=
github.com/jinzhu/configor v1.2.1/go.mod h1:nX89/MOmDba7ZX7GCyU/VIaQ2Ar2aizBl2d3JLF/rDc=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
@@ -1308,7 +1321,6 @@ github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUB
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible h1:jdpOPRN1zP63Td1hDQbZW73xKmzDvZHzVdNYxhnTMDA=
github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible/go.mod h1:1c7szIrayyPPB/987hsnvNzLushdWf4o/79s3P08L8A=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@@ -1352,6 +1364,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
@@ -1416,6 +1430,8 @@ github.com/mattn/go-sqlite3 v1.14.14/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4
github.com/mattn/go-sqlite3 v1.14.27 h1:drZCnuvf37yPfs95E5jd9s3XhdVWLal+6BOK6qrv6IU=
github.com/mattn/go-sqlite3 v1.14.27/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/microsoft/go-mssqldb v1.9.0 h1:5Vq+u2f4LDujJNeZn62Z4kBDEC9MjLv0ukRzOuEuvdA=
github.com/microsoft/go-mssqldb v1.9.0/go.mod h1:GBbW9ASTiDC+mpgWDGKdm3FnFLTUsLYN3iFL90lQ+PA=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
@@ -1498,6 +1514,8 @@ github.com/pingcap/tidb/parser v0.0.0-20221126021158-6b02a5d8ba7d h1:1DyyRrgYeNj
github.com/pingcap/tidb/parser v0.0.0-20221126021158-6b02a5d8ba7d/go.mod h1:ElJiub4lRy6UZDb+0JHDkGEdr6aOli+ykhyej7VCLoI=
github.com/pjbgf/sha1cd v0.3.2 h1:a9wb0bp1oC2TGwStyn0Umc/IGKQnEgF0vVaZ8QF8eo4=
github.com/pjbgf/sha1cd v0.3.2/go.mod h1:zQWigSxVmsHEZow5qaLtPYxpcKMMQpa09ixqBxuCS6A=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1-0.20161029093637-248dadf4e906/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@@ -2615,7 +2633,6 @@ gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o=
gopkg.in/ini.v1 v1.56.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.66.6/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
@@ -2637,6 +2654,7 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

140
i18n/deduplicate_test.go Normal file
View File

@@ -0,0 +1,140 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package i18n
import (
"bytes"
"encoding/json"
"fmt"
"os"
"testing"
)
// DuplicateInfo represents information about a duplicate key
type DuplicateInfo struct {
Key string
OldPrefix string
NewPrefix string
OldPrefixKey string // e.g., "general:Submitter"
NewPrefixKey string // e.g., "permission:Submitter"
}
// findDuplicateKeysInJSON finds duplicate keys across the entire JSON file
// Returns a list of duplicate information showing old and new prefix:key pairs
// The order is determined by the order keys appear in the JSON file (git history)
func findDuplicateKeysInJSON(filePath string) ([]DuplicateInfo, error) {
// Read the JSON file
fileContent, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", filePath, err)
}
// Track the first occurrence of each key (prefix where it was first seen)
keyFirstPrefix := make(map[string]string)
var duplicates []DuplicateInfo
// To preserve order, we need to parse the JSON with order preservation
// We'll use a decoder to read through the top-level object
decoder := json.NewDecoder(bytes.NewReader(fileContent))
// Read the opening brace of the top-level object
token, err := decoder.Token()
if err != nil {
return nil, fmt.Errorf("failed to read token: %w", err)
}
if delim, ok := token.(json.Delim); !ok || delim != '{' {
return nil, fmt.Errorf("expected object start, got %v", token)
}
// Read all namespaces in order
for decoder.More() {
// Read the namespace (prefix) name
token, err := decoder.Token()
if err != nil {
return nil, fmt.Errorf("failed to read namespace: %w", err)
}
prefix, ok := token.(string)
if !ok {
return nil, fmt.Errorf("expected string namespace, got %v", token)
}
// Read the namespace object as raw message
var namespaceData map[string]string
if err := decoder.Decode(&namespaceData); err != nil {
return nil, fmt.Errorf("failed to decode namespace %s: %w", prefix, err)
}
// Now check each key in this namespace
for key := range namespaceData {
// Check if this key was already seen in a different prefix
if firstPrefix, exists := keyFirstPrefix[key]; exists {
// This is a duplicate - the key exists in another prefix
duplicates = append(duplicates, DuplicateInfo{
Key: key,
OldPrefix: firstPrefix,
NewPrefix: prefix,
OldPrefixKey: fmt.Sprintf("%s:%s", firstPrefix, key),
NewPrefixKey: fmt.Sprintf("%s:%s", prefix, key),
})
} else {
// First time seeing this key, record the prefix
keyFirstPrefix[key] = prefix
}
}
}
return duplicates, nil
}
// TestDeduplicateFrontendI18n checks for duplicate i18n keys in the frontend en.json file
func TestDeduplicateFrontendI18n(t *testing.T) {
filePath := "../web/src/locales/en/data.json"
// Find duplicate keys
duplicates, err := findDuplicateKeysInJSON(filePath)
if err != nil {
t.Fatalf("Failed to check for duplicates in frontend i18n file: %v", err)
}
// Print all duplicates and fail the test if any are found
if len(duplicates) > 0 {
t.Errorf("Found duplicate i18n keys in frontend file (%s):", filePath)
for _, dup := range duplicates {
t.Errorf(" i18next.t(\"%s\") duplicates with i18next.t(\"%s\")", dup.NewPrefixKey, dup.OldPrefixKey)
}
t.Fail()
}
}
// TestDeduplicateBackendI18n checks for duplicate i18n keys in the backend en.json file
func TestDeduplicateBackendI18n(t *testing.T) {
filePath := "../i18n/locales/en/data.json"
// Find duplicate keys
duplicates, err := findDuplicateKeysInJSON(filePath)
if err != nil {
t.Fatalf("Failed to check for duplicates in backend i18n file: %v", err)
}
// Print all duplicates and fail the test if any are found
if len(duplicates) > 0 {
t.Errorf("Found duplicate i18n keys in backend file (%s):", filePath)
for _, dup := range duplicates {
t.Errorf(" i18n.Translate(\"%s\") duplicates with i18n.Translate(\"%s\")", dup.NewPrefixKey, dup.OldPrefixKey)
}
t.Fail()
}
}

View File

@@ -19,6 +19,7 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/casdoor/casdoor/util"
@@ -47,7 +48,11 @@ func getAllI18nStringsFrontend(fileContent string) []string {
}
for _, match := range matches {
res = append(res, match[1])
target, err := strconv.Unquote("\"" + match[1] + "\"")
if err != nil {
target = match[1]
}
res = append(res, target)
}
return res
}
@@ -61,7 +66,12 @@ func getAllI18nStringsBackend(fileContent string, isObjectPackage bool) []string
}
for _, match := range matches {
match := strings.SplitN(match[1], ",", 2)
res = append(res, match[1][2:])
target, err := strconv.Unquote("\"" + match[1][2:] + "\"")
if err != nil {
target = match[1][2:]
}
res = append(res, target)
}
} else {
matches := reI18nBackendController.FindAllStringSubmatch(fileContent, -1)
@@ -69,7 +79,11 @@ func getAllI18nStringsBackend(fileContent string, isObjectPackage bool) []string
return res
}
for _, match := range matches {
res = append(res, match[1][1:])
target, err := strconv.Unquote("\"" + match[1][1:] + "\"")
if err != nil {
target = match[1][1:]
}
res = append(res, target)
}
}

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Konnte den Benutzer nicht hinzufügen",
"Get init score failed, error: %w": "Init-Score konnte nicht abgerufen werden, Fehler: %w",
"Please sign out first": "Bitte melden Sie sich zuerst ab",
"The application does not allow to sign up new account": "Die Anwendung erlaubt es nicht, sich für ein neues Konto anzumelden"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "Die Anmeldemethode: Anmeldung per E-Mail ist für die Anwendung nicht aktiviert",
"The login method: login with face is not enabled for the application": "Die Anmeldemethode: Anmeldung per Gesicht ist für die Anwendung nicht aktiviert",
"The login method: login with password is not enabled for the application": "Die Anmeldeart \"Anmeldung mit Passwort\" ist für die Anwendung nicht aktiviert",
"The order: %s does not exist": "Die Bestellung: %s existiert nicht",
"The organization: %s does not exist": "Die Organisation: %s existiert nicht",
"The organization: %s has disabled users to signin": "Die Organisation: %s hat die Anmeldung von Benutzern deaktiviert",
"The plan: %s does not exist": "Der Plan: %s existiert nicht",
@@ -48,7 +48,7 @@
"CIDR for IP: %s should not be empty": "CIDR für IP: %s darf nicht leer sein",
"Default code does not match the code's matching rules": "Standardcode entspricht nicht den Übereinstimmungsregeln des Codes",
"DisplayName cannot be blank": "Anzeigename kann nicht leer sein",
"DisplayName is not valid real name": "DisplayName ist kein gültiger Vorname",
"DisplayName is not valid real name": "Der Anzeigename ist kein gültiger echter Name",
"Email already exists": "E-Mail existiert bereits",
"Email cannot be empty": "E-Mail darf nicht leer sein",
"Email is invalid": "E-Mail ist ungültig",
@@ -57,11 +57,11 @@
"Face data mismatch": "Gesichtsdaten stimmen nicht überein",
"Failed to parse client IP: %s": "Fehler beim Parsen der Client-IP: %s",
"FirstName cannot be blank": "Vorname darf nicht leer sein",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Gastbenutzer müssen ihr Konto aktualisieren, indem sie einen Benutzernamen und ein Passwort festlegen, bevor sie sich direkt anmelden können",
"Invitation code cannot be blank": "Einladungscode darf nicht leer sein",
"Invitation code exhausted": "Einladungscode aufgebraucht",
"Invitation code is invalid": "Einladungscode ist ungültig",
"Invitation code suspended": "Einladungscode ausgesetzt",
"LDAP user name or password incorrect": "Ldap Benutzername oder Passwort falsch",
"LastName cannot be blank": "Nachname darf nicht leer sein",
"Multiple accounts with same uid, please check your ldap server": "Mehrere Konten mit derselben uid, bitte überprüfen Sie Ihren LDAP-Server",
"Organization does not exist": "Organisation existiert nicht",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "Dem Benutzer ist der Zugang verboten, bitte kontaktieren Sie den Administrator",
"The user: %s doesn't exist in LDAP server": "Der Benutzer: %s existiert nicht im LDAP-Server",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Der Benutzername darf nur alphanumerische Zeichen, Unterstriche oder Bindestriche enthalten, keine aufeinanderfolgenden Bindestriche oder Unterstriche haben und darf nicht mit einem Bindestrich oder Unterstrich beginnen oder enden.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "Der Wert \\\"%s\\\" für das Kontenfeld \\\"%s\\\" stimmt nicht mit dem Kontenelement-Regex überein",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "Der Wert \\\"%s\\\" für das Registrierungsfeld \\\"%s\\\" stimmt nicht mit dem Registrierungselement-Regex der Anwendung \\\"%s\\\" überein",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "Der Wert \"%s\" für das Kontenfeld \"%s\" stimmt nicht mit dem Kontenelement-Regex überein",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "Der Wert \"%s\" für das Registrierungsfeld \"%s\" stimmt nicht mit dem Registrierungselement-Regex der Anwendung \"%s\" überein",
"Username already exists": "Benutzername existiert bereits",
"Username cannot be an email address": "Benutzername kann keine E-Mail-Adresse sein",
"Username cannot contain white spaces": "Benutzername darf keine Leerzeichen enthalten",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Benutzername unterstützt E-Mail-Format. Der Benutzername darf nur alphanumerische Zeichen, Unterstriche oder Bindestriche enthalten, keine aufeinanderfolgenden Bindestriche oder Unterstriche haben und darf nicht mit einem Bindestrich oder Unterstrich beginnen oder enden. Achten Sie auch auf das E-Mail-Format.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Sie haben zu oft das falsche Passwort oder den falschen Code eingegeben. Bitte warten Sie %d Minuten und versuchen Sie es erneut",
"Your IP address: %s has been banned according to the configuration of: ": "Ihre IP-Adresse: %s wurde laut Konfiguration gesperrt von: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Ihr Passwort ist abgelaufen. Bitte setzen Sie Ihr Passwort zurück, indem Sie auf \\\"Passwort vergessen\\\" klicken",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Ihr Passwort ist abgelaufen. Bitte setzen Sie Ihr Passwort zurück, indem Sie auf \"Passwort vergessen\" klicken",
"Your region is not allow to signup by phone": "Ihre Region ist nicht berechtigt, sich telefonisch anzumelden",
"password or code is incorrect": "Passwort oder Code ist falsch",
"password or code is incorrect, you have %s remaining chances": "Das Passwort oder der Code ist falsch. Du hast noch %s Versuche übrig",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Gruppen importieren fehlgeschlagen",
"Failed to import users": "Fehler beim Importieren von Benutzern",
"Insufficient balance: new balance %v would be below credit limit %v": "Unzureichendes Guthaben: neues Guthaben %v wäre unter dem Kreditlimit %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Unzureichendes Guthaben: neues Organisationsguthaben %v wäre unter dem Kreditlimit %v",
"Missing parameter": "Fehlender Parameter",
"Only admin user can specify user": "Nur Administrator kann Benutzer angeben",
"Please login first": "Bitte zuerst einloggen",
"The LDAP: %s does not exist": "Das LDAP: %s existiert nicht",
"The organization: %s should have one application at least": "Die Organisation: %s sollte mindestens eine Anwendung haben",
"The syncer: %s does not exist": "Der Synchronizer: %s existiert nicht",
"The user: %s doesn't exist": "Der Benutzer %s existiert nicht",
"The user: %s is not found": "Der Benutzer: %s wurde nicht gefunden",
"User is required for User category transaction": "Benutzer ist für Benutzer-Kategorie-Transaktionen erforderlich",
"Wrong userId": "Falsche Benutzer-ID",
"don't support captchaProvider: ": "Unterstütze captchaProvider nicht:",
"this operation is not allowed in demo mode": "Dieser Vorgang ist im Demo-Modus nicht erlaubt",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "Das Hinzufügen eines neuen Benutzers zur 'eingebauten' Organisation ist derzeit deaktiviert. Bitte beachten Sie: Alle Benutzer in der 'eingebauten' Organisation sind globale Administratoren in Casdoor. Siehe die Docs: https://casdoor.org/docs/basic/core-concepts#how -does-casdoor-manage-sich selbst. Wenn Sie immer noch einen Benutzer für die 'eingebaute' Organisation erstellen möchten, gehen Sie auf die Einstellungsseite der Organisation und aktivieren Sie die Option 'Habt Berechtigungszustimmung'."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "Die Berechtigung: \\\"%s\\\" existiert nicht"
"The permission: \"%s\" doesn't exist": "Die Berechtigung: \"%s\" existiert nicht"
},
"product": {
"Product list cannot be empty": "Produktliste darf nicht leer sein"
},
"provider": {
"Failed to initialize ID Verification provider": "ID-Verifizierungsanbieter konnte nicht initialisiert werden",
"Invalid application id": "Ungültige Anwendungs-ID",
"No ID Verification provider configured": "Kein ID-Verifizierungsanbieter konfiguriert",
"Provider is not an ID Verification provider": "Anbieter ist kein ID-Verifizierungsanbieter",
"the provider: %s does not exist": "Der Anbieter %s existiert nicht"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Ungültige E-Mail-Empfänger: %s",
"Invalid phone receivers: %s": "Ungültige Telefonempfänger: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "Sitzungs-ID %s ist die aktuelle Sitzung und kann nicht gelöscht werden"
},
"storage": {
"The objectKey: %s is not allowed": "Der Objektschlüssel %s ist nicht erlaubt",
"The provider type: %s is not supported": "Der Anbieter-Typ %s wird nicht unterstützt"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Fehler"
},
"ticket": {
"Ticket not found": "Ticket nicht gefunden"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s wird von dieser Anwendung nicht unterstützt",
"Invalid application or wrong clientSecret": "Ungültige Anwendung oder falsches clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Anzeigename darf nicht leer sein",
"ID card information and real name are required": "Personalausweisinformationen und vollständiger Name sind erforderlich",
"Identity verification failed": "Identitätsprüfung fehlgeschlagen",
"MFA email is enabled but email is empty": "MFA-E-Mail ist aktiviert, aber E-Mail ist leer",
"MFA phone is enabled but phone number is empty": "MFA-Telefon ist aktiviert, aber Telefonnummer ist leer",
"New password cannot contain blank space.": "Das neue Passwort darf keine Leerzeichen enthalten.",
"No application found for user": "Keine Anwendung für Benutzer gefunden",
"The new password must be different from your current password": "Das neue Passwort muss sich von Ihrem aktuellen Passwort unterscheiden",
"User is already verified": "Benutzer ist bereits verifiziert",
"the user's owner and name should not be empty": "Eigentümer und Name des Benutzers dürfen nicht leer sein"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Ungültiger Captcha-Anbieter.",
"Phone number is invalid in your region %s": "Die Telefonnummer ist in Ihrer Region %s ungültig",
"The forgot password feature is disabled": "Die Funktion \"Passwort vergessen\" ist deaktiviert",
"The verification code has already been used!": "Der Verifizierungscode wurde bereits verwendet!",
"The verification code has not been sent yet!": "Der Verifizierungscode wurde noch nicht gesendet!",
"Turing test failed.": "Turing-Test fehlgeschlagen.",
@@ -196,8 +219,8 @@
"Unknown type": "Unbekannter Typ",
"Wrong verification code!": "Falscher Bestätigungscode!",
"You should verify your code in %d min!": "Du solltest deinen Code in %d Minuten verifizieren!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "Bitte fügen Sie einen SMS-Anbieter zur \\\"Providers\\\"-Liste für die Anwendung hinzu: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "Bitte fügen Sie einen E-Mail-Anbieter zur \\\"Providers\\\"-Liste für die Anwendung hinzu: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "Bitte fügen Sie einen SMS-Anbieter zur \"Providers\"-Liste für die Anwendung hinzu: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "Bitte fügen Sie einen E-Mail-Anbieter zur \"Providers\"-Liste für die Anwendung hinzu: %s",
"the user does not exist, please sign up first": "Der Benutzer existiert nicht, bitte zuerst anmelden"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Failed to add user",
"Get init score failed, error: %w": "Get init score failed, error: %w",
"Please sign out first": "Please sign out first",
"The application does not allow to sign up new account": "The application does not allow to sign up new account"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "The login method: login with email is not enabled for the application",
"The login method: login with face is not enabled for the application": "The login method: login with face is not enabled for the application",
"The login method: login with password is not enabled for the application": "The login method: login with password is not enabled for the application",
"The order: %s does not exist": "The order: %s does not exist",
"The organization: %s does not exist": "The organization: %s does not exist",
"The organization: %s has disabled users to signin": "The organization: %s has disabled users to signin",
"The plan: %s does not exist": "The plan: %s does not exist",
@@ -57,11 +57,11 @@
"Face data mismatch": "Face data mismatch",
"Failed to parse client IP: %s": "Failed to parse client IP: %s",
"FirstName cannot be blank": "FirstName cannot be blank",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Guest users must upgrade their account by setting a username and password before they can sign in directly",
"Invitation code cannot be blank": "Invitation code cannot be blank",
"Invitation code exhausted": "Invitation code exhausted",
"Invitation code is invalid": "Invitation code is invalid",
"Invitation code suspended": "Invitation code suspended",
"LDAP user name or password incorrect": "LDAP user name or password incorrect",
"LastName cannot be blank": "LastName cannot be blank",
"Multiple accounts with same uid, please check your ldap server": "Multiple accounts with same uid, please check your ldap server",
"Organization does not exist": "Organization does not exist",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "The user is forbidden to sign in, please contact the administrator",
"The user: %s doesn't exist in LDAP server": "The user: %s doesn't exist in LDAP server",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "The value \"%s\" for account field \"%s\" doesn't match the account item regex",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"",
"Username already exists": "Username already exists",
"Username cannot be an email address": "Username cannot be an email address",
"Username cannot contain white spaces": "Username cannot contain white spaces",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "You have entered the wrong password or code too many times, please wait for %d minutes and try again",
"Your IP address: %s has been banned according to the configuration of: ": "Your IP address: %s has been banned according to the configuration of: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Your password has expired. Please reset your password by clicking \"Forgot password\"",
"Your region is not allow to signup by phone": "Your region is not allow to signup by phone",
"password or code is incorrect": "password or code is incorrect",
"password or code is incorrect, you have %s remaining chances": "password or code is incorrect, you have %s remaining chances",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Failed to import groups",
"Failed to import users": "Failed to import users",
"Insufficient balance: new balance %v would be below credit limit %v": "Insufficient balance: new balance %v would be below credit limit %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Insufficient balance: new organization balance %v would be below credit limit %v",
"Missing parameter": "Missing parameter",
"Only admin user can specify user": "Only admin user can specify user",
"Please login first": "Please login first",
"The LDAP: %s does not exist": "The LDAP: %s does not exist",
"The organization: %s should have one application at least": "The organization: %s should have one application at least",
"The syncer: %s does not exist": "The syncer: %s does not exist",
"The user: %s doesn't exist": "The user: %s doesn't exist",
"The user: %s is not found": "The user: %s is not found",
"User is required for User category transaction": "User is required for User category transaction",
"Wrong userId": "Wrong userId",
"don't support captchaProvider: ": "don't support captchaProvider: ",
"this operation is not allowed in demo mode": "this operation is not allowed in demo mode",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "The permission: \\\"%s\\\" doesn't exist"
"The permission: \"%s\" doesn't exist": "The permission: \"%s\" doesn't exist"
},
"product": {
"Product list cannot be empty": "Product list cannot be empty"
},
"provider": {
"Failed to initialize ID Verification provider": "Failed to initialize ID Verification provider",
"Invalid application id": "Invalid application id",
"No ID Verification provider configured": "No ID Verification provider configured",
"Provider is not an ID Verification provider": "Provider is not an ID Verification provider",
"the provider: %s does not exist": "the provider: %s does not exist"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Invalid Email receivers: %s",
"Invalid phone receivers: %s": "Invalid phone receivers: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "session id %s is the current session and cannot be deleted"
},
"storage": {
"The objectKey: %s is not allowed": "The objectKey: %s is not allowed",
"The provider type: %s is not supported": "The provider type: %s is not supported"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Error"
},
"ticket": {
"Ticket not found": "Ticket not found"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s is not supported in this application",
"Invalid application or wrong clientSecret": "Invalid application or wrong clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Display name cannot be empty",
"ID card information and real name are required": "ID card information and real name are required",
"Identity verification failed": "Identity verification failed",
"MFA email is enabled but email is empty": "MFA email is enabled but email is empty",
"MFA phone is enabled but phone number is empty": "MFA phone is enabled but phone number is empty",
"New password cannot contain blank space.": "New password cannot contain blank space.",
"No application found for user": "No application found for user",
"The new password must be different from your current password": "The new password must be different from your current password",
"User is already verified": "User is already verified",
"the user's owner and name should not be empty": "the user's owner and name should not be empty"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Invalid captcha provider.",
"Phone number is invalid in your region %s": "Phone number is invalid in your region %s",
"The forgot password feature is disabled": "The forgot password feature is disabled",
"The verification code has already been used!": "The verification code has already been used!",
"The verification code has not been sent yet!": "The verification code has not been sent yet!",
"Turing test failed.": "Turing test failed.",
@@ -196,8 +219,8 @@
"Unknown type": "Unknown type",
"Wrong verification code!": "Wrong verification code!",
"You should verify your code in %d min!": "You should verify your code in %d min!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "please add a SMS provider to the \\\"Providers\\\" list for the application: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "please add an Email provider to the \\\"Providers\\\" list for the application: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "please add a SMS provider to the \"Providers\" list for the application: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "please add an Email provider to the \"Providers\" list for the application: %s",
"the user does not exist, please sign up first": "the user does not exist, please sign up first"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "No se pudo agregar el usuario",
"Get init score failed, error: %w": "Error al obtener el puntaje de inicio, error: %w",
"Please sign out first": "Por favor, cierra sesión primero",
"The application does not allow to sign up new account": "La aplicación no permite registrarse con una cuenta nueva"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "El método de inicio de sesión: inicio de sesión con correo electrónico no está habilitado para la aplicación",
"The login method: login with face is not enabled for the application": "El método de inicio de sesión: inicio de sesión con reconocimiento facial no está habilitado para la aplicación",
"The login method: login with password is not enabled for the application": "El método de inicio de sesión: inicio de sesión con contraseña no está habilitado para la aplicación",
"The order: %s does not exist": "El pedido: %s no existe",
"The organization: %s does not exist": "La organización: %s no existe",
"The organization: %s has disabled users to signin": "La organización: %s ha desactivado el inicio de sesión de usuarios",
"The plan: %s does not exist": "El plan: %s no existe",
@@ -35,7 +35,7 @@
"User's tag: %s is not listed in the application's tags": "La etiqueta del usuario: %s no está incluida en las etiquetas de la aplicación",
"UserCode Expired": "Código de usuario expirado",
"UserCode Invalid": "Código de usuario inválido",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "El usuario de pago %s no tiene una suscripción activa o pendiente y la aplicación: %s no tiene precio predeterminado",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "El usuario de pago %s no tiene una suscripción activa o pendiente y la aplicación %s no tiene precios predeterminados",
"the application for user %s is not found": "no se encontró la aplicación para el usuario %s",
"the organization: %s is not found": "no se encontró la organización: %s"
},
@@ -44,9 +44,9 @@
},
"check": {
"%s does not meet the CIDR format requirements: %s": "%s no cumple con los requisitos del formato CIDR: %s",
"Affiliation cannot be blank": "Afiliación no puede estar en blanco",
"Affiliation cannot be blank": "La afiliación no puede estar vacía",
"CIDR for IP: %s should not be empty": "El CIDR para la IP: %s no debe estar vacío",
"Default code does not match the code's matching rules": "El código predeterminado no coincide con las reglas de coincidencia de códigos",
"Default code does not match the code's matching rules": "El código predeterminado no cumple con las reglas de validación del código",
"DisplayName cannot be blank": "El nombre de visualización no puede estar en blanco",
"DisplayName is not valid real name": "El nombre de pantalla no es un nombre real válido",
"Email already exists": "El correo electrónico ya existe",
@@ -57,11 +57,11 @@
"Face data mismatch": "Los datos faciales no coinciden",
"Failed to parse client IP: %s": "Error al analizar la IP del cliente: %s",
"FirstName cannot be blank": "El nombre no puede estar en blanco",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Los usuarios invitados deben actualizar su cuenta configurando un nombre de usuario y una contraseña antes de poder iniciar sesión directamente",
"Invitation code cannot be blank": "El código de invitación no puede estar vacío",
"Invitation code exhausted": "Código de invitación agotado",
"Invitation code is invalid": "Código de invitación inválido",
"Invitation code suspended": "Código de invitación suspendido",
"LDAP user name or password incorrect": "Nombre de usuario o contraseña de Ldap incorrectos",
"LastName cannot be blank": "El apellido no puede estar en blanco",
"Multiple accounts with same uid, please check your ldap server": "Cuentas múltiples con el mismo uid, por favor revise su servidor ldap",
"Organization does not exist": "La organización no existe",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "El usuario no está autorizado a iniciar sesión, por favor contacte al administrador",
"The user: %s doesn't exist in LDAP server": "El usuario: %s no existe en el servidor LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "El nombre de usuario solo puede contener caracteres alfanuméricos, guiones bajos o guiones, no puede tener guiones o subrayados consecutivos, y no puede comenzar ni terminar con un guión o subrayado.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "El valor \\\"%s\\\" para el campo de cuenta \\\"%s\\\" no coincide con la expresión regular del elemento de cuenta",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "El valor \\\"%s\\\" para el campo de registro \\\"%s\\\" no coincide con la expresión regular del elemento de registro de la aplicación \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "El valor \"%s\" para el campo de cuenta \"%s\" no coincide con la expresión regular del elemento de cuenta",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "El valor \"%s\" para el campo de registro \"%s\" no coincide con la expresión regular del elemento de registro de la aplicación \"%s\"",
"Username already exists": "El nombre de usuario ya existe",
"Username cannot be an email address": "Nombre de usuario no puede ser una dirección de correo electrónico",
"Username cannot contain white spaces": "Nombre de usuario no puede contener espacios en blanco",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "El nombre de usuario admite formato de correo electrónico. Además, el nombre de usuario solo puede contener caracteres alfanuméricos, guiones bajos o guiones, no puede tener guiones bajos o guiones consecutivos y no puede comenzar ni terminar con un guión o guión bajo. También preste atención al formato del correo electrónico.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Has ingresado la contraseña o código incorrecto demasiadas veces, por favor espera %d minutos e intenta de nuevo",
"Your IP address: %s has been banned according to the configuration of: ": "Su dirección IP: %s ha sido bloqueada según la configuración de: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Su contraseña ha expirado. Restablezca su contraseña haciendo clic en \\\"Olvidé mi contraseña\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Su contraseña ha expirado. Restablezca su contraseña haciendo clic en \"Olvidé mi contraseña\"",
"Your region is not allow to signup by phone": "Tu región no está permitida para registrarse por teléfono",
"password or code is incorrect": "contraseña o código incorrecto",
"password or code is incorrect, you have %s remaining chances": "Contraseña o código incorrecto, tienes %s intentos restantes",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Error al importar grupos",
"Failed to import users": "Error al importar usuarios",
"Insufficient balance: new balance %v would be below credit limit %v": "Saldo insuficiente: el nuevo saldo %v estaría por debajo del límite de crédito %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Saldo insuficiente: el nuevo saldo de la organización %v estaría por debajo del límite de crédito %v",
"Missing parameter": "Parámetro faltante",
"Only admin user can specify user": "Solo el usuario administrador puede especificar usuario",
"Please login first": "Por favor, inicia sesión primero",
"The LDAP: %s does not exist": "El LDAP: %s no existe",
"The organization: %s should have one application at least": "La organización: %s debe tener al menos una aplicación",
"The syncer: %s does not exist": "El sincronizador: %s no existe",
"The user: %s doesn't exist": "El usuario: %s no existe",
"The user: %s is not found": "El usuario: %s no encontrado",
"User is required for User category transaction": "El usuario es obligatorio para la transacción de la categoría Usuario",
"Wrong userId": "ID de usuario incorrecto",
"don't support captchaProvider: ": "No apoyo a captchaProvider",
"this operation is not allowed in demo mode": "esta operación no está permitida en modo de demostración",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "La adición de un nuevo usuario a la organización 'integrada' está actualmente deshabilitada. Tenga en cuenta: todos los usuarios de la organización 'integrada' son administradores globales en Casdoor. Consulte los docs: https://casdoor.org/docs/basic/core-concepts#how -does-casdoor-manage-itself. Si todavía desea crear un usuario para la organización 'integrada', vaya a la página de configuración de la organización y habilite la opción 'Tiene consentimiento de privilegios'."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "El permiso: \\\"%s\\\" no existe"
"The permission: \"%s\" doesn't exist": "El permiso: \"%s\" no existe"
},
"product": {
"Product list cannot be empty": "La lista de productos no puede estar vacía"
},
"provider": {
"Failed to initialize ID Verification provider": "Error al inicializar el proveedor de verificación de ID",
"Invalid application id": "Identificación de aplicación no válida",
"No ID Verification provider configured": "No hay proveedor de verificación de ID configurado",
"Provider is not an ID Verification provider": "El proveedor no es un proveedor de verificación de ID",
"the provider: %s does not exist": "El proveedor: %s no existe"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Receptores de correo electrónico no válidos: %s",
"Invalid phone receivers: %s": "Receptores de teléfono no válidos: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "session id %s is the current session and cannot be deleted"
},
"storage": {
"The objectKey: %s is not allowed": "El objectKey: %s no está permitido",
"The provider type: %s is not supported": "El tipo de proveedor: %s no es compatible"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Error"
},
"ticket": {
"Ticket not found": "Ticket no encontrado"
},
"token": {
"Grant_type: %s is not supported in this application": "El tipo de subvención: %s no es compatible con esta aplicación",
"Invalid application or wrong clientSecret": "Solicitud inválida o clientSecret incorrecto",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "El nombre de pantalla no puede estar vacío",
"ID card information and real name are required": "Se requiere información de la tarjeta de identificación y el nombre real",
"Identity verification failed": "Falló la verificación de identidad",
"MFA email is enabled but email is empty": "El correo electrónico MFA está habilitado pero el correo está vacío",
"MFA phone is enabled but phone number is empty": "El teléfono MFA está habilitado pero el número de teléfono está vacío",
"New password cannot contain blank space.": "La nueva contraseña no puede contener espacios en blanco.",
"No application found for user": "No se encontró aplicación para el usuario",
"The new password must be different from your current password": "La nueva contraseña debe ser diferente de su contraseña actual",
"User is already verified": "El usuario ya está verificado",
"the user's owner and name should not be empty": "el propietario y el nombre del usuario no deben estar vacíos"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Proveedor de captcha no válido.",
"Phone number is invalid in your region %s": "El número de teléfono es inválido en tu región %s",
"The forgot password feature is disabled": "La función de contraseña olvidada está deshabilitada",
"The verification code has already been used!": "¡El código de verificación ya ha sido utilizado!",
"The verification code has not been sent yet!": "¡El código de verificación aún no ha sido enviado!",
"Turing test failed.": "El test de Turing falló.",
@@ -196,8 +219,8 @@
"Unknown type": "Tipo desconocido",
"Wrong verification code!": "¡Código de verificación incorrecto!",
"You should verify your code in %d min!": "¡Deberías verificar tu código en %d minutos!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "agregue un proveedor de SMS a la lista \\\"Proveedores\\\" para la aplicación: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "agregue un proveedor de correo electrónico a la lista \\\"Proveedores\\\" para la aplicación: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "agregue un proveedor de SMS a la lista \"Proveedores\" para la aplicación: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "agregue un proveedor de correo electrónico a la lista \"Proveedores\" para la aplicación: %s",
"the user does not exist, please sign up first": "El usuario no existe, por favor regístrese primero"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Échec d'ajout d'utilisateur",
"Get init score failed, error: %w": "Obtention du score initiale échouée, erreur : %w",
"Please sign out first": "Veuillez vous déconnecter en premier",
"The application does not allow to sign up new account": "L'application ne permet pas de créer un nouveau compte"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "La méthode de connexion : connexion par e-mail n'est pas activée pour l'application",
"The login method: login with face is not enabled for the application": "La méthode de connexion : connexion par visage n'est pas activée pour l'application",
"The login method: login with password is not enabled for the application": "La méthode de connexion : connexion avec mot de passe n'est pas activée pour l'application",
"The order: %s does not exist": "La commande : %s n'existe pas",
"The organization: %s does not exist": "L'organisation : %s n'existe pas",
"The organization: %s has disabled users to signin": "L'organisation: %s a désactivé la connexion des utilisateurs",
"The plan: %s does not exist": "Le plan : %s n'existe pas",
@@ -35,7 +35,7 @@
"User's tag: %s is not listed in the application's tags": "Le tag de l'utilisateur : %s n'est pas répertorié dans les tags de l'application",
"UserCode Expired": "Code utilisateur expiré",
"UserCode Invalid": "Code utilisateur invalide",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "L'utilisateur payant %s n'a pas d'abonnement actif ou en attente et l'application : %s n'a pas de tarification par défaut",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "L'utilisateur payant %s n'a pas d'abonnement actif ou en attente et l'application %s n'a pas de tarification par défaut",
"the application for user %s is not found": "L'application pour l'utilisateur %s est introuvable",
"the organization: %s is not found": "L'organisation : %s est introuvable"
},
@@ -44,9 +44,9 @@
},
"check": {
"%s does not meet the CIDR format requirements: %s": "%s ne respecte pas les exigences du format CIDR : %s",
"Affiliation cannot be blank": "Affiliation ne peut pas être vide",
"Affiliation cannot be blank": "L'affiliation ne peut pas être vide",
"CIDR for IP: %s should not be empty": "Le CIDR pour l'IP : %s ne doit pas être vide",
"Default code does not match the code's matching rules": "Le code par défaut ne correspond pas aux règles de correspondance du code",
"Default code does not match the code's matching rules": "Le code par défaut ne respecte pas les règles de validation du code",
"DisplayName cannot be blank": "Le nom d'affichage ne peut pas être vide",
"DisplayName is not valid real name": "DisplayName n'est pas un nom réel valide",
"Email already exists": "E-mail déjà existant",
@@ -57,11 +57,11 @@
"Face data mismatch": "Données faciales incorrectes",
"Failed to parse client IP: %s": "Échec de l'analyse de l'IP client : %s",
"FirstName cannot be blank": "Le prénom ne peut pas être laissé vide",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Les utilisateurs invités doivent mettre à niveau leur compte en définissant un nom d'utilisateur et un mot de passe avant de pouvoir se connecter directement",
"Invitation code cannot be blank": "Le code d'invitation ne peut pas être vide",
"Invitation code exhausted": "Code d'invitation épuisé",
"Invitation code is invalid": "Code d'invitation invalide",
"Invitation code suspended": "Code d'invitation suspendu",
"LDAP user name or password incorrect": "Nom d'utilisateur ou mot de passe LDAP incorrect",
"LastName cannot be blank": "Le nom de famille ne peut pas être vide",
"Multiple accounts with same uid, please check your ldap server": "Plusieurs comptes avec le même identifiant d'utilisateur, veuillez vérifier votre serveur LDAP",
"Organization does not exist": "L'organisation n'existe pas",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "L'utilisateur est interdit de se connecter, veuillez contacter l'administrateur",
"The user: %s doesn't exist in LDAP server": "L'utilisateur : %s n'existe pas sur le serveur LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Le nom d'utilisateur ne peut contenir que des caractères alphanumériques, des traits soulignés ou des tirets, ne peut pas avoir de tirets ou de traits soulignés consécutifs et ne peut pas commencer ou se terminer par un tiret ou un trait souligné.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "La valeur \\\"%s\\\" pour le champ de compte \\\"%s\\\" ne correspond pas à l'expression régulière de l'élément de compte",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "La valeur \\\"%s\\\" pour le champ d'inscription \\\"%s\\\" ne correspond pas à l'expression régulière de l'élément d'inscription de l'application \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "La valeur \"%s\" pour le champ de compte \"%s\" ne correspond pas à l'expression régulière de l'élément de compte",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "La valeur \"%s\" pour le champ d'inscription \"%s\" ne correspond pas à l'expression régulière de l'élément d'inscription de l'application \"%s\"",
"Username already exists": "Nom d'utilisateur existe déjà",
"Username cannot be an email address": "Nom d'utilisateur ne peut pas être une adresse e-mail",
"Username cannot contain white spaces": "Nom d'utilisateur ne peut pas contenir d'espaces blancs",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Le nom d'utilisateur prend en charge le format e-mail. De plus, il ne peut contenir que des caractères alphanumériques, des tirets bas ou des traits d'union, ne peut pas avoir de traits d'union ou de tirets bas consécutifs, et ne peut pas commencer ou se terminer par un trait d'union ou un tiret bas. Faites également attention au format de l'e-mail.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Vous avez entré le mauvais mot de passe ou code plusieurs fois, veuillez attendre %d minutes et réessayer",
"Your IP address: %s has been banned according to the configuration of: ": "Votre adresse IP : %s a été bannie selon la configuration de : ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Votre mot de passe a expiré. Veuillez le réinitialiser en cliquant sur \\\"Mot de passe oublié\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Votre mot de passe a expiré. Veuillez le réinitialiser en cliquant sur \"Mot de passe oublié\"",
"Your region is not allow to signup by phone": "Votre région n'est pas autorisée à s'inscrire par téléphone",
"password or code is incorrect": "mot de passe ou code incorrect",
"password or code is incorrect, you have %s remaining chances": "Le mot de passe ou le code est incorrect, il vous reste %s chances",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Échec de l'importation des groupes",
"Failed to import users": "Échec de l'importation des utilisateurs",
"Insufficient balance: new balance %v would be below credit limit %v": "Solde insuffisant : le nouveau solde %v serait inférieur à la limite de crédit %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Solde insuffisant : le nouveau solde de l'organisation %v serait inférieur à la limite de crédit %v",
"Missing parameter": "Paramètre manquant",
"Only admin user can specify user": "Seul un administrateur peut désigner un utilisateur",
"Please login first": "Veuillez d'abord vous connecter",
"The LDAP: %s does not exist": "Le LDAP : %s n'existe pas",
"The organization: %s should have one application at least": "L'organisation : %s doit avoir au moins une application",
"The syncer: %s does not exist": "Le synchroniseur : %s n'existe pas",
"The user: %s doesn't exist": "L'utilisateur : %s n'existe pas",
"The user: %s is not found": "L'utilisateur : %s est introuvable",
"User is required for User category transaction": "L'utilisateur est requis pour la transaction de catégorie Utilisateur",
"Wrong userId": "ID utilisateur incorrect",
"don't support captchaProvider: ": "ne prend pas en charge captchaProvider: ",
"this operation is not allowed in demo mode": "cette opération n'est pas autorisée en mode démo",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "L'ajout d'un nouvel utilisateur à l'organisation « built-in » (intégrée) est actuellement désactivé. Veuillez noter : Tous les utilisateurs de l'organisation « built-in » sont des administrateurs globaux dans Casdoor. Consulter la documentation : https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Si vous souhaitez encore créer un utilisateur pour l'organisation « built-in », accédez à la page des paramètres de l'organisation et activez l'option « A le consentement aux privilèges »."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "La permission : \\\"%s\\\" n'existe pas"
"The permission: \"%s\" doesn't exist": "La permission : \"%s\" n'existe pas"
},
"product": {
"Product list cannot be empty": "La liste des produits ne peut pas être vide"
},
"provider": {
"Failed to initialize ID Verification provider": "Échec de l'initialisation du fournisseur de vérification d'identité",
"Invalid application id": "Identifiant d'application invalide",
"No ID Verification provider configured": "Aucun fournisseur de vérification d'identité configuré",
"Provider is not an ID Verification provider": "Le fournisseur n'est pas un fournisseur de vérification d'identité",
"the provider: %s does not exist": "Le fournisseur : %s n'existe pas"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Destinataires d'e-mail invalides : %s",
"Invalid phone receivers: %s": "Destinataires de téléphone invalide : %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "session id %s is the current session and cannot be deleted"
},
"storage": {
"The objectKey: %s is not allowed": "La clé d'objet : %s n'est pas autorisée",
"The provider type: %s is not supported": "Le type de fournisseur : %s n'est pas pris en charge"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Erreur"
},
"ticket": {
"Ticket not found": "Ticket introuvable"
},
"token": {
"Grant_type: %s is not supported in this application": "Type_de_subvention : %s n'est pas pris en charge dans cette application",
"Invalid application or wrong clientSecret": "Application invalide ou clientSecret incorrect",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Le nom d'affichage ne peut pas être vide",
"ID card information and real name are required": "Les informations de la carte d'identité et le nom réel sont requis",
"Identity verification failed": "Échec de la vérification d'identité",
"MFA email is enabled but email is empty": "L'authentification MFA par e-mail est activée mais l'e-mail est vide",
"MFA phone is enabled but phone number is empty": "L'authentification MFA par téléphone est activée mais le numéro de téléphone est vide",
"New password cannot contain blank space.": "Le nouveau mot de passe ne peut pas contenir d'espace.",
"No application found for user": "Aucune application trouvée pour l'utilisateur",
"The new password must be different from your current password": "Le nouveau mot de passe doit être différent de votre mot de passe actuel",
"User is already verified": "L'utilisateur est déjà vérifié",
"the user's owner and name should not be empty": "le propriétaire et le nom de l'utilisateur ne doivent pas être vides"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Fournisseur de captcha invalide.",
"Phone number is invalid in your region %s": "Le numéro de téléphone n'est pas valide dans votre région %s",
"The forgot password feature is disabled": "La fonction de mot de passe oublié est désactivée",
"The verification code has already been used!": "Le code de vérification a déjà été utilisé !",
"The verification code has not been sent yet!": "Le code de vérification n'a pas encore été envoyé !",
"Turing test failed.": "Le test de Turing a échoué.",
@@ -196,8 +219,8 @@
"Unknown type": "Type inconnu",
"Wrong verification code!": "Mauvais code de vérification !",
"You should verify your code in %d min!": "Vous devriez vérifier votre code en %d min !",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "veuillez ajouter un fournisseur SMS à la liste \\\"Providers\\\" pour l'application : %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "veuillez ajouter un fournisseur d'e-mail à la liste \\\"Providers\\\" pour l'application : %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "veuillez ajouter un fournisseur SMS à la liste \"Providers\" pour l'application : %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "veuillez ajouter un fournisseur d'e-mail à la liste \"Providers\" pour l'application : %s",
"the user does not exist, please sign up first": "L'utilisateur n'existe pas, veuillez vous inscrire d'abord"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "ユーザーの追加に失敗しました",
"Get init score failed, error: %w": "イニットスコアの取得に失敗しました。エラー:%w",
"Please sign out first": "最初にサインアウトしてください",
"The application does not allow to sign up new account": "アプリケーションは新しいアカウントの登録を許可しません"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "このアプリケーションではメールログインは有効になっていません",
"The login method: login with face is not enabled for the application": "このアプリケーションでは顔認証ログインは有効になっていません",
"The login method: login with password is not enabled for the application": "ログイン方法:パスワードでのログインはアプリケーションで有効になっていません",
"The order: %s does not exist": "注文:%s は存在しません",
"The organization: %s does not exist": "組織「%s」は存在しません",
"The organization: %s has disabled users to signin": "組織: %s はユーザーのサインインを無効にしました",
"The plan: %s does not exist": "プラン: %sは存在しません",
@@ -57,11 +57,11 @@
"Face data mismatch": "顔認証データが一致しません",
"Failed to parse client IP: %s": "クライアント IP「%s」の解析に失敗しました",
"FirstName cannot be blank": "ファーストネームは空白にできません",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "ゲストユーザーは直接サインインする前に、ユーザー名とパスワードを設定してアカウントをアップグレードする必要があります",
"Invitation code cannot be blank": "招待コードは空にできません",
"Invitation code exhausted": "招待コードの使用回数が上限に達しました",
"Invitation code is invalid": "招待コードが無効です",
"Invitation code suspended": "招待コードは一時的に無効化されています",
"LDAP user name or password incorrect": "Ldapのユーザー名またはパスワードが間違っています",
"LastName cannot be blank": "姓は空白にできません",
"Multiple accounts with same uid, please check your ldap server": "同じuidを持つ複数のアカウントがあります。あなたのLDAPサーバーを確認してください",
"Organization does not exist": "組織は存在しません",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "ユーザーはサインインできません。管理者に連絡してください",
"The user: %s doesn't exist in LDAP server": "ユーザー「%s」は LDAP サーバーに存在しません",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "ユーザー名には英数字、アンダースコア、ハイフンしか含めることができません。連続したハイフンまたはアンダースコアは不可であり、ハイフンまたはアンダースコアで始まるまたは終わることもできません。",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "アカウントフィールド「%s」の値「%s」がアカウント項目の正規表現に一致しません",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "アプリケーション「%s」のサインアップ項目「%s」の値「%s」が正規表現に一致しません",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "アカウントフィールド「%s」の値「%s」がアカウント項目の正規表現に一致しません",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "アプリケーション「%s」のサインアップ項目「%s」の値「%s」が正規表現に一致しません",
"Username already exists": "ユーザー名はすでに存在しています",
"Username cannot be an email address": "ユーザー名には電子メールアドレスを使用できません",
"Username cannot contain white spaces": "ユーザ名にはスペースを含めることはできません",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "ユーザー名はメール形式もサポートします。ユーザー名は英数字、アンダースコア、またはハイフンのみを含め、連続するハイフンやアンダースコアは使用できません。また、ハイフンまたはアンダースコアで始まったり終わったりすることもできません。メール形式にも注意してください。",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "あなたは間違ったパスワードまたはコードを何度も入力しました。%d 分間待ってから再度お試しください",
"Your IP address: %s has been banned according to the configuration of: ": "あなたの IP アドレス「%s」は設定によりアクセスが禁止されています: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "パスワードの有効期限が切れています。「パスワードを忘れた方はこちら」をクリックしてリセットしてください",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "パスワードの有効期限が切れています。「パスワードを忘れた方はこちら」をクリックしてリセットしてください",
"Your region is not allow to signup by phone": "あなたの地域は電話でサインアップすることができません",
"password or code is incorrect": "パスワードまたはコードが正しくありません",
"password or code is incorrect, you have %s remaining chances": "パスワードまたはコードが間違っています。あと %s 回の試行機会があります",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "グループのインポートに失敗しました",
"Failed to import users": "ユーザーのインポートに失敗しました",
"Insufficient balance: new balance %v would be below credit limit %v": "残高不足:新しい残高 %v がクレジット制限 %v を下回ります",
"Insufficient balance: new organization balance %v would be below credit limit %v": "残高不足:新しい組織残高 %v がクレジット制限 %v を下回ります",
"Missing parameter": "不足しているパラメーター",
"Only admin user can specify user": "管理者ユーザーのみがユーザーを指定できます",
"Please login first": "最初にログインしてください",
"The LDAP: %s does not exist": "LDAP%s は存在しません",
"The organization: %s should have one application at least": "組織「%s」は少なくとも1つのアプリケーションを持っている必要があります",
"The syncer: %s does not exist": "同期装置:%s は存在しません",
"The user: %s doesn't exist": "そのユーザー:%sは存在しません",
"The user: %s is not found": "ユーザー:%s が見つかりません",
"User is required for User category transaction": "ユーザーカテゴリトランザクションにはユーザーが必要です",
"Wrong userId": "無効なユーザーIDです",
"don't support captchaProvider: ": "captchaProviderをサポートしないでください",
"this operation is not allowed in demo mode": "この操作はデモモードでは許可されていません",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "「built-in」組み込み組織への新しいユーザーの追加は現在無効になっています。注意「built-in」組織のすべてのユーザーは、Casdoor のグローバル管理者です。ドキュメントを参照してくださいhttps://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself。「built-in」組織のユーザーを作成したい場合は、組織の設定ページに移動し、「特権同意を持つ」オプションを有効にしてください。"
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "権限「%s」は存在しません"
"The permission: \"%s\" doesn't exist": "権限「%s」は存在しません"
},
"product": {
"Product list cannot be empty": "商品リストは空にできません"
},
"provider": {
"Failed to initialize ID Verification provider": "ID認証プロバイダーの初期化に失敗しました",
"Invalid application id": "アプリケーションIDが無効です",
"No ID Verification provider configured": "ID認証プロバイダーが設定されていません",
"Provider is not an ID Verification provider": "プロバイダーはID認証プロバイダーではありません",
"the provider: %s does not exist": "プロバイダー%sは存在しません"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "無効な電子メール受信者:%s",
"Invalid phone receivers: %s": "電話受信者が無効です:%s"
},
"session": {
"session id %s is the current session and cannot be deleted": "セッションID %s は現在のセッションであり、削除できません"
},
"storage": {
"The objectKey: %s is not allowed": "オブジェクトキー %s は許可されていません",
"The provider type: %s is not supported": "プロバイダータイプ:%sはサポートされていません"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "エラー"
},
"ticket": {
"Ticket not found": "チケットが見つかりません"
},
"token": {
"Grant_type: %s is not supported in this application": "grant_type%sはこのアプリケーションでサポートされていません",
"Invalid application or wrong clientSecret": "無効なアプリケーションまたは誤ったクライアントシークレットです",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "表示名は空にできません",
"ID card information and real name are required": "身分証明書の情報と実名が必要です",
"Identity verification failed": "身元確認に失敗しました",
"MFA email is enabled but email is empty": "MFA メールが有効になっていますが、メールアドレスが空です",
"MFA phone is enabled but phone number is empty": "MFA 電話番号が有効になっていますが、電話番号が空です",
"New password cannot contain blank space.": "新しいパスワードにはスペースを含めることはできません。",
"No application found for user": "ユーザーのアプリケーションが見つかりません",
"The new password must be different from your current password": "新しいパスワードは現在のパスワードと異なる必要があります",
"User is already verified": "ユーザーは既に認証済みです",
"the user's owner and name should not be empty": "ユーザーのオーナーと名前は空にできません"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "無効なCAPTCHAプロバイダー。",
"Phone number is invalid in your region %s": "電話番号はあなたの地域で無効です %s",
"The forgot password feature is disabled": "パスワードを忘れた機能は無効になっています",
"The verification code has already been used!": "この検証コードは既に使用されています!",
"The verification code has not been sent yet!": "検証コードはまだ送信されていません!",
"Turing test failed.": "チューリングテストは失敗しました。",
@@ -196,8 +219,8 @@
"Unknown type": "不明なタイプ",
"Wrong verification code!": "誤った検証コードです!",
"You should verify your code in %d min!": "あなたは%d分であなたのコードを確認する必要があります",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "アプリケーション「%s」の「Providers」リストに SMS プロバイダを追加してください",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "アプリケーション「%s」の「Providers」リストにメールプロバイダを追加してください",
"please add a SMS provider to the \"Providers\" list for the application: %s": "アプリケーション「%s」の「Providers」リストに SMS プロバイダを追加してください",
"please add an Email provider to the \"Providers\" list for the application: %s": "アプリケーション「%s」の「Providers」リストにメールプロバイダを追加してください",
"the user does not exist, please sign up first": "ユーザーは存在しません。まず登録してください"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Nie udało się dodać użytkownika",
"Get init score failed, error: %w": "Pobranie początkowego wyniku nie powiodło się, błąd: %w",
"Please sign out first": "Najpierw się wyloguj",
"The application does not allow to sign up new account": "Aplikacja nie pozwala na rejestrację nowego konta"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "Metoda logowania: logowanie przez email nie jest włączona dla aplikacji",
"The login method: login with face is not enabled for the application": "Metoda logowania: logowanie przez twarz nie jest włączona dla aplikacji",
"The login method: login with password is not enabled for the application": "Metoda logowania: logowanie przez hasło nie jest włączone dla aplikacji",
"The order: %s does not exist": "Zamówienie: %s nie istnieje",
"The organization: %s does not exist": "Organizacja: %s nie istnieje",
"The organization: %s has disabled users to signin": "Organizacja: %s wyłączyła logowanie użytkowników",
"The plan: %s does not exist": "Plan: %s nie istnieje",
@@ -57,11 +57,11 @@
"Face data mismatch": "Niezgodność danych twarzy",
"Failed to parse client IP: %s": "Nie udało się przeanalizować IP klienta: %s",
"FirstName cannot be blank": "Imię nie może być puste",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Użytkownicy-goście muszą uaktualnić swoje konto, ustawiając nazwę użytkownika i hasło, zanim będą mogli się zalogować bezpośrednio",
"Invitation code cannot be blank": "Kod zaproszenia nie może być pusty",
"Invitation code exhausted": "Kod zaproszenia został wykorzystany",
"Invitation code is invalid": "Kod zaproszenia jest nieprawidłowy",
"Invitation code suspended": "Kod zaproszenia został zawieszony",
"LDAP user name or password incorrect": "Nazwa użytkownika LDAP lub hasło jest nieprawidłowe",
"LastName cannot be blank": "Nazwisko nie może być puste",
"Multiple accounts with same uid, please check your ldap server": "Wiele kont z tym samym uid, sprawdź swój serwer ldap",
"Organization does not exist": "Organizacja nie istnieje",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "Użytkownikowi zabroniono logowania, skontaktuj się z administratorem",
"The user: %s doesn't exist in LDAP server": "Użytkownik: %s nie istnieje w serwerze LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Nazwa użytkownika może zawierać tylko znaki alfanumeryczne, podkreślenia lub myślniki, nie może mieć kolejnych myślników lub podkreśleń i nie może zaczynać się ani kończyć myślnikiem lub podkreśleniem.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "Wartość \\\"%s\\\" dla pola konta \\\"%s\\\" nie pasuje do wyrażenia regularnego elementu konta",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "Wartość \\\"%s\\\" dla pola rejestracji \\\"%s\\\" nie pasuje do wyrażenia regularnego elementu rejestracji aplikacji \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "Wartość \"%s\" dla pola konta \"%s\" nie pasuje do wyrażenia regularnego elementu konta",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "Wartość \"%s\" dla pola rejestracji \"%s\" nie pasuje do wyrażenia regularnego elementu rejestracji aplikacji \"%s\"",
"Username already exists": "Nazwa użytkownika już istnieje",
"Username cannot be an email address": "Nazwa użytkownika nie może być adresem email",
"Username cannot contain white spaces": "Nazwa użytkownika nie może zawierać spacji",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Nazwa użytkownika obsługuje format email. Również nazwa użytkownika może zawierać tylko znaki alfanumeryczne, podkreślenia lub myślniki, nie może mieć kolejnych myślników lub podkreśleń i nie może zaczynać się ani kończyć myślnikiem lub podkreśleniem. Zwróć też uwagę na format email.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Wprowadziłeś złe hasło lub kod zbyt wiele razy, poczekaj %d minut i spróbuj ponownie",
"Your IP address: %s has been banned according to the configuration of: ": "Twój adres IP: %s został zablokowany zgodnie z konfiguracją: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Twoje hasło wygasło. Zresetuj hasło klikając \\\"Zapomniałem hasła\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Twoje hasło wygasło. Zresetuj hasło klikając \"Zapomniałem hasła\"",
"Your region is not allow to signup by phone": "Twój region nie pozwala na rejestrację przez telefon",
"password or code is incorrect": "hasło lub kod jest nieprawidłowe",
"password or code is incorrect, you have %s remaining chances": "hasło lub kod jest nieprawidłowe, masz jeszcze %s prób",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Nie udało się zaimportować grup",
"Failed to import users": "Nie udało się zaimportować użytkowników",
"Insufficient balance: new balance %v would be below credit limit %v": "Niewystarczające saldo: nowe saldo %v byłoby poniżej limitu kredytowego %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Niewystarczające saldo: nowe saldo organizacji %v byłoby poniżej limitu kredytowego %v",
"Missing parameter": "Brakujący parametr",
"Only admin user can specify user": "Tylko administrator może wskazać użytkownika",
"Please login first": "Najpierw się zaloguj",
"The LDAP: %s does not exist": "LDAP: %s nie istnieje",
"The organization: %s should have one application at least": "Organizacja: %s powinna mieć co najmniej jedną aplikację",
"The syncer: %s does not exist": "Synchronizer: %s nie istnieje",
"The user: %s doesn't exist": "Użytkownik: %s nie istnieje",
"The user: %s is not found": "Użytkownik: %s nie został znaleziony",
"User is required for User category transaction": "Użytkownik jest wymagany do transakcji kategorii użytkownika",
"Wrong userId": "Nieprawidłowy userId",
"don't support captchaProvider: ": "nie obsługuje captchaProvider: ",
"this operation is not allowed in demo mode": "ta operacja nie jest dozwolona w trybie demo",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "Dodawanie nowego użytkownika do organizacji „built-in' (wbudowanej) jest obecnie wyłączone. Należy zauważyć, że wszyscy użytkownicy w organizacji „built-in' są globalnymi administratorami w Casdoor. Zobacz dokumentację: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Jeśli nadal chcesz utworzyć użytkownika dla organizacji „built-in', przejdź do strony ustawień organizacji i włącz opcję „Ma zgodę na uprawnienia'."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "Uprawnienie: \\\"%s\\\" nie istnieje"
"The permission: \"%s\" doesn't exist": "Uprawnienie: \"%s\" nie istnieje"
},
"product": {
"Product list cannot be empty": "Lista produktów nie może być pusta"
},
"provider": {
"Failed to initialize ID Verification provider": "Nie udało się zainicjować dostawcy weryfikacji ID",
"Invalid application id": "Nieprawidłowe id aplikacji",
"No ID Verification provider configured": "Brak skonfigurowanego dostawcy weryfikacji ID",
"Provider is not an ID Verification provider": "Dostawca nie jest dostawcą weryfikacji ID",
"the provider: %s does not exist": "dostawca: %s nie istnieje"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Nieprawidłowi odbiorcy email: %s",
"Invalid phone receivers: %s": "Nieprawidłowi odbiorcy telefonu: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "identyfikator sesji %s jest bieżącą sesją i nie może być usunięty"
},
"storage": {
"The objectKey: %s is not allowed": "Klucz obiektu: %s jest niedozwolony",
"The provider type: %s is not supported": "Typ dostawcy: %s nie jest obsługiwany"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Błąd"
},
"ticket": {
"Ticket not found": "Nie znaleziono biletu"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s nie jest obsługiwany w tej aplikacji",
"Invalid application or wrong clientSecret": "Nieprawidłowa aplikacja lub błędny clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Nazwa wyświetlana nie może być pusta",
"ID card information and real name are required": "Wymagane są informacje z dowodu osobistego i prawdziwe nazwisko",
"Identity verification failed": "Weryfikacja tożsamości nie powiodła się",
"MFA email is enabled but email is empty": "MFA email jest włączone, ale email jest pusty",
"MFA phone is enabled but phone number is empty": "MFA telefon jest włączony, ale numer telefonu jest pusty",
"New password cannot contain blank space.": "Nowe hasło nie może zawierać spacji.",
"No application found for user": "Nie znaleziono aplikacji dla użytkownika",
"The new password must be different from your current password": "Nowe hasło musi różnić się od obecnego hasła",
"User is already verified": "Użytkownik jest już zweryfikowany",
"the user's owner and name should not be empty": "właściciel i nazwa użytkownika nie powinny być puste"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Nieprawidłowy dostawca captcha.",
"Phone number is invalid in your region %s": "Numer telefonu jest nieprawidłowy w twoim regionie %s",
"The forgot password feature is disabled": "Funkcja \"Zapomniałem hasła\" jest wyłączona",
"The verification code has already been used!": "Kod weryfikacyjny został już wykorzystany!",
"The verification code has not been sent yet!": "Kod weryfikacyjny nie został jeszcze wysłany!",
"Turing test failed.": "Test Turinga nie powiódł się.",
@@ -196,8 +219,8 @@
"Unknown type": "Nieznany typ",
"Wrong verification code!": "Zły kod weryfikacyjny!",
"You should verify your code in %d min!": "Powinieneś zweryfikować swój kod w ciągu %d min!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "proszę dodać dostawcę SMS do listy \\\"Providers\\\" dla aplikacji: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "proszę dodać dostawcę email do listy \\\"Providers\\\" dla aplikacji: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "proszę dodać dostawcę SMS do listy \"Providers\" dla aplikacji: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "proszę dodać dostawcę email do listy \"Providers\" dla aplikacji: %s",
"the user does not exist, please sign up first": "użytkownik nie istnieje, najpierw się zarejestruj"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Falha ao adicionar usuário",
"Get init score failed, error: %w": "Falha ao obter pontuação inicial, erro: %w",
"Please sign out first": "Por favor, saia primeiro",
"The application does not allow to sign up new account": "O aplicativo não permite a criação de novas contas"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "O método de login com e-mail não está habilitado para o aplicativo",
"The login method: login with face is not enabled for the application": "O método de login com reconhecimento facial não está habilitado para o aplicativo",
"The login method: login with password is not enabled for the application": "O método de login com senha não está habilitado para o aplicativo",
"The order: %s does not exist": "O pedido: %s não existe",
"The organization: %s does not exist": "A organização: %s não existe",
"The organization: %s has disabled users to signin": "A organização: %s desativou o login de usuários",
"The plan: %s does not exist": "O plano: %s não existe",
@@ -57,11 +57,11 @@
"Face data mismatch": "Dados faciais não correspondem",
"Failed to parse client IP: %s": "Falha ao analisar o IP do cliente: %s",
"FirstName cannot be blank": "O primeiro nome não pode estar em branco",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Usuários convidados devem atualizar suas contas definindo um nome de usuário e senha antes de poderem entrar diretamente",
"Invitation code cannot be blank": "O código de convite não pode estar em branco",
"Invitation code exhausted": "O código de convite foi esgotado",
"Invitation code is invalid": "Código de convite inválido",
"Invitation code suspended": "Código de convite suspenso",
"LDAP user name or password incorrect": "Nome de usuário ou senha LDAP incorretos",
"LastName cannot be blank": "O sobrenome não pode estar em branco",
"Multiple accounts with same uid, please check your ldap server": "Múltiplas contas com o mesmo uid, verifique seu servidor LDAP",
"Organization does not exist": "A organização não existe",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "O usuário está proibido de entrar, entre em contato com o administrador",
"The user: %s doesn't exist in LDAP server": "O usuário: %s não existe no servidor LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "O nome de usuário pode conter apenas caracteres alfanuméricos, sublinhados ou hífens, não pode ter hífens ou sublinhados consecutivos e não pode começar ou terminar com hífen ou sublinhado.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "O valor \\\"%s\\\" para o campo de conta \\\"%s\\\" não corresponde à expressão regular definida",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "O valor \\\"%s\\\" para o campo de registro \\\"%s\\\" não corresponde à expressão regular definida na aplicação \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "O valor \"%s\" para o campo de conta \"%s\" não corresponde à expressão regular definida",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "O valor \"%s\" para o campo de registro \"%s\" não corresponde à expressão regular definida na aplicação \"%s\"",
"Username already exists": "O nome de usuário já existe",
"Username cannot be an email address": "O nome de usuário não pode ser um endereço de e-mail",
"Username cannot contain white spaces": "O nome de usuário não pode conter espaços em branco",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "O nome de usuário suporta o formato de e-mail. Além disso, pode conter apenas caracteres alfanuméricos, sublinhados ou hífens, não pode ter hífens ou sublinhados consecutivos e não pode começar ou terminar com hífen ou sublinhado. Também preste atenção ao formato do e-mail.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Você digitou a senha ou o código incorretos muitas vezes. Aguarde %d minutos e tente novamente",
"Your IP address: %s has been banned according to the configuration of: ": "Seu endereço IP: %s foi bloqueado de acordo com a configuração de: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Sua senha expirou. Por favor, redefina-a clicando em \\\"Esqueci a senha\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Sua senha expirou. Por favor, redefina-a clicando em \"Esqueci a senha\"",
"Your region is not allow to signup by phone": "Sua região não permite cadastro por telefone",
"password or code is incorrect": "Senha ou código incorreto",
"password or code is incorrect, you have %s remaining chances": "Senha ou código incorreto, você tem %s tentativas restantes",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Falha ao importar grupos",
"Failed to import users": "Falha ao importar usuários",
"Insufficient balance: new balance %v would be below credit limit %v": "Saldo insuficiente: o novo saldo %v estaria abaixo do limite de crédito %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Saldo insuficiente: o novo saldo da organização %v estaria abaixo do limite de crédito %v",
"Missing parameter": "Parâmetro ausente",
"Only admin user can specify user": "Apenas um administrador pode especificar um usuário",
"Please login first": "Por favor, faça login primeiro",
"The LDAP: %s does not exist": "O LDAP: %s não existe",
"The organization: %s should have one application at least": "A organização: %s deve ter pelo menos um aplicativo",
"The syncer: %s does not exist": "O sincronizador: %s não existe",
"The user: %s doesn't exist": "O usuário: %s não existe",
"The user: %s is not found": "O usuário: %s não foi encontrado",
"User is required for User category transaction": "Usuário é obrigatório para transação de categoria de usuário",
"Wrong userId": "ID de usuário incorreto",
"don't support captchaProvider: ": "captchaProvider não suportado: ",
"this operation is not allowed in demo mode": "esta operação não é permitida no modo de demonstração",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "A adição de novos usuários à organização 'built-in' está desativada. Observe que todos os usuários nessa organização são administradores globais no Casdoor. Consulte a documentação: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Se ainda desejar criar um usuário, vá até a página de configurações da organização e habilite a opção 'Possui consentimento de privilégios'."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "A permissão: \\\"%s\\\" não existe"
"The permission: \"%s\" doesn't exist": "A permissão: \"%s\" não existe"
},
"product": {
"Product list cannot be empty": "A lista de produtos não pode estar vazia"
},
"provider": {
"Failed to initialize ID Verification provider": "Falha ao inicializar provedor de verificação de ID",
"Invalid application id": "ID de aplicativo inválido",
"No ID Verification provider configured": "Nenhum provedor de verificação de ID configurado",
"Provider is not an ID Verification provider": "Provedor não é um provedor de verificação de ID",
"the provider: %s does not exist": "O provedor: %s não existe"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Destinatários de e-mail inválidos: %s",
"Invalid phone receivers: %s": "Destinatários de telefone inválidos: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "ID da sessão %s é a sessão atual e não pode ser excluída"
},
"storage": {
"The objectKey: %s is not allowed": "A chave de objeto: %s não é permitida",
"The provider type: %s is not supported": "O tipo de provedor: %s não é suportado"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Erro"
},
"ticket": {
"Ticket not found": "Ticket não encontrado"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s não é suportado neste aplicativo",
"Invalid application or wrong clientSecret": "Aplicativo inválido ou clientSecret incorreto",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "O nome de exibição não pode estar vazio",
"ID card information and real name are required": "Informações do documento de identidade e nome verdadeiro são obrigatórios",
"Identity verification failed": "Falha na verificação de identidade",
"MFA email is enabled but email is empty": "MFA por e-mail está habilitado, mas o e-mail está vazio",
"MFA phone is enabled but phone number is empty": "MFA por telefone está habilitado, mas o número de telefone está vazio",
"New password cannot contain blank space.": "A nova senha não pode conter espaços em branco.",
"No application found for user": "Nenhum aplicativo encontrado para o usuário",
"The new password must be different from your current password": "A nova senha deve ser diferente da senha atual",
"User is already verified": "Usuário já está verificado",
"the user's owner and name should not be empty": "O proprietário e o nome do usuário não devem estar vazios"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Provedor de captcha inválido.",
"Phone number is invalid in your region %s": "Número de telefone inválido na sua região %s",
"The forgot password feature is disabled": "A funcionalidade de esqueci a senha está desabilitada",
"The verification code has already been used!": "O código de verificação já foi utilizado!",
"The verification code has not been sent yet!": "O código de verificação ainda não foi enviado!",
"Turing test failed.": "O teste de Turing falhou.",
@@ -196,8 +219,8 @@
"Unknown type": "Tipo desconhecido",
"Wrong verification code!": "Código de verificação incorreto!",
"You should verify your code in %d min!": "Você deve verificar seu código em %d minuto(s)!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "Adicione um provedor de SMS à lista \\\"Providers\\\" do aplicativo: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "Adicione um provedor de e-mail à lista \\\"Providers\\\" do aplicativo: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "Adicione um provedor de SMS à lista \"Providers\" do aplicativo: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "Adicione um provedor de e-mail à lista \"Providers\" do aplicativo: %s",
"the user does not exist, please sign up first": "O usuário não existe, cadastre-se primeiro"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Kullanıcı eklenemedi",
"Get init score failed, error: %w": "Başlangıç puanı alınamadı, hata: %w",
"Please sign out first": "Lütfen önce çıkış yapın",
"The application does not allow to sign up new account": "Uygulama yeni hesap kaydına izin vermiyor"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "Uygulama için e-posta ile giriş yöntemi etkin değil",
"The login method: login with face is not enabled for the application": "Uygulama için yüz ile giriş yöntemi etkin değil",
"The login method: login with password is not enabled for the application": "Şifre ile giriş yöntemi bu uygulama için etkin değil",
"The order: %s does not exist": "Sipariş: %s mevcut değil",
"The organization: %s does not exist": "Organizasyon: %s mevcut değil",
"The organization: %s has disabled users to signin": "Organizasyon: %s kullanıcıların oturum açmasını devre dışı bıraktı",
"The plan: %s does not exist": "Plan: %s mevcut değil",
@@ -57,11 +57,11 @@
"Face data mismatch": "Yüz verisi uyuşmazlığı",
"Failed to parse client IP: %s": "İstemci IP'si ayrıştırılamadı: %s",
"FirstName cannot be blank": "Ad boş olamaz",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Misafir kullanıcılar doğrudan giriş yapabilmek için kullanıcı adı ve şifre belirleyerek hesaplarını yükseltmelidir",
"Invitation code cannot be blank": "Davet kodu boş olamaz",
"Invitation code exhausted": "Davet kodu kullanım dışı",
"Invitation code is invalid": "Davet kodu geçersiz",
"Invitation code suspended": "Davet kodu askıya alındı",
"LDAP user name or password incorrect": "LDAP kullanıcı adı veya şifre yanlış",
"LastName cannot be blank": "Soyad boş olamaz",
"Multiple accounts with same uid, please check your ldap server": "Aynı uid'ye sahip birden fazla hesap, lütfen ldap sunucunuzu kontrol edin",
"Organization does not exist": "Organizasyon bulunamadı",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "Kullanıcı giriş yapmaktan men edildi, lütfen yönetici ile iletişime geçin",
"The user: %s doesn't exist in LDAP server": "Kullanıcı: %s LDAP sunucusunda mevcut değil",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Kullanıcı adı yalnızca alfanümerik karakterler, alt çizgi veya tire içerebilir, ardışık tire veya alt çizgi içeremez ve tire veya alt çizgi ile başlayamaz veya bitemez.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "Hesap alanı \\\"%s\\\" için \\\"%s\\\" değeri, hesap öğesi regex'iyle eşleşmiyor",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "Kayıt alanı \\\"%s\\\" için \\\"%s\\\" değeri, \\\"%s\\\" uygulamasının kayıt öğesi regex'iyle eşleşmiyor",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "Hesap alanı \"%s\" için \"%s\" değeri, hesap öğesi regex'iyle eşleşmiyor",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "Kayıt alanı \"%s\" için \"%s\" değeri, \"%s\" uygulamasının kayıt öğesi regex'iyle eşleşmiyor",
"Username already exists": "Kullanıcı adı zaten var",
"Username cannot be an email address": "Kullanıcı adı e-posta adresi olamaz",
"Username cannot contain white spaces": "Kullanıcı adı boşluk içeremez",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Kullanıcı adı e-posta biçimini destekler. Ayrıca kullanıcı adı yalnızca alfanümerik karakterler, alt çizgiler veya tireler içerebilir, ardışık tireler veya alt çizgiler olamaz ve tire veya alt çizgi ile başlayıp bitemez. Ayrıca e-posta biçimine dikkat edin.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Çok fazla hatalı şifre veya kod girdiniz, lütfen %d dakika bekleyin ve tekrar deneyin",
"Your IP address: %s has been banned according to the configuration of: ": "IP adresiniz: %s, yapılandırmaya göre yasaklandı: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Şifrenizin süresi doldu. Lütfen \\\"Şifremi unuttum\\\"a tıklayarak şifrenizi sıfırlayın",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Şifrenizin süresi doldu. Lütfen \"Şifremi unuttum\"a tıklayarak şifrenizi sıfırlayın",
"Your region is not allow to signup by phone": "Bölgeniz telefonla kayıt yapmaya izin verilmiyor",
"password or code is incorrect": "şifre veya kod yanlış",
"password or code is incorrect, you have %s remaining chances": "şifre veya kod yanlış, %s hakkınız kaldı",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Gruplar içe aktarılamadı",
"Failed to import users": "Kullanıcılar içe aktarılamadı",
"Insufficient balance: new balance %v would be below credit limit %v": "Yetersiz bakiye: yeni bakiye %v kredi limitinin altında olacak %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Yetersiz bakiye: yeni organizasyon bakiyesi %v kredi limitinin altında olacak %v",
"Missing parameter": "Eksik parametre",
"Only admin user can specify user": "Yalnızca yönetici kullanıcı kullanıcı belirleyebilir",
"Please login first": "Lütfen önce giriş yapın",
"The LDAP: %s does not exist": "LDAP: %s mevcut değil",
"The organization: %s should have one application at least": "Organizasyon: %s en az bir uygulamaya sahip olmalı",
"The syncer: %s does not exist": "Senkronizasyon: %s mevcut değil",
"The user: %s doesn't exist": "Kullanıcı: %s bulunamadı",
"The user: %s is not found": "Kullanıcı: %s bulunamadı",
"User is required for User category transaction": "Kullanıcı kategorisi işlemi için kullanıcı gerekli",
"Wrong userId": "Yanlış kullanıcı kimliği",
"don't support captchaProvider: ": "captchaProvider desteklenmiyor: ",
"this operation is not allowed in demo mode": "bu işlem demo modunda izin verilmiyor",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "'built-in' (yerleşik) organizasyona yeni bir kullanıcı ekleme şu anda devre dışı bırakılmıştır. Not: 'built-in' organizasyonundaki tüm kullanıcılar Casdoor'da genel yöneticilerdir. Belgelere bakın: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Hala 'built-in' organizasyonu için bir kullanıcı oluşturmak isterseniz, organizasyonun ayarları sayfasına gidin ve 'Yetki onayı var' seçeneğini etkinleştirin."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "İzin: \\\"%s\\\" mevcut değil"
"The permission: \"%s\" doesn't exist": "İzin: \"%s\" mevcut değil"
},
"product": {
"Product list cannot be empty": "Ürün listesi boş olamaz"
},
"provider": {
"Failed to initialize ID Verification provider": "Kimlik Doğrulama sağlayıcısı başlatılamadı",
"Invalid application id": "Geçersiz uygulama id",
"No ID Verification provider configured": "Kimlik Doğrulama sağlayıcısı yapılandırılmamış",
"Provider is not an ID Verification provider": "Sağlayıcı bir Kimlik Doğrulama sağlayıcısı değil",
"the provider: %s does not exist": "provider: %s bulunamadı"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Geçersiz e-posta alıcıları: %s",
"Invalid phone receivers: %s": "Geçersiz telefon alıcıları: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "oturum kimliği %s geçerli oturumdur ve silinemez"
},
"storage": {
"The objectKey: %s is not allowed": "objectKey: %s izin verilmiyor",
"The provider type: %s is not supported": "provider türü: %s desteklenmiyor"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Hata"
},
"ticket": {
"Ticket not found": "Bilet bulunamadı"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s bu uygulamada desteklenmiyor",
"Invalid application or wrong clientSecret": "Geçersiz uygulama veya yanlış clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Görünen ad boş olamaz",
"ID card information and real name are required": "Kimlik kartı bilgileri ve gerçek adı gereklidir",
"Identity verification failed": "Kimlik doğrulama başarısız",
"MFA email is enabled but email is empty": "MFA e-postası etkin ancak e-posta boş",
"MFA phone is enabled but phone number is empty": "MFA telefonu etkin ancak telefon numarası boş",
"New password cannot contain blank space.": "Yeni şifre boşluk içeremez.",
"No application found for user": "Kullanıcı için uygulama bulunamadı",
"The new password must be different from your current password": "Yeni şifre mevcut şifrenizden farklı olmalıdır",
"User is already verified": "Kullanıcı zaten doğrulanmış",
"the user's owner and name should not be empty": "kullanıcının sahibi ve adı boş olmamalıdır"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Geçersiz captcha sağlayıcı.",
"Phone number is invalid in your region %s": "Telefon numaranız bölgenizde geçersiz %s",
"The forgot password feature is disabled": "Şifremi unuttum özelliği devre dışı",
"The verification code has already been used!": "Doğrulama kodu zaten kullanılmış!",
"The verification code has not been sent yet!": "Doğrulama kodu henüz gönderilmedi!",
"Turing test failed.": "Turing testi başarısız.",
@@ -196,8 +219,8 @@
"Unknown type": "Bilinmeyen tür",
"Wrong verification code!": "Yanlış doğrulama kodu!",
"You should verify your code in %d min!": "Kodunuzu %d dakika içinde doğrulamalısınız!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "lütfen uygulama için \\\"Sağlayıcılar\\\" listesine bir SMS sağlayıcı ekleyin: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "lütfen uygulama için \\\"Sağlayıcılar\\\" listesine bir E-posta sağlayıcı ekleyin: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "lütfen uygulama için \"Sağlayıcılar\" listesine bir SMS sağlayıcı ekleyin: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "lütfen uygulama için \"Sağlayıcılar\" listesine bir E-posta sağlayıcı ekleyin: %s",
"the user does not exist, please sign up first": "kullanıcı mevcut değil, lütfen önce kaydolun"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Не вдалося додати користувача",
"Get init score failed, error: %w": "Не вдалося отримати початковий бал, помилка: %w",
"Please sign out first": "Спочатку вийдіть із системи",
"The application does not allow to sign up new account": "Додаток не дозволяє реєструвати нові облікові записи"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "Метод входу через email не увімкнено для цього додатка",
"The login method: login with face is not enabled for the application": "Метод входу через обличчя не увімкнено для цього додатка",
"The login method: login with password is not enabled for the application": "Метод входу через пароль не увімкнено для цього додатка",
"The order: %s does not exist": "Замовлення: %s не існує",
"The organization: %s does not exist": "Організація: %s не існує",
"The organization: %s has disabled users to signin": "Організація: %s вимкнула вхід користувачів",
"The plan: %s does not exist": "План: %s не існує",
@@ -57,11 +57,11 @@
"Face data mismatch": "Невідповідність даних обличчя",
"Failed to parse client IP: %s": "Не вдалося розібрати IP клієнта: %s",
"FirstName cannot be blank": "Ім’я не може бути порожнім",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Гостьові користувачі повинні оновити свій обліковий запис, встановивши ім'я користувача та пароль, перш ніж вони зможуть увійти безпосередньо",
"Invitation code cannot be blank": "Код запрошення не може бути порожнім",
"Invitation code exhausted": "Код запрошення вичерпано",
"Invitation code is invalid": "Код запрошення недійсний",
"Invitation code suspended": "Код запрошення призупинено",
"LDAP user name or password incorrect": "Ім’я користувача або пароль LDAP неправильні",
"LastName cannot be blank": "Прізвище не може бути порожнім",
"Multiple accounts with same uid, please check your ldap server": "Кілька облікових записів з однаковим uid, перевірте ваш ldap-сервер",
"Organization does not exist": "Організація не існує",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "Користувачу заборонено вхід, зверніться до адміністратора",
"The user: %s doesn't exist in LDAP server": "Користувач: %s не існує на сервері LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Ім’я користувача може містити лише буквено-цифрові символи, підкреслення або дефіси, не може мати послідовні дефіси або підкреслення та не може починатися або закінчуватися дефісом або підкресленням.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "Värdet \\\"%s\\\" för kontofältet \\\"%s\\\" matchar inte kontots regex",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "Värdet \\\"%s\\\" för registreringsfältet \\\"%s\\\" matchar inte registreringsfältets regex för applikationen \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "Значення \"%s\" для поля облікового запису \"%s\" не відповідає регулярному виразу облікового запису",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "Значення \"%s\" для поля реєстрації \"%s\" не відповідає регулярному виразу поля реєстрації додатка \"%s\"",
"Username already exists": "Ім’я користувача вже існує",
"Username cannot be an email address": "Ім’я користувача не може бути email-адресою",
"Username cannot contain white spaces": "Ім’я користувача не може містити пробіли",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Ім’я користувача підтримує формат email. Також може містити лише буквено-цифрові символи, підкреслення або дефіси, не може мати послідовні дефіси або підкреслення та не може починатися або закінчуватися дефісом або підкресленням. Зверніть увагу на формат email.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Ви ввели неправильний пароль або код забагато разів, зачекайте %d хвилин і спробуйте знову",
"Your IP address: %s has been banned according to the configuration of: ": "Ваша IP-адреса: %s заблокована відповідно до конфігурації: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Ditt lösenord har gått ut. Återställ det genom att klicka på \\\"Glömt lösenord\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Ваш пароль застарів. Будь ласка, скиньте пароль, натиснувши \"Забув пароль\"",
"Your region is not allow to signup by phone": "У вашому регіоні реєстрація за телефоном недоступна",
"password or code is incorrect": "пароль або код неправильний",
"password or code is incorrect, you have %s remaining chances": "пароль або код неправильний, у вас залишилось %s спроб",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Не вдалося імпортувати групи",
"Failed to import users": "Не вдалося імпортувати користувачів",
"Insufficient balance: new balance %v would be below credit limit %v": "Недостатній баланс: новий баланс %v буде нижче кредитного ліміту %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Недостатній баланс: новий баланс організації %v буде нижче кредитного ліміту %v",
"Missing parameter": "Відсутній параметр",
"Only admin user can specify user": "Лише адміністратор може вказати користувача",
"Please login first": "Спочатку увійдіть",
"The LDAP: %s does not exist": "LDAP: %s не існує",
"The organization: %s should have one application at least": "Організація: %s має мати щонайменше один додаток",
"The syncer: %s does not exist": "Синхронізатор: %s не існує",
"The user: %s doesn't exist": "Користувач: %s не існує",
"The user: %s is not found": "Користувач: %s не знайдено",
"User is required for User category transaction": "Користувач обов'язковий для транзакції категорії користувача",
"Wrong userId": "Неправильний userId",
"don't support captchaProvider: ": "не підтримується captchaProvider: ",
"this operation is not allowed in demo mode": "ця операція недоступна в демо-режимі",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "Додавання нового користувача до організації «built-in» (вбудованої) на даний момент вимкнено. Зауважте: усі користувачі в організації «built-in» є глобальними адміністраторами в Casdoor. Дивіться документацію: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Якщо ви все ще хочете створити користувача для організації «built-in», перейдіть на сторінку налаштувань організації та увімкніть опцію «Має згоду на привілеї»."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "Behörigheten: \\\"%s\\\" finns inte"
"The permission: \"%s\" doesn't exist": "Дозвіл: \"%s\" не існує"
},
"product": {
"Product list cannot be empty": "Список товарів не може бути порожнім"
},
"provider": {
"Failed to initialize ID Verification provider": "Не вдалося ініціалізувати провайдера верифікації ID",
"Invalid application id": "Недійсний id додатка",
"No ID Verification provider configured": "Провайдер верифікації ID не налаштований",
"Provider is not an ID Verification provider": "Провайдер не є провайдером верифікації ID",
"the provider: %s does not exist": "провайдер: %s не існує"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Недійсні отримувачі Email: %s",
"Invalid phone receivers: %s": "Недійсні отримувачі телефону: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "ідентифікатор сесії %s є поточною сесією і не може бути видалений"
},
"storage": {
"The objectKey: %s is not allowed": "objectKey: %s не дозволено",
"The provider type: %s is not supported": "Тип провайдера: %s не підтримується"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Помилка"
},
"ticket": {
"Ticket not found": "Квиток не знайдено"
},
"token": {
"Grant_type: %s is not supported in this application": "Grant_type: %s не підтримується в цьому додатку",
"Invalid application or wrong clientSecret": "Недійсний додаток або неправильний clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Відображуване ім’я не може бути порожнім",
"ID card information and real name are required": "Інформація про посвідчення особи та справжнє ім'я обов'язкові",
"Identity verification failed": "Верифікація особи не вдалася",
"MFA email is enabled but email is empty": "MFA email увімкнено, але email порожній",
"MFA phone is enabled but phone number is empty": "MFA телефон увімкнено, але номер телефону порожній",
"New password cannot contain blank space.": "Новий пароль не може містити пробіли.",
"No application found for user": "Не знайдено додаток для користувача",
"The new password must be different from your current password": "Новий пароль повинен відрізнятися від поточного пароля",
"User is already verified": "Користувач уже верифікований",
"the user's owner and name should not be empty": "власник ім’я користувача не повинні бути порожніми"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Недійсний провайдер captcha.",
"Phone number is invalid in your region %s": "Номер телефону недійсний у вашому регіоні %s",
"The forgot password feature is disabled": "Функція відновлення пароля вимкнена",
"The verification code has already been used!": "Код підтвердження вже використано!",
"The verification code has not been sent yet!": "Код підтвердження ще не надіслано!",
"Turing test failed.": "Тест Тюрінга не пройдено.",
@@ -196,8 +219,8 @@
"Unknown type": "Невідомий тип",
"Wrong verification code!": "Неправильний код підтвердження!",
"You should verify your code in %d min!": "Ви маєте підтвердити код за %d хв!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "lägg till en SMS-leverantör i listan \\\"Leverantörer\\\" för applikationen: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "lägg till en e-postleverantör i listan \\\"Leverantörer\\\" för applikationen: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "будь ласка, додайте SMS-провайдера до списку \"Провайдери\" для додатка: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "будь ласка, додайте Email-провайдера до списку \"Провайдери\" для додатка: %s",
"the user does not exist, please sign up first": "користувача не існує, спочатку зареєструйтесь"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "Không thể thêm người dùng",
"Get init score failed, error: %w": "Lấy điểm khởi đầu thất bại, lỗi: %w",
"Please sign out first": "Vui lòng đăng xuất trước",
"The application does not allow to sign up new account": "Ứng dụng không cho phép đăng ký tài khoản mới"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "Phương thức đăng nhập bằng email chưa được bật cho ứng dụng",
"The login method: login with face is not enabled for the application": "Phương thức đăng nhập bằng khuôn mặt chưa được bật cho ứng dụng",
"The login method: login with password is not enabled for the application": "Phương thức đăng nhập: đăng nhập bằng mật khẩu không được kích hoạt cho ứng dụng",
"The order: %s does not exist": "Đơn hàng: %s không tồn tại",
"The organization: %s does not exist": "Tổ chức: %s không tồn tại",
"The organization: %s has disabled users to signin": "Tổ chức: %s đã vô hiệu hóa đăng nhập của người dùng",
"The plan: %s does not exist": "Kế hoạch: %s không tồn tại",
@@ -57,11 +57,11 @@
"Face data mismatch": "Dữ liệu khuôn mặt không khớp",
"Failed to parse client IP: %s": "Không thể phân tích IP khách: %s",
"FirstName cannot be blank": "Tên không được để trống",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "Người dùng khách phải nâng cấp tài khoản bằng cách đặt tên người dùng và mật khẩu trước khi có thể đăng nhập trực tiếp",
"Invitation code cannot be blank": "Mã mời không được để trống",
"Invitation code exhausted": "Mã mời đã hết",
"Invitation code is invalid": "Mã mời không hợp lệ",
"Invitation code suspended": "Mã mời đã bị tạm ngưng",
"LDAP user name or password incorrect": "Tên người dùng hoặc mật khẩu Ldap không chính xác",
"LastName cannot be blank": "Họ không thể để trống",
"Multiple accounts with same uid, please check your ldap server": "Nhiều tài khoản với cùng một uid, vui lòng kiểm tra máy chủ ldap của bạn",
"Organization does not exist": "Tổ chức không tồn tại",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "Người dùng bị cấm đăng nhập, vui lòng liên hệ với quản trị viên",
"The user: %s doesn't exist in LDAP server": "Người dùng: %s không tồn tại trên máy chủ LDAP",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "Tên người dùng chỉ có thể chứa các ký tự chữ và số, gạch dưới hoặc gạch ngang, không được có hai ký tự gạch dưới hoặc gạch ngang liền kề và không được bắt đầu hoặc kết thúc bằng dấu gạch dưới hoặc gạch ngang.",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "Giá trị \\\"%s\\\" cho trường tài khoản \\\"%s\\\" không khớp với biểu thức chính quy của mục tài khoản",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "Giá trị \\\"%s\\\" cho trường đăng ký \\\"%s\\\" không khớp với biểu thức chính quy của mục đăng ký trong ứng dụng \\\"%s\\\"",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "Giá trị \"%s\" cho trường tài khoản \"%s\" không khớp với biểu thức chính quy của mục tài khoản",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "Giá trị \"%s\" cho trường đăng ký \"%s\" không khớp với biểu thức chính quy của mục đăng ký trong ứng dụng \"%s\"",
"Username already exists": "Tên đăng nhập đã tồn tại",
"Username cannot be an email address": "Tên người dùng không thể là địa chỉ email",
"Username cannot contain white spaces": "Tên người dùng không thể chứa khoảng trắng",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "Tên người dùng hỗ trợ định dạng email. Ngoài ra, tên người dùng chỉ có thể chứa ký tự chữ và số, gạch dưới hoặc gạch ngang, không được có gạch ngang hoặc gạch dưới liên tiếp và không được bắt đầu hoặc kết thúc bằng gạch ngang hoặc gạch dưới. Đồng thời lưu ý định dạng email.",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "Bạn đã nhập sai mật khẩu hoặc mã quá nhiều lần, vui lòng đợi %d phút và thử lại",
"Your IP address: %s has been banned according to the configuration of: ": "Địa chỉ IP của bạn: %s đã bị cấm theo cấu hình của: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "Mật khẩu của bạn đã hết hạn. Vui lòng đặt lại mật khẩu bằng cách nhấp vào \\\"Quên mật khẩu\\\"",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "Mật khẩu của bạn đã hết hạn. Vui lòng đặt lại mật khẩu bằng cách nhấp vào \"Quên mật khẩu\"",
"Your region is not allow to signup by phone": "Vùng của bạn không được phép đăng ký bằng điện thoại",
"password or code is incorrect": "mật khẩu hoặc mã không đúng",
"password or code is incorrect, you have %s remaining chances": "Mật khẩu hoặc mã không chính xác, bạn còn %s lần cơ hội",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "Không thể nhập nhóm",
"Failed to import users": "Không thể nhập người dùng",
"Insufficient balance: new balance %v would be below credit limit %v": "Số dư không đủ: số dư mới %v sẽ thấp hơn giới hạn tín dụng %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "Số dư không đủ: số dư tổ chức mới %v sẽ thấp hơn giới hạn tín dụng %v",
"Missing parameter": "Thiếu tham số",
"Only admin user can specify user": "Chỉ người dùng quản trị mới có thể chỉ định người dùng",
"Please login first": "Vui lòng đăng nhập trước",
"The LDAP: %s does not exist": "LDAP: %s không tồn tại",
"The organization: %s should have one application at least": "Tổ chức: %s cần có ít nhất một ứng dụng",
"The syncer: %s does not exist": "Bộ đồng bộ: %s không tồn tại",
"The user: %s doesn't exist": "Người dùng: %s không tồn tại",
"The user: %s is not found": "Người dùng: %s không được tìm thấy",
"User is required for User category transaction": "Người dùng được yêu cầu cho giao dịch danh mục Người dùng",
"Wrong userId": "ID người dùng sai",
"don't support captchaProvider: ": "không hỗ trợ captchaProvider: ",
"this operation is not allowed in demo mode": "thao tác này không được phép trong chế độ demo",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "Thêm người dùng mới vào tổ chức 'built-in' (tích hợp sẵn) hiện đang bị vô hiệu hóa. Lưu ý: Tất cả người dùng trong tổ chức 'built-in' đều là quản trị viên toàn cầu trong Casdoor. Xem tài liệu: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. Nếu bạn vẫn muốn tạo người dùng cho tổ chức 'built-in', hãy truy cập trang cài đặt của tổ chức và bật tùy chọn 'Có đồng ý quyền đặc biệt'."
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "Quyền: \\\"%s\\\" không tồn tại"
"The permission: \"%s\" doesn't exist": "Quyền: \"%s\" không tồn tại"
},
"product": {
"Product list cannot be empty": "Danh sách sản phẩm không thể trống"
},
"provider": {
"Failed to initialize ID Verification provider": "Không thể khởi tạo nhà cung cấp Xác minh ID",
"Invalid application id": "Sai ID ứng dụng",
"No ID Verification provider configured": "Không có nhà cung cấp Xác minh ID được cấu hình",
"Provider is not an ID Verification provider": "Nhà cung cấp không phải là nhà cung cấp Xác minh ID",
"the provider: %s does not exist": "Nhà cung cấp: %s không tồn tại"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "Người nhận Email không hợp lệ: %s",
"Invalid phone receivers: %s": "Người nhận điện thoại không hợp lệ: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "id phiên %s là phiên hiện tại và không thể bị xóa"
},
"storage": {
"The objectKey: %s is not allowed": "Khóa đối tượng: %s không được phép",
"The provider type: %s is not supported": "Loại nhà cung cấp: %s không được hỗ trợ"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "Lỗi"
},
"ticket": {
"Ticket not found": "Không tìm thấy vé"
},
"token": {
"Grant_type: %s is not supported in this application": "Loại cấp phép: %s không được hỗ trợ trong ứng dụng này",
"Invalid application or wrong clientSecret": "Đơn đăng ký không hợp lệ hoặc sai clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "Tên hiển thị không thể trống",
"ID card information and real name are required": "Thông tin chứng minh nhân dân và tên thật là bắt buộc",
"Identity verification failed": "Xác minh danh tính thất bại",
"MFA email is enabled but email is empty": "MFA email đã bật nhưng email trống",
"MFA phone is enabled but phone number is empty": "MFA điện thoại đã bật nhưng số điện thoại trống",
"New password cannot contain blank space.": "Mật khẩu mới không thể chứa dấu trắng.",
"No application found for user": "Không tìm thấy ứng dụng cho người dùng",
"The new password must be different from your current password": "Mật khẩu mới phải khác với mật khẩu hiện tại của bạn",
"User is already verified": "Người dùng đã được xác minh",
"the user's owner and name should not be empty": "chủ sở hữu và tên người dùng không được để trống"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "Nhà cung cấp captcha không hợp lệ.",
"Phone number is invalid in your region %s": "Số điện thoại không hợp lệ trong vùng của bạn %s",
"The forgot password feature is disabled": "Tính năng quên mật khẩu đã bị tắt",
"The verification code has already been used!": "Mã xác thực đã được sử dụng!",
"The verification code has not been sent yet!": "Mã xác thực chưa được gửi!",
"Turing test failed.": "Kiểm định Turing thất bại.",
@@ -196,8 +219,8 @@
"Unknown type": "Loại không xác định",
"Wrong verification code!": "Mã xác thực sai!",
"You should verify your code in %d min!": "Bạn nên kiểm tra mã của mình trong %d phút!",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "vui lòng thêm nhà cung cấp SMS vào danh sách \\\"Providers\\\" cho ứng dụng: %s",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "vui lòng thêm nhà cung cấp Email vào danh sách \\\"Providers\\\" cho ứng dụng: %s",
"please add a SMS provider to the \"Providers\" list for the application: %s": "vui lòng thêm nhà cung cấp SMS vào danh sách \"Providers\" cho ứng dụng: %s",
"please add an Email provider to the \"Providers\" list for the application: %s": "vui lòng thêm nhà cung cấp Email vào danh sách \"Providers\" cho ứng dụng: %s",
"the user does not exist, please sign up first": "Người dùng không tồn tại, vui lòng đăng ký trước"
},
"webauthn": {

View File

@@ -2,7 +2,6 @@
"account": {
"Failed to add user": "添加用户失败",
"Get init score failed, error: %w": "初始化分数失败: %w",
"Please sign out first": "请先退出登录",
"The application does not allow to sign up new account": "该应用不允许注册新用户"
},
"auth": {
@@ -23,6 +22,7 @@
"The login method: login with email is not enabled for the application": "该应用禁止采用邮箱登录方式",
"The login method: login with face is not enabled for the application": "该应用禁止采用人脸登录",
"The login method: login with password is not enabled for the application": "该应用禁止采用密码登录方式",
"The order: %s does not exist": "订单: %s 不存在",
"The organization: %s does not exist": "组织: %s 不存在",
"The organization: %s has disabled users to signin": "组织: %s 禁止用户登录",
"The plan: %s does not exist": "计划: %s不存在",
@@ -35,7 +35,7 @@
"User's tag: %s is not listed in the application's tags": "用户的标签: %s不在该应用的标签列表中",
"UserCode Expired": "用户代码已过期",
"UserCode Invalid": "用户代码无效",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "paid-user %s 没有激活或正在等待订阅且应用: %s 没有默认",
"paid-user %s does not have active or pending subscription and the application: %s does not have default pricing": "付费用户 %s 没有激活或待处理的订阅且应用 %s 没有默认定价",
"the application for user %s is not found": "未找到用户 %s 的应用程序",
"the organization: %s is not found": "组织: %s 不存在"
},
@@ -57,11 +57,11 @@
"Face data mismatch": "人脸不匹配",
"Failed to parse client IP: %s": "无法解析客户端 IP 地址: %s",
"FirstName cannot be blank": "名不可以为空",
"Guest users must upgrade their account by setting a username and password before they can sign in directly": "访客用户必须通过设置用户名和密码来升级账户,然后才能直接登录",
"Invitation code cannot be blank": "邀请码不能为空",
"Invitation code exhausted": "邀请码使用次数已耗尽",
"Invitation code is invalid": "邀请码无效",
"Invitation code suspended": "邀请码已被禁止使用",
"LDAP user name or password incorrect": "LDAP密码错误",
"LastName cannot be blank": "姓不可以为空",
"Multiple accounts with same uid, please check your ldap server": "多个帐户具有相同的uid请检查您的 LDAP 服务器",
"Organization does not exist": "组织不存在",
@@ -83,8 +83,8 @@
"The user is forbidden to sign in, please contact the administrator": "该用户被禁止登录,请联系管理员",
"The user: %s doesn't exist in LDAP server": "用户: %s 在LDAP服务器中未找到",
"The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline.": "用户名只能包含字母数字字符、下划线或连字符,不能有连续的连字符或下划线,也不能以连字符或下划线开头或结尾",
"The value \\\"%s\\\" for account field \\\"%s\\\" doesn't match the account item regex": "值 \\\"%s\\\"在账户信息字段\\\"%s\\\" 中与应用的账户项正则表达式不匹配",
"The value \\\"%s\\\" for signup field \\\"%s\\\" doesn't match the signup item regex of the application \\\"%s\\\"": "值\\\"%s\\\"在注册字段\\\"%s\\\"中与应用\\\"%s\\\"的注册项正则表达式不匹配",
"The value \"%s\" for account field \"%s\" doesn't match the account item regex": "值 \"%s\"在账户信息字段\"%s\" 中与应用的账户项正则表达式不匹配",
"The value \"%s\" for signup field \"%s\" doesn't match the signup item regex of the application \"%s\"": "值\"%s\"在注册字段\"%s\"中与应用\"%s\"的注册项正则表达式不匹配",
"Username already exists": "用户名已存在",
"Username cannot be an email address": "用户名不可以是邮箱地址",
"Username cannot contain white spaces": "用户名禁止包含空格",
@@ -94,7 +94,7 @@
"Username supports email format. Also The username may only contain alphanumeric characters, underlines or hyphens, cannot have consecutive hyphens or underlines, and cannot begin or end with a hyphen or underline. Also pay attention to the email format.": "用户名支持电子邮件格式。此外,用户名只能包含字母数字字符、下划线或连字符,不能包含连续的连字符或下划线,也不能以连字符或下划线开头或结尾。同时请注意电子邮件格式。",
"You have entered the wrong password or code too many times, please wait for %d minutes and try again": "密码错误次数已达上限,请在 %d 分后重试",
"Your IP address: %s has been banned according to the configuration of: ": "您的IP地址%s 根据以下配置已被禁止: ",
"Your password has expired. Please reset your password by clicking \\\"Forgot password\\\"": "您的密码已过期。请点击 \\\"忘记密码\\\" 以重置密码",
"Your password has expired. Please reset your password by clicking \"Forgot password\"": "您的密码已过期。请点击 \"忘记密码\" 以重置密码",
"Your region is not allow to signup by phone": "所在地区不支持手机号注册",
"password or code is incorrect": "密码错误",
"password or code is incorrect, you have %s remaining chances": "密码错误,您还有 %s 次尝试的机会",
@@ -106,11 +106,17 @@
"general": {
"Failed to import groups": "导入群组失败",
"Failed to import users": "导入用户失败",
"Insufficient balance: new balance %v would be below credit limit %v": "余额不足:新余额 %v 将低于信用限额 %v",
"Insufficient balance: new organization balance %v would be below credit limit %v": "余额不足:新组织余额 %v 将低于信用限额 %v",
"Missing parameter": "缺少参数",
"Only admin user can specify user": "仅管理员用户可以指定用户",
"Please login first": "请先登录",
"The LDAP: %s does not exist": "LDAP: %s 不存在",
"The organization: %s should have one application at least": "组织: %s 应该拥有至少一个应用",
"The syncer: %s does not exist": "同步器: %s 不存在",
"The user: %s doesn't exist": "用户: %s不存在",
"The user: %s is not found": "用户: %s 未找到",
"User is required for User category transaction": "用户类别交易需要用户",
"Wrong userId": "错误的 userId",
"don't support captchaProvider: ": "不支持验证码提供商: ",
"this operation is not allowed in demo mode": "demo模式下不允许该操作",
@@ -137,10 +143,16 @@
"adding a new user to the 'built-in' organization is currently disabled. Please note: all users in the 'built-in' organization are global administrators in Casdoor. Refer to the docs: https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself. If you still wish to create a user for the 'built-in' organization, go to the organization's settings page and enable the 'Has privilege consent' option.": "目前,向'built-in'组织添加新用户的功能已禁用。请注意:'built-in'组织中的所有用户均为Casdoor的全局管理员。请参阅文档https://casdoor.org/docs/basic/core-concepts#how-does-casdoor-manage-itself。如果您仍希望为built-in组织创建用户请转到该组织的设置页面并启用“特权同意”选项。"
},
"permission": {
"The permission: \\\"%s\\\" doesn't exist": "权限: \\\"%s\\\" 不存在"
"The permission: \"%s\" doesn't exist": "权限: \"%s\" 不存在"
},
"product": {
"Product list cannot be empty": "产品列表不能为空"
},
"provider": {
"Failed to initialize ID Verification provider": "初始化身份验证提供商失败",
"Invalid application id": "无效的应用ID",
"No ID Verification provider configured": "未配置身份验证提供商",
"Provider is not an ID Verification provider": "提供商不是身份验证提供商",
"the provider: %s does not exist": "提供商: %s不存在"
},
"resource": {
@@ -158,6 +170,9 @@
"Invalid Email receivers: %s": "无效的邮箱收件人: %s",
"Invalid phone receivers: %s": "无效的手机短信收信人: %s"
},
"session": {
"session id %s is the current session and cannot be deleted": "会话ID %s 是当前会话,无法删除"
},
"storage": {
"The objectKey: %s is not allowed": "objectKey: %s被禁止",
"The provider type: %s is not supported": "不支持的提供商类型: %s"
@@ -165,6 +180,9 @@
"subscription": {
"Error": "错误"
},
"ticket": {
"Ticket not found": "工单未找到"
},
"token": {
"Grant_type: %s is not supported in this application": "该应用不支持Grant_type: %s",
"Invalid application or wrong clientSecret": "无效应用或错误的clientSecret",
@@ -174,10 +192,14 @@
},
"user": {
"Display name cannot be empty": "显示名称不可为空",
"ID card information and real name are required": "需要身份证信息和真实姓名",
"Identity verification failed": "身份验证失败",
"MFA email is enabled but email is empty": "MFA 电子邮件已启用,但电子邮件为空",
"MFA phone is enabled but phone number is empty": "MFA 电话已启用,但电话号码为空",
"New password cannot contain blank space.": "新密码不可以包含空格",
"No application found for user": "未找到用户的应用程序",
"The new password must be different from your current password": "新密码必须与您当前的密码不同",
"User is already verified": "用户已验证",
"the user's owner and name should not be empty": "用户的组织和名称不能为空"
},
"util": {
@@ -188,6 +210,7 @@
"verification": {
"Invalid captcha provider.": "非法的验证码提供商",
"Phone number is invalid in your region %s": "您所在地区的电话号码无效 %s",
"The forgot password feature is disabled": "忘记密码功能已被禁用",
"The verification code has already been used!": "验证码已使用过!",
"The verification code has not been sent yet!": "验证码未发送!",
"Turing test failed.": "验证码还未发送",
@@ -196,8 +219,8 @@
"Unknown type": "未知类型",
"Wrong verification code!": "验证码错误!",
"You should verify your code in %d min!": "请在 %d 分钟内输入正确验证码",
"please add a SMS provider to the \\\"Providers\\\" list for the application: %s": "请添加一个SMS提供商到应用 %s 的 \\\"提供商 \\\"列表",
"please add an Email provider to the \\\"Providers\\\" list for the application: %s": "请添加一个Email提供商到应用 %s 的 \\\"提供商 \\\"列表",
"please add a SMS provider to the \"Providers\" list for the application: %s": "请添加一个SMS提供商到应用 %s 的 \"提供商 \"列表",
"please add an Email provider to the \"Providers\" list for the application: %s": "请添加一个Email提供商到应用 %s 的 \"提供商 \"列表",
"the user does not exist, please sign up first": "用户不存在,请先注册"
},
"webauthn": {

View File

@@ -264,27 +264,31 @@ func rsaSignWithRSA256(signContent string, privateKey string) (string, error) {
// privateKey in database is a string, format it to PEM style
func formatPrivateKey(privateKey string) string {
// each line length is 64
preFmtPrivateKey := ""
for i := 0; ; {
if i+64 <= len(privateKey) {
preFmtPrivateKey = preFmtPrivateKey + privateKey[i:i+64] + "\n"
i += 64
} else {
preFmtPrivateKey = preFmtPrivateKey + privateKey[i:]
break
// Check if the key is already in PEM format
if strings.HasPrefix(privateKey, "-----BEGIN PRIVATE KEY-----") ||
strings.HasPrefix(privateKey, "-----BEGIN RSA PRIVATE KEY-----") {
// Key is already in PEM format, return as is
return privateKey
}
// Remove any whitespace from the key
privateKey = strings.ReplaceAll(privateKey, "\n", "")
privateKey = strings.ReplaceAll(privateKey, "\r", "")
privateKey = strings.ReplaceAll(privateKey, " ", "")
// Format the key with line breaks every 64 characters using strings.Builder
var builder strings.Builder
for i := 0; i < len(privateKey); i += 64 {
end := i + 64
if end > len(privateKey) {
end = len(privateKey)
}
builder.WriteString(privateKey[i:end])
if end < len(privateKey) {
builder.WriteString("\n")
}
}
privateKey = strings.Trim(preFmtPrivateKey, "\n")
// add pkcs#8 BEGIN and END
PemBegin := "-----BEGIN PRIVATE KEY-----\n"
PemEnd := "\n-----END PRIVATE KEY-----"
if !strings.HasPrefix(privateKey, PemBegin) {
privateKey = PemBegin + privateKey
}
if !strings.HasSuffix(privateKey, PemEnd) {
privateKey = privateKey + PemEnd
}
return privateKey
return "-----BEGIN PRIVATE KEY-----\n" + builder.String() + "\n-----END PRIVATE KEY-----"
}

View File

@@ -31,11 +31,12 @@ type CustomIdProvider struct {
Client *http.Client
Config *oauth2.Config
UserInfoURL string
TokenURL string
AuthURL string
UserMapping map[string]string
Scopes []string
UserInfoURL string
TokenURL string
AuthURL string
UserMapping map[string]string
Scopes []string
CodeVerifier string
}
func NewCustomIdProvider(idpInfo *ProviderInfo, redirectUrl string) *CustomIdProvider {
@@ -53,6 +54,7 @@ func NewCustomIdProvider(idpInfo *ProviderInfo, redirectUrl string) *CustomIdPro
idp.UserInfoURL = idpInfo.UserInfoURL
idp.UserMapping = idpInfo.UserMapping
idp.CodeVerifier = idpInfo.CodeVerifier
return idp
}
@@ -62,7 +64,11 @@ func (idp *CustomIdProvider) SetHttpClient(client *http.Client) {
func (idp *CustomIdProvider) GetToken(code string) (*oauth2.Token, error) {
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, idp.Client)
return idp.Config.Exchange(ctx, code)
var oauth2Opts []oauth2.AuthCodeOption
if idp.CodeVerifier != "" {
oauth2Opts = append(oauth2Opts, oauth2.VerifierOption(idp.CodeVerifier))
}
return idp.Config.Exchange(ctx, code, oauth2Opts...)
}
func getNestedValue(data map[string]interface{}, path string) (interface{}, error) {

View File

@@ -87,8 +87,9 @@ import (
)
type GothIdProvider struct {
Provider goth.Provider
Session goth.Session
Provider goth.Provider
Session goth.Session
CodeVerifier string
}
func NewGothIdProvider(providerType string, clientId string, clientSecret string, clientId2 string, clientSecret2 string, redirectUrl string, hostUrl string) (*GothIdProvider, error) {
@@ -448,7 +449,13 @@ func (idp *GothIdProvider) GetToken(code string) (*oauth2.Token, error) {
value = url.Values{}
value.Add("code", code)
if idp.Provider.Name() == "twitterv2" || idp.Provider.Name() == "fitbit" {
value.Add("oauth_verifier", "casdoor-verifier")
// Use dynamic code verifier if provided, otherwise fall back to static one
verifier := idp.CodeVerifier
if verifier == "" {
verifier = "casdoor-verifier"
}
// RFC 7636 PKCE uses 'code_verifier' parameter
value.Add("code_verifier", verifier)
}
}
accessToken, err := idp.Session.Authorize(idp.Provider, value)

View File

@@ -45,6 +45,7 @@ type ProviderInfo struct {
HostUrl string
RedirectUrl string
DisableSsl bool
CodeVerifier string
TokenURL string
AuthURL string
@@ -128,7 +129,9 @@ func GetIdProvider(idpInfo *ProviderInfo, redirectUrl string) (IdProvider, error
case "Web3Onboard":
return NewWeb3OnboardIdProvider(), nil
case "Twitter":
return NewTwitterIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl), nil
provider := NewTwitterIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl)
provider.CodeVerifier = idpInfo.CodeVerifier
return provider, nil
case "Telegram":
return NewTelegramIdProvider(idpInfo.ClientId, idpInfo.ClientSecret, redirectUrl), nil
default:

View File

@@ -28,8 +28,9 @@ import (
)
type TwitterIdProvider struct {
Client *http.Client
Config *oauth2.Config
Client *http.Client
Config *oauth2.Config
CodeVerifier string
}
func NewTwitterIdProvider(clientId string, clientSecret string, redirectUrl string) *TwitterIdProvider {
@@ -84,7 +85,12 @@ func (idp *TwitterIdProvider) GetToken(code string) (*oauth2.Token, error) {
params := url.Values{}
// params.Add("client_id", idp.Config.ClientID)
params.Add("redirect_uri", idp.Config.RedirectURL)
params.Add("code_verifier", "casdoor-verifier")
// Use dynamic code verifier if provided, otherwise fall back to static one
verifier := idp.CodeVerifier
if verifier == "" {
verifier = "casdoor-verifier"
}
params.Add("code_verifier", verifier)
params.Add("code", code)
params.Add("grant_type", "authorization_code")
req, err := http.NewRequest("POST", "https://api.twitter.com/2/oauth2/token", strings.NewReader(params.Encode()))

View File

@@ -67,6 +67,8 @@
{"name": "ID", "visible": true, "viewRule": "Public", "modifyRule": "Immutable"},
{"name": "Name", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Display name", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "First name", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Last name", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Avatar", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "User type", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Password", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
@@ -75,18 +77,34 @@
{"name": "Country code", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Country/Region", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Location", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Address", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Addresses", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Affiliation", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Title", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "ID card type", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "ID card", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "ID card info", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Real name", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "ID verification", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Homepage", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Bio", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Tag", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Language", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Gender", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Birthday", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Education", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Balance", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Balance credit", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Balance currency", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Cart", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Transactions", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Score", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Karma", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Ranking", "visible": true, "viewRule": "Public", "modifyRule": "Self"},
{"name": "Signup application", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Register type", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "Register source", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
{"name": "API key", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Roles", "visible": true, "viewRule": "Public", "modifyRule": "Immutable"},
{"name": "Permissions", "visible": true, "viewRule": "Public", "modifyRule": "Immutable"},
{"name": "Groups", "visible": true, "viewRule": "Public", "modifyRule": "Admin"},
@@ -96,9 +114,14 @@
{"name": "Is forbidden", "visible": true, "viewRule": "Admin", "modifyRule": "Admin"},
{"name": "Is deleted", "visible": true, "viewRule": "Admin", "modifyRule": "Admin"},
{"name": "Multi-factor authentication", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "MFA items", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "WebAuthn credentials", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Last change password time", "visible": true, "viewRule": "Admin", "modifyRule": "Admin"},
{"name": "Managed accounts", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "MFA accounts", "visible": true, "viewRule": "Self", "modifyRule": "Self"}
{"name": "Face ID", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "MFA accounts", "visible": true, "viewRule": "Self", "modifyRule": "Self"},
{"name": "Need update password", "visible": true, "viewRule": "Admin", "modifyRule": "Admin"},
{"name": "IP whitelist", "visible": true, "viewRule": "Admin", "modifyRule": "Admin"}
]
}
],
@@ -236,6 +259,7 @@
"phone": "",
"countryCode": "",
"address": [],
"addresses": [],
"affiliation": "",
"tag": "",
"score": 2000,

View File

@@ -216,6 +216,16 @@ func handleSearch(w ldap.ResponseWriter, m *ldap.Message) {
e.AddAttribute("mobile", message.AttributeValue(user.Phone))
e.AddAttribute("sn", message.AttributeValue(user.LastName))
e.AddAttribute("givenName", message.AttributeValue(user.FirstName))
// Add POSIX attributes for Linux machine login support
e.AddAttribute("loginShell", getAttribute("loginShell", user))
e.AddAttribute("gecos", getAttribute("gecos", user))
// Add SSH public key if available
sshKey := getAttribute("sshPublicKey", user)
if sshKey != "" {
e.AddAttribute("sshPublicKey", sshKey)
}
// Add objectClass for posixAccount
e.AddAttribute("objectClass", "posixAccount")
for _, group := range user.Groups {
e.AddAttribute(ldapMemberOfAttr, message.AttributeValue(group))
}

View File

@@ -83,6 +83,45 @@ var ldapAttributesMapping = map[string]FieldRelation{
return message.AttributeValue(getUserPasswordWithType(user))
},
},
"loginShell": {
userField: "loginShell",
notSearchable: true,
fieldMapper: func(user *object.User) message.AttributeValue {
// Check user properties first, otherwise return default shell
if user.Properties != nil {
if shell, ok := user.Properties["loginShell"]; ok && shell != "" {
return message.AttributeValue(shell)
}
}
return message.AttributeValue("/bin/bash")
},
},
"gecos": {
userField: "gecos",
notSearchable: true,
fieldMapper: func(user *object.User) message.AttributeValue {
// GECOS field typically contains full name and other user info
// Format: Full Name,Room Number,Work Phone,Home Phone,Other
gecos := user.DisplayName
if gecos == "" {
gecos = user.Name
}
return message.AttributeValue(gecos)
},
},
"sshPublicKey": {
userField: "sshPublicKey",
notSearchable: true,
fieldMapper: func(user *object.User) message.AttributeValue {
// Return SSH public key from user properties
if user.Properties != nil {
if sshKey, ok := user.Properties["sshPublicKey"]; ok && sshKey != "" {
return message.AttributeValue(sshKey)
}
}
return message.AttributeValue("")
},
},
}
const ldapMemberOfAttr = "memberOf"

View File

@@ -15,6 +15,7 @@
package mcp
import (
"strings"
"time"
"github.com/casdoor/casdoor/object"
@@ -120,3 +121,58 @@ func (c *McpController) GetAcceptLanguage() string {
}
return language
}
// GetTokenFromRequest extracts the Bearer token from the Authorization header
func (c *McpController) GetTokenFromRequest() string {
authHeader := c.Ctx.Request.Header.Get("Authorization")
if authHeader == "" {
return ""
}
// Extract Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return ""
}
return parts[1]
}
// GetClaimsFromToken parses and validates the JWT token and returns the claims
// Returns nil if no token is present or if token is invalid
func (c *McpController) GetClaimsFromToken() *object.Claims {
tokenString := c.GetTokenFromRequest()
if tokenString == "" {
return nil
}
// Try to find the application for this token
// For MCP, we'll try to parse using the first available application's certificate
// In a production scenario, you might want to use a specific MCP application
token, err := object.GetTokenByAccessToken(tokenString)
if err != nil || token == nil {
return nil
}
application, err := object.GetApplication(token.Application)
if err != nil || application == nil {
return nil
}
claims, err := object.ParseJwtTokenByApplication(tokenString, application)
if err != nil {
return nil
}
return claims
}
// GetScopesFromClaims extracts the scopes from JWT claims and returns them as a slice
func GetScopesFromClaims(claims *object.Claims) []string {
if claims == nil || claims.Scope == "" {
return []string{}
}
// Scopes are space-separated in OAuth 2.0
return strings.Split(claims.Scope, " ")
}

View File

@@ -268,7 +268,160 @@ func (c *McpController) handlePing(req McpRequest) {
}
func (c *McpController) handleToolsList(req McpRequest) {
tools := []McpTool{
allTools := c.getAllTools()
// Get JWT claims from the request
claims := c.GetClaimsFromToken()
// If no token is present, check session authentication
if claims == nil {
username := c.GetSessionUsername()
// If user is authenticated via session, return all tools (backward compatibility)
if username != "" {
result := McpListToolsResult{
Tools: allTools,
}
c.McpResponseOk(req.ID, result)
return
}
// Unauthenticated request - return all tools for discovery
// This allows clients to see what tools are available before authenticating
result := McpListToolsResult{
Tools: allTools,
}
c.McpResponseOk(req.ID, result)
return
}
// Token-based authentication - filter tools by scopes
grantedScopes := GetScopesFromClaims(claims)
allowedTools := GetToolsForScopes(grantedScopes, BuiltinScopes)
// Filter tools based on allowed scopes
var filteredTools []McpTool
for _, tool := range allTools {
if allowedTools[tool.Name] {
filteredTools = append(filteredTools, tool)
}
}
result := McpListToolsResult{
Tools: filteredTools,
}
c.McpResponseOk(req.ID, result)
}
func (c *McpController) handleToolsCall(req McpRequest) {
var params McpCallToolParams
err := json.Unmarshal(req.Params, &params)
if err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
// Check scope-tool permission
if !c.checkToolPermission(req.ID, params.Name) {
return // Error already sent by checkToolPermission
}
// Route to the appropriate tool handler
switch params.Name {
case "get_applications":
var args GetApplicationsArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleGetApplicationsTool(req.ID, args)
case "get_application":
var args GetApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleGetApplicationTool(req.ID, args)
case "add_application":
var args AddApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleAddApplicationTool(req.ID, args)
case "update_application":
var args UpdateApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleUpdateApplicationTool(req.ID, args)
case "delete_application":
var args DeleteApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleDeleteApplicationTool(req.ID, args)
default:
c.McpResponseError(req.ID, -32602, "Invalid tool name", fmt.Sprintf("Tool '%s' not found", params.Name))
}
}
// checkToolPermission validates that the current token has the required scope for the tool
// Returns false and sends an error response if permission is denied
func (c *McpController) checkToolPermission(id interface{}, toolName string) bool {
// Get JWT claims from the request
claims := c.GetClaimsFromToken()
// If no token is present, check if the user is authenticated via session
if claims == nil {
username := c.GetSessionUsername()
// If user is authenticated via session (e.g., session cookie), allow access
// This maintains backward compatibility with existing session-based auth
if username != "" {
return true
}
// No authentication present - deny access
c.sendInsufficientScopeError(id, toolName, []string{})
return false
}
// Extract scopes from claims
grantedScopes := GetScopesFromClaims(claims)
// Get allowed tools for the granted scopes
allowedTools := GetToolsForScopes(grantedScopes, BuiltinScopes)
// Check if the requested tool is allowed
if !allowedTools[toolName] {
c.sendInsufficientScopeError(id, toolName, grantedScopes)
return false
}
return true
}
// sendInsufficientScopeError sends an error response for insufficient scope
func (c *McpController) sendInsufficientScopeError(id interface{}, toolName string, grantedScopes []string) {
// Find required scope for this tool
requiredScope := GetRequiredScopeForTool(toolName, BuiltinScopes)
errorData := map[string]interface{}{
"tool": toolName,
"granted_scopes": grantedScopes,
}
if requiredScope != "" {
errorData["required_scope"] = requiredScope
}
c.McpResponseError(id, -32001, "insufficient_scope", errorData)
}
// getAllTools returns all available MCP tools
func (c *McpController) getAllTools() []McpTool {
return []McpTool{
{
Name: "get_applications",
Description: "Get all applications for a specific owner",
@@ -344,60 +497,4 @@ func (c *McpController) handleToolsList(req McpRequest) {
},
},
}
result := McpListToolsResult{
Tools: tools,
}
c.McpResponseOk(req.ID, result)
}
func (c *McpController) handleToolsCall(req McpRequest) {
var params McpCallToolParams
err := json.Unmarshal(req.Params, &params)
if err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
// Route to the appropriate tool handler
switch params.Name {
case "get_applications":
var args GetApplicationsArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleGetApplicationsTool(req.ID, args)
case "get_application":
var args GetApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleGetApplicationTool(req.ID, args)
case "add_application":
var args AddApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleAddApplicationTool(req.ID, args)
case "update_application":
var args UpdateApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleUpdateApplicationTool(req.ID, args)
case "delete_application":
var args DeleteApplicationArgs
if err := json.Unmarshal(params.Arguments, &args); err != nil {
c.sendInvalidParamsError(req.ID, err.Error())
return
}
c.handleDeleteApplicationTool(req.ID, args)
default:
c.McpResponseError(req.ID, -32602, "Invalid tool name", fmt.Sprintf("Tool '%s' not found", params.Name))
}
}

158
mcp/permission.go Normal file
View File

@@ -0,0 +1,158 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package mcp
import (
"github.com/casdoor/casdoor/object"
)
// BuiltinScopes defines the default scope-to-tool mappings for Casdoor's MCP server
var BuiltinScopes = []*object.ScopeItem{
{
Name: "application:read",
DisplayName: "Read Applications",
Description: "View application list and details",
Tools: []string{"get_applications", "get_application"},
},
{
Name: "application:write",
DisplayName: "Manage Applications",
Description: "Create, update, and delete applications",
Tools: []string{"add_application", "update_application", "delete_application"},
},
{
Name: "user:read",
DisplayName: "Read Users",
Description: "View user list and details",
Tools: []string{"get_users", "get_user"},
},
{
Name: "user:write",
DisplayName: "Manage Users",
Description: "Create, update, and delete users",
Tools: []string{"add_user", "update_user", "delete_user"},
},
{
Name: "organization:read",
DisplayName: "Read Organizations",
Description: "View organization list and details",
Tools: []string{"get_organizations", "get_organization"},
},
{
Name: "organization:write",
DisplayName: "Manage Organizations",
Description: "Create, update, and delete organizations",
Tools: []string{"add_organization", "update_organization", "delete_organization"},
},
{
Name: "permission:read",
DisplayName: "Read Permissions",
Description: "View permission list and details",
Tools: []string{"get_permissions", "get_permission"},
},
{
Name: "permission:write",
DisplayName: "Manage Permissions",
Description: "Create, update, and delete permissions",
Tools: []string{"add_permission", "update_permission", "delete_permission"},
},
{
Name: "role:read",
DisplayName: "Read Roles",
Description: "View role list and details",
Tools: []string{"get_roles", "get_role"},
},
{
Name: "role:write",
DisplayName: "Manage Roles",
Description: "Create, update, and delete roles",
Tools: []string{"add_role", "update_role", "delete_role"},
},
{
Name: "provider:read",
DisplayName: "Read Providers",
Description: "View provider list and details",
Tools: []string{"get_providers", "get_provider"},
},
{
Name: "provider:write",
DisplayName: "Manage Providers",
Description: "Create, update, and delete providers",
Tools: []string{"add_provider", "update_provider", "delete_provider"},
},
{
Name: "token:read",
DisplayName: "Read Tokens",
Description: "View token list and details",
Tools: []string{"get_tokens", "get_token"},
},
{
Name: "token:write",
DisplayName: "Manage Tokens",
Description: "Delete tokens",
Tools: []string{"delete_token"},
},
}
// ConvenienceScopes defines alias scopes that expand to multiple resource scopes
var ConvenienceScopes = map[string][]string{
"read": {"application:read", "user:read", "organization:read", "permission:read", "role:read", "provider:read", "token:read"},
"write": {"application:write", "user:write", "organization:write", "permission:write", "role:write", "provider:write", "token:write"},
"admin": {"application:read", "application:write", "user:read", "user:write", "organization:read", "organization:write", "permission:read", "permission:write", "role:read", "role:write", "provider:read", "provider:write", "token:read", "token:write"},
}
// GetToolsForScopes returns a map of tools allowed by the given scopes
// The grantedScopes are the scopes present in the token
// The registry contains the scope-to-tool mappings (either BuiltinScopes or Application.Scopes)
func GetToolsForScopes(grantedScopes []string, registry []*object.ScopeItem) map[string]bool {
allowed := make(map[string]bool)
// Expand convenience scopes first
expandedScopes := make([]string, 0)
for _, scopeName := range grantedScopes {
if expansion, isConvenience := ConvenienceScopes[scopeName]; isConvenience {
expandedScopes = append(expandedScopes, expansion...)
} else {
expandedScopes = append(expandedScopes, scopeName)
}
}
// Map scopes to tools
for _, scopeName := range expandedScopes {
for _, item := range registry {
if item.Name == scopeName {
for _, tool := range item.Tools {
allowed[tool] = true
}
break
}
}
}
return allowed
}
// GetRequiredScopeForTool returns the first scope that provides access to the given tool
// Returns an empty string if no scope is found for the tool
func GetRequiredScopeForTool(toolName string, registry []*object.ScopeItem) string {
for _, scopeItem := range registry {
for _, tool := range scopeItem.Tools {
if tool == toolName {
return scopeItem.Name
}
}
}
return ""
}

View File

@@ -61,9 +61,17 @@ type SamlItem struct {
}
type JwtItem struct {
Name string `json:"name"`
Value string `json:"value"`
Type string `json:"type"`
Name string `json:"name"`
Category string `json:"category"`
Value string `json:"value"`
Type string `json:"type"`
}
type ScopeItem struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
Tools []string `json:"tools"` // MCP tools allowed by this scope
}
type Application struct {
@@ -72,6 +80,9 @@ type Application struct {
CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
DisplayName string `xorm:"varchar(100)" json:"displayName"`
Category string `xorm:"varchar(20)" json:"category"`
Type string `xorm:"varchar(20)" json:"type"`
Scopes []*ScopeItem `xorm:"mediumtext" json:"scopes"`
Logo string `xorm:"varchar(200)" json:"logo"`
Title string `xorm:"varchar(100)" json:"title"`
Favicon string `xorm:"varchar(200)" json:"favicon"`
@@ -143,6 +154,13 @@ type Application struct {
FailedSigninLimit int `json:"failedSigninLimit"`
FailedSigninFrozenTime int `json:"failedSigninFrozenTime"`
CodeResendTimeout int `json:"codeResendTimeout"`
// Reverse proxy fields
Domain string `xorm:"varchar(100)" json:"domain"`
OtherDomains []string `xorm:"varchar(1000)" json:"otherDomains"`
UpstreamHost string `xorm:"varchar(100)" json:"upstreamHost"`
SslMode string `xorm:"varchar(100)" json:"sslMode"`
SslCert string `xorm:"varchar(100)" json:"sslCert"`
}
func GetApplicationCount(owner, field, value string) (int64, error) {
@@ -669,6 +687,21 @@ func GetAllowedApplications(applications []*Application, userId string, lang str
return res, nil
}
func checkMultipleCaptchaProviders(application *Application, lang string) error {
var captchaProviders []string
for _, providerItem := range application.Providers {
if providerItem.Provider != nil && providerItem.Provider.Category == "Captcha" {
captchaProviders = append(captchaProviders, providerItem.Name)
}
}
if len(captchaProviders) > 1 {
return fmt.Errorf(i18n.Translate(lang, "general:Multiple captcha providers are not allowed in the same application: %s"), strings.Join(captchaProviders, ", "))
}
return nil
}
func UpdateApplication(id string, application *Application, isGlobalAdmin bool, lang string) (bool, error) {
owner, name, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
@@ -707,6 +740,11 @@ func UpdateApplication(id string, application *Application, isGlobalAdmin bool,
return false, fmt.Errorf("only applications belonging to built-in organization can be shared")
}
err = checkMultipleCaptchaProviders(application, lang)
if err != nil {
return false, err
}
for _, providerItem := range application.Providers {
providerItem.Provider = nil
}

View File

@@ -20,7 +20,8 @@ import "github.com/casdoor/casdoor/email"
// TestSmtpServer Test the SMTP server
func TestSmtpServer(provider *Provider) error {
smtpEmailProvider := email.NewSmtpEmailProvider(provider.ClientId, provider.ClientSecret, provider.Host, provider.Port, provider.Type, provider.DisableSsl, provider.EnableProxy)
sslMode := getSslMode(provider)
smtpEmailProvider := email.NewSmtpEmailProvider(provider.ClientId, provider.ClientSecret, provider.Host, provider.Port, provider.Type, sslMode, provider.EnableProxy)
sender, err := smtpEmailProvider.Dialer.Dial()
if err != nil {
return err
@@ -31,7 +32,8 @@ func TestSmtpServer(provider *Provider) error {
}
func SendEmail(provider *Provider, title string, content string, dest []string, sender string) error {
emailProvider := email.GetEmailProvider(provider.Type, provider.ClientId, provider.ClientSecret, provider.Host, provider.Port, provider.DisableSsl, provider.Endpoint, provider.Method, provider.HttpHeaders, provider.UserMapping, provider.IssuerUrl, provider.EnableProxy)
sslMode := getSslMode(provider)
emailProvider := email.GetEmailProvider(provider.Type, provider.ClientId, provider.ClientSecret, provider.Host, provider.Port, sslMode, provider.Endpoint, provider.Method, provider.HttpHeaders, provider.UserMapping, provider.IssuerUrl, provider.EnableProxy)
fromAddress := provider.ClientId2
if fromAddress == "" {
@@ -45,3 +47,19 @@ func SendEmail(provider *Provider, title string, content string, dest []string,
return emailProvider.Send(fromAddress, fromName, dest, title, content)
}
// getSslMode returns the SSL mode for the provider, with backward compatibility for DisableSsl
func getSslMode(provider *Provider) string {
// If SslMode is set, use it
if provider.SslMode != "" {
return provider.SslMode
}
// Backward compatibility: convert DisableSsl to SslMode
if provider.DisableSsl {
return "Disable"
}
// Default to "Auto" for new configurations or when DisableSsl is false
return "Auto"
}

View File

@@ -15,6 +15,7 @@
package object
import (
"fmt"
"sync"
"time"
@@ -49,7 +50,12 @@ func GetDashboard(owner string) (*map[string][]int64, error) {
dashboard[tableName+"Counts"] = make([]int64, 31)
tableFullName := tableNamePrefix + tableName
go func(ch chan error) {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
ch <- fmt.Errorf("panic in dashboard goroutine: %v", r)
}
wg.Done()
}()
dashboardDateItems := []DashboardDateItem{}
var countResult int64

View File

@@ -53,6 +53,8 @@ func getBuiltInAccountItems() []*AccountItem {
{Name: "ID", Visible: true, ViewRule: "Public", ModifyRule: "Immutable"},
{Name: "Name", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Display name", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "First name", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Last name", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Avatar", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "User type", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Password", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
@@ -61,18 +63,34 @@ func getBuiltInAccountItems() []*AccountItem {
{Name: "Country code", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Country/Region", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Location", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Address", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Addresses", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Affiliation", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Title", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "ID card type", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "ID card", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "ID card info", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Real name", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "ID verification", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Homepage", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Bio", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Tag", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Language", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Gender", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Birthday", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Education", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Balance", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Balance credit", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Balance currency", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Cart", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Transactions", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Score", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Karma", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Ranking", Visible: true, ViewRule: "Public", ModifyRule: "Self"},
{Name: "Signup application", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Register type", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "Register source", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
{Name: "API key", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Roles", Visible: true, ViewRule: "Public", ModifyRule: "Immutable"},
{Name: "Permissions", Visible: true, ViewRule: "Public", ModifyRule: "Immutable"},
{Name: "Groups", Visible: true, ViewRule: "Public", ModifyRule: "Admin"},
@@ -82,9 +100,14 @@ func getBuiltInAccountItems() []*AccountItem {
{Name: "Is forbidden", Visible: true, ViewRule: "Admin", ModifyRule: "Admin"},
{Name: "Is deleted", Visible: true, ViewRule: "Admin", ModifyRule: "Admin"},
{Name: "Multi-factor authentication", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "MFA items", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "WebAuthn credentials", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Last change password time", Visible: true, ViewRule: "Admin", ModifyRule: "Admin"},
{Name: "Managed accounts", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Face ID", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "MFA accounts", Visible: true, ViewRule: "Self", ModifyRule: "Self"},
{Name: "Need update password", Visible: true, ViewRule: "Admin", ModifyRule: "Admin"},
{Name: "IP whitelist", Visible: true, ViewRule: "Admin", ModifyRule: "Admin"},
}
}
@@ -118,6 +141,7 @@ func initBuiltInOrganization() bool {
IsProfilePublic: false,
UseEmailAsUsername: false,
EnableTour: true,
DcrPolicy: "open",
}
_, err = AddOrganization(organization)
if err != nil {
@@ -183,6 +207,9 @@ func initBuiltInApplication() {
Name: "app-built-in",
CreatedTime: util.GetCurrentTime(),
DisplayName: "Casdoor",
Category: "Default",
Type: "All",
Scopes: []*ScopeItem{},
Logo: fmt.Sprintf("%s/img/casdoor-logo_1185x256.png", conf.GetConfigString("staticBaseUrl")),
HomepageUrl: "https://casdoor.org",
Organization: "built-in",

View File

@@ -37,8 +37,9 @@ type Ldap struct {
PasswordType string `xorm:"varchar(100)" json:"passwordType"`
CustomAttributes map[string]string `json:"customAttributes"`
AutoSync int `json:"autoSync"`
LastSync string `xorm:"varchar(100)" json:"lastSync"`
AutoSync int `json:"autoSync"`
LastSync string `xorm:"varchar(100)" json:"lastSync"`
EnableGroups bool `xorm:"bool" json:"enableGroups"`
}
func AddLdap(ldap *Ldap) (bool, error) {
@@ -152,7 +153,7 @@ func UpdateLdap(ldap *Ldap) (bool, error) {
}
affected, err := ormer.Engine.ID(ldap.Id).Cols("owner", "server_name", "host",
"port", "enable_ssl", "username", "password", "base_dn", "filter", "filter_fields", "auto_sync", "default_group", "password_type", "allow_self_signed_cert", "custom_attributes").Update(ldap)
"port", "enable_ssl", "username", "password", "base_dn", "filter", "filter_fields", "auto_sync", "default_group", "password_type", "allow_self_signed_cert", "custom_attributes", "enable_groups").Update(ldap)
if err != nil {
return false, nil
}

View File

@@ -91,13 +91,28 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) e
return err
}
// fetch all users
// fetch all users and groups
conn, err := ldap.GetLdapConn()
if err != nil {
logs.Warning(fmt.Sprintf("autoSync failed for %s, error %s", ldap.Id, err))
continue
}
// Sync groups first if enabled (so they exist before assigning users)
if ldap.EnableGroups {
groups, err := conn.GetLdapGroups(ldap)
if err != nil {
logs.Warning(fmt.Sprintf("autoSync failed to fetch groups for %s, error %s", ldap.Id, err))
} else {
newGroups, updatedGroups, err := SyncLdapGroups(ldap.Owner, groups, ldap.Id)
if err != nil {
logs.Warning(fmt.Sprintf("autoSync failed to sync groups for %s, error %s", ldap.Id, err))
} else {
logs.Info(fmt.Sprintf("ldap group sync success for %s, %d new groups, %d updated groups", ldap.Id, newGroups, updatedGroups))
}
}
}
users, err := conn.GetLdapUsers(ldap)
if err != nil {
conn.Close()

View File

@@ -26,10 +26,35 @@ import (
"github.com/casdoor/casdoor/i18n"
"github.com/casdoor/casdoor/util"
goldap "github.com/go-ldap/ldap/v3"
"github.com/nyaruka/phonenumbers"
"github.com/thanhpk/randstr"
"golang.org/x/text/encoding/unicode"
)
// formatUserPhone processes phone number for a user based on their CountryCode
func formatUserPhone(u *User) {
if u.Phone == "" {
return
}
// 1. Normalize hint (e.g., "China" -> "CN") for the parser
countryHint := u.CountryCode
if strings.EqualFold(countryHint, "China") {
countryHint = "CN"
}
if len(countryHint) != 2 {
countryHint = "" // Only 2-letter codes are valid hints
}
// 2. Try parsing (Strictly using countryHint from LDAP)
num, err := phonenumbers.Parse(u.Phone, countryHint)
if err == nil && num != nil && phonenumbers.IsValidNumber(num) {
// Store a clean national number (digits only, without country prefix)
u.Phone = fmt.Sprint(num.GetNationalNumber())
}
}
type LdapConn struct {
Conn *goldap.Conn
IsAD bool
@@ -62,10 +87,19 @@ type LdapUser struct {
GroupId string `json:"groupId"`
Address string `json:"address"`
MemberOf string `json:"memberOf"`
MemberOf []string `json:"memberOf"`
Attributes map[string]string `json:"attributes"`
}
type LdapGroup struct {
Dn string `json:"dn"`
Cn string `json:"cn"`
Name string `json:"name"`
Description string `json:"description"`
Member []string `json:"member"`
ParentDn string `json:"parentDn"`
}
func (ldap *Ldap) GetLdapConn() (c *LdapConn, err error) {
var conn *goldap.Conn
tlsConfig := tls.Config{
@@ -154,7 +188,7 @@ func (l *LdapConn) GetLdapUsers(ldapServer *Ldap) ([]LdapUser, error) {
SearchAttributes := []string{
"uidNumber", "cn", "sn", "gidNumber", "entryUUID", "displayName", "mail", "email",
"emailAddress", "telephoneNumber", "mobile", "mobileTelephoneNumber", "registeredAddress", "postalAddress",
"c", "co",
"c", "co", "memberOf",
}
if l.IsAD {
SearchAttributes = append(SearchAttributes, "sAMAccountName")
@@ -222,7 +256,7 @@ func (l *LdapConn) GetLdapUsers(ldapServer *Ldap) ([]LdapUser, error) {
case "co":
user.CountryName = attribute.Values[0]
case "memberOf":
user.MemberOf = attribute.Values[0]
user.MemberOf = attribute.Values
default:
if propName, ok := ldapServer.CustomAttributes[attribute.Name]; ok {
if user.Attributes == nil {
@@ -238,42 +272,135 @@ func (l *LdapConn) GetLdapUsers(ldapServer *Ldap) ([]LdapUser, error) {
return ldapUsers, nil
}
// FIXME: The Base DN does not necessarily contain the Group
//
// func (l *ldapConn) GetLdapGroups(baseDn string) (map[string]ldapGroup, error) {
// SearchFilter := "(objectClass=posixGroup)"
// SearchAttributes := []string{"cn", "gidNumber"}
// groupMap := make(map[string]ldapGroup)
//
// searchReq := goldap.NewSearchRequest(baseDn,
// goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false,
// SearchFilter, SearchAttributes, nil)
// searchResult, err := l.Conn.Search(searchReq)
// if err != nil {
// return nil, err
// }
//
// if len(searchResult.Entries) == 0 {
// return nil, errors.New("no result")
// }
//
// for _, entry := range searchResult.Entries {
// var ldapGroupItem ldapGroup
// for _, attribute := range entry.Attributes {
// switch attribute.Name {
// case "gidNumber":
// ldapGroupItem.GidNumber = attribute.Values[0]
// break
// case "cn":
// ldapGroupItem.Cn = attribute.Values[0]
// break
// }
// }
// groupMap[ldapGroupItem.GidNumber] = ldapGroupItem
// }
//
// return groupMap, nil
// }
// GetLdapGroups fetches LDAP groups and organizational units
func (l *LdapConn) GetLdapGroups(ldapServer *Ldap) ([]LdapGroup, error) {
var allGroups []LdapGroup
// Search for LDAP groups (groupOfNames, groupOfUniqueNames, posixGroup)
groupFilters := []string{
"(objectClass=groupOfNames)",
"(objectClass=groupOfUniqueNames)",
"(objectClass=posixGroup)",
}
// Add Active Directory group filter
if l.IsAD {
groupFilters = append(groupFilters, "(objectClass=group)")
}
// Build combined filter
var filterBuilder strings.Builder
filterBuilder.WriteString("(|")
for _, filter := range groupFilters {
filterBuilder.WriteString(filter)
}
filterBuilder.WriteString(")")
SearchAttributes := []string{"cn", "name", "description", "member", "uniqueMember", "memberUid"}
searchReq := goldap.NewSearchRequest(ldapServer.BaseDn,
goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false,
filterBuilder.String(), SearchAttributes, nil)
searchResult, err := l.Conn.SearchWithPaging(searchReq, 100)
if err != nil {
// Groups might not exist, which is okay
return allGroups, nil
}
for _, entry := range searchResult.Entries {
group := LdapGroup{
Dn: entry.DN,
}
for _, attribute := range entry.Attributes {
switch attribute.Name {
case "cn":
group.Cn = attribute.Values[0]
case "name":
group.Name = attribute.Values[0]
case "description":
if len(attribute.Values) > 0 {
group.Description = attribute.Values[0]
}
case "member", "uniqueMember", "memberUid":
group.Member = append(group.Member, attribute.Values...)
}
}
// Use cn as name if name is not set
if group.Name == "" {
group.Name = group.Cn
}
// Parse parent DN from the entry DN
group.ParentDn = getParentDn(entry.DN)
allGroups = append(allGroups, group)
}
// Also fetch organizational units as groups
ouFilter := "(objectClass=organizationalUnit)"
ouSearchReq := goldap.NewSearchRequest(ldapServer.BaseDn,
goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false,
ouFilter, []string{"ou", "description"}, nil)
ouSearchResult, err := l.Conn.SearchWithPaging(ouSearchReq, 100)
if err == nil {
for _, entry := range ouSearchResult.Entries {
ou := LdapGroup{
Dn: entry.DN,
}
for _, attribute := range entry.Attributes {
switch attribute.Name {
case "ou":
ou.Name = attribute.Values[0]
ou.Cn = attribute.Values[0]
case "description":
if len(attribute.Values) > 0 {
ou.Description = attribute.Values[0]
}
}
}
// Parse parent DN from the entry DN
ou.ParentDn = getParentDn(entry.DN)
allGroups = append(allGroups, ou)
}
}
return allGroups, nil
}
// getParentDn extracts the parent DN from a full DN
func getParentDn(dn string) string {
// Split DN by comma
parts := strings.Split(dn, ",")
if len(parts) <= 1 {
return ""
}
// Remove the first component (the current node) and rejoin
return strings.Join(parts[1:], ",")
}
// parseDnToGroupName converts a DN to a group name
func parseDnToGroupName(dn string) string {
// Extract the CN or OU from the DN
parts := strings.Split(dn, ",")
if len(parts) == 0 {
return ""
}
firstPart := parts[0]
// Extract value after = sign
if idx := strings.Index(firstPart, "="); idx != -1 {
return firstPart[idx+1:]
}
return firstPart
}
func AutoAdjustLdapUser(users []LdapUser) []LdapUser {
res := make([]LdapUser, len(users))
@@ -289,6 +416,8 @@ func AutoAdjustLdapUser(users []LdapUser) []LdapUser {
Mobile: util.ReturnAnyNotEmpty(user.Mobile, user.MobileTelephoneNumber, user.TelephoneNumber),
Address: util.ReturnAnyNotEmpty(user.Address, user.PostalAddress, user.RegisteredAddress),
Country: util.ReturnAnyNotEmpty(user.Country, user.CountryName),
CountryName: user.CountryName,
MemberOf: user.MemberOf,
Attributes: user.Attributes,
}
}
@@ -361,6 +490,7 @@ func SyncLdapUsers(owner string, syncUsers []LdapUser, ldapId string) (existUser
Avatar: organization.DefaultAvatar,
Email: syncUser.Email,
Phone: syncUser.Mobile,
CountryCode: syncUser.Country,
Address: []string{syncUser.Address},
Region: util.ReturnAnyNotEmpty(syncUser.Country, syncUser.CountryName),
Affiliation: affiliation,
@@ -369,9 +499,24 @@ func SyncLdapUsers(owner string, syncUsers []LdapUser, ldapId string) (existUser
Ldap: syncUser.Uuid,
Properties: syncUser.Attributes,
}
formatUserPhone(newUser)
// Assign user to groups based on memberOf attribute
userGroups := []string{}
if ldap.DefaultGroup != "" {
newUser.Groups = []string{ldap.DefaultGroup}
userGroups = append(userGroups, ldap.DefaultGroup)
}
// Extract group names from memberOf DNs
for _, memberDn := range syncUser.MemberOf {
groupName := dnToGroupName(owner, memberDn)
if groupName != "" {
userGroups = append(userGroups, groupName)
}
}
if len(userGroups) > 0 {
newUser.Groups = userGroups
}
affected, err := AddUser(newUser, "en")
@@ -392,6 +537,179 @@ func SyncLdapUsers(owner string, syncUsers []LdapUser, ldapId string) (existUser
return existUsers, failedUsers, err
}
// SyncLdapGroups syncs LDAP groups/OUs to Casdoor groups with hierarchy
func SyncLdapGroups(owner string, ldapGroups []LdapGroup, ldapId string) (newGroups int, updatedGroups int, err error) {
if len(ldapGroups) == 0 {
return 0, 0, nil
}
// Create a map of DN to group for quick lookup
dnToGroup := make(map[string]*LdapGroup)
for i := range ldapGroups {
dnToGroup[ldapGroups[i].Dn] = &ldapGroups[i]
}
// Get existing groups for this organization
existingGroups, err := GetGroups(owner)
if err != nil {
return 0, 0, err
}
existingGroupMap := make(map[string]*Group)
for _, group := range existingGroups {
existingGroupMap[group.Name] = group
}
ldap, err := GetLdap(ldapId)
if err != nil {
return 0, 0, err
}
// Process groups in hierarchical order (parents before children)
processedGroups := make(map[string]bool)
var processGroup func(ldapGroup *LdapGroup) error
processGroup = func(ldapGroup *LdapGroup) error {
if processedGroups[ldapGroup.Dn] {
return nil
}
// Generate group name from DN
groupName := dnToGroupName(owner, ldapGroup.Dn)
if groupName == "" {
return nil
}
// Determine parent
var parentId string
var isTopGroup bool
if ldapGroup.ParentDn == "" || ldapGroup.ParentDn == ldap.BaseDn {
isTopGroup = true
parentId = ""
} else {
// Process parent first
if parentGroup, exists := dnToGroup[ldapGroup.ParentDn]; exists {
err := processGroup(parentGroup)
if err != nil {
return err
}
parentId = dnToGroupName(owner, ldapGroup.ParentDn)
} else {
isTopGroup = true
}
}
// Check if group already exists
if existingGroup, exists := existingGroupMap[groupName]; exists {
// Update existing group
existingGroup.DisplayName = ldapGroup.Name
existingGroup.ParentId = parentId
existingGroup.IsTopGroup = isTopGroup
existingGroup.Type = "ldap-synced"
existingGroup.UpdatedTime = util.GetCurrentTime()
_, err := UpdateGroup(existingGroup.GetId(), existingGroup)
if err == nil {
updatedGroups++
}
} else {
// Create new group
newGroup := &Group{
Owner: owner,
Name: groupName,
CreatedTime: util.GetCurrentTime(),
UpdatedTime: util.GetCurrentTime(),
DisplayName: ldapGroup.Name,
ParentId: parentId,
IsTopGroup: isTopGroup,
Type: "ldap-synced",
IsEnabled: true,
}
_, err := AddGroup(newGroup)
if err == nil {
newGroups++
existingGroupMap[groupName] = newGroup
}
}
processedGroups[ldapGroup.Dn] = true
return nil
}
// Process all groups
for i := range ldapGroups {
err := processGroup(&ldapGroups[i])
if err != nil {
// Log error but continue processing other groups
continue
}
}
return newGroups, updatedGroups, nil
}
// dnToGroupName converts an LDAP DN to a Casdoor group name
func dnToGroupName(owner, dn string) string {
if dn == "" {
return ""
}
// Parse DN to extract meaningful components
parts := strings.Split(dn, ",")
// Build a hierarchical name from DN components (excluding DC parts)
var nameComponents []string
for _, part := range parts {
part = strings.TrimSpace(part)
lowerPart := strings.ToLower(part)
// Skip DC (domain component) parts
if strings.HasPrefix(lowerPart, "dc=") {
continue
}
// Extract value after = sign
if idx := strings.Index(part, "="); idx != -1 {
value := part[idx+1:]
nameComponents = append(nameComponents, value)
}
}
if len(nameComponents) == 0 {
return ""
}
// Reverse to get top-down hierarchy
for i, j := 0, len(nameComponents)-1; i < j; i, j = i+1, j-1 {
nameComponents[i], nameComponents[j] = nameComponents[j], nameComponents[i]
}
// Join with underscore to create a unique group name
groupName := strings.Join(nameComponents, "_")
// Sanitize group name - replace invalid characters with underscores
// Keep only alphanumeric characters, underscores, and hyphens
var sanitized strings.Builder
for _, r := range groupName {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' {
sanitized.WriteRune(r)
} else {
sanitized.WriteRune('_')
}
}
groupName = sanitized.String()
// Remove consecutive underscores and trim
for strings.Contains(groupName, "__") {
groupName = strings.ReplaceAll(groupName, "__", "_")
}
groupName = strings.Trim(groupName, "_")
return groupName
}
func GetExistUuids(owner string, uuids []string) ([]string, error) {
var existUuids []string

193
object/oauth_dcr.go Normal file
View File

@@ -0,0 +1,193 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"fmt"
"time"
"github.com/casdoor/casdoor/util"
)
// DynamicClientRegistrationRequest represents an RFC 7591 client registration request
type DynamicClientRegistrationRequest struct {
ClientName string `json:"client_name,omitempty"`
RedirectUris []string `json:"redirect_uris,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
ApplicationType string `json:"application_type,omitempty"`
Contacts []string `json:"contacts,omitempty"`
LogoUri string `json:"logo_uri,omitempty"`
ClientUri string `json:"client_uri,omitempty"`
PolicyUri string `json:"policy_uri,omitempty"`
TosUri string `json:"tos_uri,omitempty"`
Scope string `json:"scope,omitempty"`
}
// DynamicClientRegistrationResponse represents an RFC 7591 client registration response
type DynamicClientRegistrationResponse struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
ClientIdIssuedAt int64 `json:"client_id_issued_at,omitempty"`
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
ClientName string `json:"client_name,omitempty"`
RedirectUris []string `json:"redirect_uris,omitempty"`
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
ApplicationType string `json:"application_type,omitempty"`
Contacts []string `json:"contacts,omitempty"`
LogoUri string `json:"logo_uri,omitempty"`
ClientUri string `json:"client_uri,omitempty"`
PolicyUri string `json:"policy_uri,omitempty"`
TosUri string `json:"tos_uri,omitempty"`
Scope string `json:"scope,omitempty"`
RegistrationClientUri string `json:"registration_client_uri,omitempty"`
RegistrationAccessToken string `json:"registration_access_token,omitempty"`
}
// DcrError represents an RFC 7591 error response
type DcrError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
// RegisterDynamicClient creates a new application based on DCR request
func RegisterDynamicClient(req *DynamicClientRegistrationRequest, organization string) (*DynamicClientRegistrationResponse, *DcrError, error) {
// Validate organization exists and has DCR enabled
org, err := GetOrganization(util.GetId("admin", organization))
if err != nil {
return nil, nil, err
}
if org == nil {
return nil, &DcrError{
Error: "invalid_client_metadata",
ErrorDescription: "organization not found",
}, nil
}
// Check if DCR is enabled for this organization
if org.DcrPolicy == "" || org.DcrPolicy == "disabled" {
return nil, &DcrError{
Error: "invalid_client_metadata",
ErrorDescription: "dynamic client registration is disabled for this organization",
}, nil
}
// Validate required fields
if len(req.RedirectUris) == 0 {
return nil, &DcrError{
Error: "invalid_redirect_uri",
ErrorDescription: "redirect_uris is required and must contain at least one URI",
}, nil
}
// Set defaults
if req.ClientName == "" {
clientIdPrefix := util.GenerateClientId()
if len(clientIdPrefix) > 8 {
clientIdPrefix = clientIdPrefix[:8]
}
req.ClientName = fmt.Sprintf("DCR Client %s", clientIdPrefix)
}
if len(req.GrantTypes) == 0 {
req.GrantTypes = []string{"authorization_code"}
}
if len(req.ResponseTypes) == 0 {
req.ResponseTypes = []string{"code"}
}
if req.TokenEndpointAuthMethod == "" {
req.TokenEndpointAuthMethod = "client_secret_basic"
}
if req.ApplicationType == "" {
req.ApplicationType = "web"
}
// Generate unique application name
randomName := util.GetRandomName()
appName := fmt.Sprintf("dcr_%s", randomName)
// Create Application object
// Note: DCR applications are created under "admin" owner by default
// This can be made configurable in future versions
clientId := util.GenerateClientId()
clientSecret := util.GenerateClientSecret()
createdTime := util.GetCurrentTime()
application := &Application{
Owner: "admin",
Name: appName,
Organization: organization,
CreatedTime: createdTime,
DisplayName: req.ClientName,
Category: "Agent",
Type: "MCP",
Scopes: []*ScopeItem{},
Logo: req.LogoUri,
HomepageUrl: req.ClientUri,
ClientId: clientId,
ClientSecret: clientSecret,
RedirectUris: req.RedirectUris,
GrantTypes: req.GrantTypes,
EnablePassword: false,
EnableSignUp: false,
DisableSignin: false,
EnableSigninSession: false,
EnableCodeSignin: true,
EnableAutoSignin: false,
TokenFormat: "JWT",
ExpireInHours: 168,
RefreshExpireInHours: 168,
CookieExpireInHours: 720,
FormOffset: 2,
Tags: []string{"dcr"},
TermsOfUse: req.TosUri,
}
// Add the application
affected, err := AddApplication(application)
if err != nil {
return nil, nil, err
}
if !affected {
return nil, &DcrError{
Error: "invalid_client_metadata",
ErrorDescription: "failed to create client application",
}, nil
}
// Build response
response := &DynamicClientRegistrationResponse{
ClientId: clientId,
ClientSecret: clientSecret,
ClientIdIssuedAt: time.Now().Unix(),
ClientSecretExpiresAt: 0, // Never expires
ClientName: req.ClientName,
RedirectUris: req.RedirectUris,
GrantTypes: req.GrantTypes,
ResponseTypes: req.ResponseTypes,
TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
ApplicationType: req.ApplicationType,
Contacts: req.Contacts,
LogoUri: req.LogoUri,
ClientUri: req.ClientUri,
PolicyUri: req.PolicyUri,
TosUri: req.TosUri,
Scope: req.Scope,
}
return response, nil, nil
}

View File

@@ -26,6 +26,7 @@ type Order struct {
Owner string `xorm:"varchar(100) notnull pk" json:"owner"`
Name string `xorm:"varchar(100) notnull pk" json:"name"`
CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
UpdateTime string `xorm:"varchar(100)" json:"updateTime"`
DisplayName string `xorm:"varchar(100)" json:"displayName"`
// Product Info
@@ -43,15 +44,12 @@ type Order struct {
// Order State
State string `xorm:"varchar(100)" json:"state"`
Message string `xorm:"varchar(2000)" json:"message"`
// Order Duration
StartTime string `xorm:"varchar(100)" json:"startTime"`
EndTime string `xorm:"varchar(100)" json:"endTime"`
}
type ProductInfo struct {
Owner string `json:"owner"`
Name string `json:"name"`
CreatedTime string `json:"createdTime,omitempty"`
DisplayName string `json:"displayName"`
Image string `json:"image,omitempty"`
Detail string `json:"detail,omitempty"`
@@ -138,6 +136,14 @@ func UpdateOrder(id string, order *Order) (bool, error) {
return false, nil
}
if o.State != order.State {
if order.State == "Created" {
order.UpdateTime = ""
} else {
order.UpdateTime = util.GetCurrentTime()
}
}
if !slices.Equal(o.Products, order.Products) {
existingInfos := make(map[string]ProductInfo, len(o.ProductInfos))
for _, info := range o.ProductInfos {

View File

@@ -99,8 +99,7 @@ func PlaceOrder(owner string, reqProductInfos []ProductInfo, user *User) (*Order
Currency: orderCurrency,
State: "Created",
Message: "",
StartTime: util.GetCurrentTime(),
EndTime: "",
UpdateTime: "",
}
affected, err := AddOrder(order)
@@ -180,6 +179,17 @@ func PayOrder(providerName, host, paymentEnv string, order *Order, lang string)
return nil, nil, fmt.Errorf("the plan: %s does not exist", productInfo.PlanName)
}
// Check if plan restricts user to one subscription
if plan.IsExclusive {
hasSubscription, err := HasActiveSubscriptionForPlan(owner, user.Name, plan.Name)
if err != nil {
return nil, nil, err
}
if hasSubscription {
return nil, nil, fmt.Errorf("user already has an active subscription for plan: %s", plan.Name)
}
}
sub, err := NewSubscription(owner, user.Name, plan.Name, paymentName, plan.Period)
if err != nil {
return nil, nil, err
@@ -266,7 +276,7 @@ func PayOrder(providerName, host, paymentEnv string, order *Order, lang string)
OutOrderId: payResp.OrderId,
}
if provider.Type == "Dummy" || provider.Type == "Balance" {
if provider.Type == "Balance" {
payment.State = pp.PaymentStatePaid
}
@@ -341,10 +351,10 @@ func PayOrder(providerName, host, paymentEnv string, order *Order, lang string)
}
order.Payment = payment.Name
if provider.Type == "Dummy" || provider.Type == "Balance" {
if provider.Type == "Balance" {
order.State = "Paid"
order.Message = "Payment successful"
order.EndTime = util.GetCurrentTime()
order.UpdateTime = util.GetCurrentTime()
}
// Update order state first to avoid inconsistency
@@ -354,7 +364,7 @@ func PayOrder(providerName, host, paymentEnv string, order *Order, lang string)
}
// Update product stock after order state is persisted (for instant payment methods)
if provider.Type == "Dummy" || provider.Type == "Balance" {
if provider.Type == "Balance" {
err = UpdateProductStock(orderProductInfos)
if err != nil {
return nil, nil, err
@@ -371,6 +381,6 @@ func CancelOrder(order *Order) (bool, error) {
order.State = "Canceled"
order.Message = "Canceled by user"
order.EndTime = util.GetCurrentTime()
order.UpdateTime = util.GetCurrentTime()
return UpdateOrder(order.GetId(), order)
}

View File

@@ -32,6 +32,7 @@ type AccountItem struct {
ViewRule string `json:"viewRule"`
ModifyRule string `json:"modifyRule"`
Regex string `json:"regex"`
Tab string `json:"tab"`
}
type ThemeData struct {
@@ -88,8 +89,11 @@ type Organization struct {
MfaItems []*MfaItem `xorm:"varchar(300)" json:"mfaItems"`
MfaRememberInHours int `json:"mfaRememberInHours"`
AccountMenu string `xorm:"varchar(20)" json:"accountMenu"`
AccountItems []*AccountItem `xorm:"mediumtext" json:"accountItems"`
DcrPolicy string `xorm:"varchar(100)" json:"dcrPolicy"`
OrgBalance float64 `json:"orgBalance"`
UserBalance float64 `json:"userBalance"`
BalanceCredit float64 `json:"balanceCredit"`

View File

@@ -29,9 +29,9 @@ import (
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/util"
xormadapter "github.com/casdoor/xorm-adapter/v3"
_ "github.com/denisenkom/go-mssqldb" // db = mssql
_ "github.com/go-sql-driver/mysql" // db = mysql
_ "github.com/lib/pq" // db = postgres
_ "github.com/go-sql-driver/mysql" // db = mysql
_ "github.com/lib/pq" // db = postgres
_ "github.com/microsoft/go-mssqldb" // db = mssql
"github.com/xorm-io/xorm"
"github.com/xorm-io/xorm/core"
"github.com/xorm-io/xorm/names"
@@ -62,6 +62,12 @@ func InitFlag() {
configPath = *configPathPtr
exportData = *exportDataPtr
exportFilePath = *exportFilePathPtr
// Load beego config from the specified config path
err := web.LoadAppConfig("ini", configPath)
if err != nil {
panic(fmt.Sprintf("failed to load config from %s: %v", configPath, err))
}
}
func ShouldExportData() bool {

View File

@@ -33,6 +33,8 @@ type Payment struct {
// Product Info
Products []string `xorm:"varchar(1000)" json:"products"`
ProductsDisplayName string `xorm:"varchar(1000)" json:"productsDisplayName"`
ProductName string `xorm:"varchar(1000)" json:"productName"`
ProductDisplayName string `xorm:"varchar(1000)" json:"productDisplayName"`
Detail string `xorm:"varchar(255)" json:"detail"`
Currency string `xorm:"varchar(100)" json:"currency"`
Price float64 `json:"price"`
@@ -50,7 +52,8 @@ type Payment struct {
InvoiceRemark string `xorm:"varchar(100)" json:"invoiceRemark"`
InvoiceUrl string `xorm:"varchar(255)" json:"invoiceUrl"`
// Order Info
Order string `xorm:"varchar(100)" json:"order"` // Internal order name
Order string `xorm:"varchar(100)" json:"order"` // Internal order name
OrderObj *Order `xorm:"-" json:"orderObj,omitempty"`
OutOrderId string `xorm:"varchar(100)" json:"outOrderId"` // External payment provider's order ID
PayUrl string `xorm:"varchar(2000)" json:"payUrl"`
SuccessUrl string `xorm:"varchar(2000)" json:"successUrl"` // `successUrl` is redirected from `payUrl` after pay success
@@ -70,6 +73,11 @@ func GetPayments(owner string) ([]*Payment, error) {
return nil, err
}
err = ExtendPaymentWithOrder(payments)
if err != nil {
return nil, err
}
return payments, nil
}
@@ -80,6 +88,11 @@ func GetUserPayments(owner, user string) ([]*Payment, error) {
return nil, err
}
err = ExtendPaymentWithOrder(payments)
if err != nil {
return nil, err
}
return payments, nil
}
@@ -91,9 +104,49 @@ func GetPaginationPayments(owner string, offset, limit int, field, value, sortFi
return nil, err
}
err = ExtendPaymentWithOrder(payments)
if err != nil {
return nil, err
}
return payments, nil
}
func ExtendPaymentWithOrder(payments []*Payment) error {
ownerOrdersMap := make(map[string][]string)
for _, payment := range payments {
if payment.Order != "" {
ownerOrdersMap[payment.Owner] = append(ownerOrdersMap[payment.Owner], payment.Order)
}
}
ordersMap := make(map[string]*Order)
for owner, orderNames := range ownerOrdersMap {
if len(orderNames) == 0 {
continue
}
var orders []*Order
err := ormer.Engine.In("name", orderNames).Find(&orders, &Order{Owner: owner})
if err != nil {
return err
}
for _, order := range orders {
ordersMap[util.GetId(order.Owner, order.Name)] = order
}
}
for _, payment := range payments {
if payment.Order != "" {
orderId := util.GetId(payment.Owner, payment.Order)
if order, ok := ordersMap[orderId]; ok {
payment.OrderObj = order
}
}
}
return nil
}
func getPayment(owner string, name string) (*Payment, error) {
if owner == "" || name == "" {
return nil, nil
@@ -210,18 +263,29 @@ func NotifyPayment(body []byte, owner string, paymentName string, lang string) (
}
// Check if payment is already in a terminal state to prevent duplicate processing
if payment.State == pp.PaymentStatePaid || payment.State == pp.PaymentStateError ||
payment.State == pp.PaymentStateCanceled || payment.State == pp.PaymentStateTimeout {
if pp.IsTerminalState(payment.State) {
return payment, nil
}
// Determine the new payment state
var newState pp.PaymentState
var newMessage string
if err != nil {
payment.State = pp.PaymentStateError
payment.Message = err.Error()
newState = pp.PaymentStateError
newMessage = err.Error()
} else {
payment.State = notifyResult.PaymentStatus
payment.Message = notifyResult.NotifyMessage
newState = notifyResult.PaymentStatus
newMessage = notifyResult.NotifyMessage
}
// Check if the payment state would actually change
// This prevents duplicate webhook events when providers send redundant notifications
if payment.State == newState {
return payment, nil
}
payment.State = newState
payment.Message = newMessage
_, err = UpdatePayment(payment.GetId(), payment)
if err != nil {
return nil, err
@@ -239,16 +303,19 @@ func NotifyPayment(body []byte, owner string, paymentName string, lang string) (
if payment.State == pp.PaymentStatePaid {
order.State = "Paid"
order.Message = "Payment successful"
order.EndTime = util.GetCurrentTime()
order.UpdateTime = util.GetCurrentTime()
} else if payment.State == pp.PaymentStateError {
order.State = "PaymentFailed"
order.State = "Failed"
order.Message = payment.Message
order.UpdateTime = util.GetCurrentTime()
} else if payment.State == pp.PaymentStateCanceled {
order.State = "Canceled"
order.Message = "Payment was cancelled"
order.UpdateTime = util.GetCurrentTime()
} else if payment.State == pp.PaymentStateTimeout {
order.State = "Timeout"
order.Message = "Payment timed out"
order.UpdateTime = util.GetCurrentTime()
}
_, err = UpdateOrder(order.GetId(), order)
if err != nil {

View File

@@ -35,6 +35,7 @@ type Plan struct {
Product string `xorm:"varchar(100)" json:"product"`
PaymentProviders []string `xorm:"varchar(100)" json:"paymentProviders"` // payment providers for related product
IsEnabled bool `json:"isEnabled"`
IsExclusive bool `json:"isExclusive"` // if true, a user can only have at most one subscription of this plan
Role string `xorm:"varchar(100)" json:"role"`
Options []string `xorm:"-" json:"options"`

View File

@@ -53,7 +53,8 @@ type Provider struct {
Host string `xorm:"varchar(100)" json:"host"`
Port int `json:"port"`
DisableSsl bool `json:"disableSsl"` // If the provider type is WeChat, DisableSsl means EnableQRCode, if type is Google, it means sync phone number
DisableSsl bool `json:"disableSsl"` // Deprecated: Use SslMode instead. If the provider type is WeChat, DisableSsl means EnableQRCode, if type is Google, it means sync phone number
SslMode string `xorm:"varchar(100)" json:"sslMode"` // "Auto" (empty means Auto), "Enable", "Disable"
Title string `xorm:"varchar(100)" json:"title"`
Content string `xorm:"varchar(2000)" json:"content"` // If provider type is WeChat, Content means QRCode string by Base64 encoding
Receiver string `xorm:"varchar(100)" json:"receiver"`
@@ -563,7 +564,7 @@ func providerChangeTrigger(oldName string, newName string) error {
return session.Commit()
}
func FromProviderToIdpInfo(ctx *context.Context, provider *Provider) *idp.ProviderInfo {
func FromProviderToIdpInfo(ctx *context.Context, provider *Provider) (*idp.ProviderInfo, error) {
providerInfo := &idp.ProviderInfo{
Type: provider.Type,
SubType: provider.SubType,
@@ -587,9 +588,19 @@ func FromProviderToIdpInfo(ctx *context.Context, provider *Provider) *idp.Provid
}
} else if provider.Type == "ADFS" || provider.Type == "AzureAD" || provider.Type == "AzureADB2C" || provider.Type == "Casdoor" || provider.Type == "Okta" {
providerInfo.HostUrl = provider.Domain
} else if provider.Type == "Alipay" && provider.Cert != "" {
// For Alipay with certificate mode, load private key from certificate
cert, err := GetCert(util.GetId(provider.Owner, provider.Cert))
if err != nil {
return nil, fmt.Errorf("failed to load certificate for Alipay provider %s: %w", provider.Name, err)
}
if cert == nil {
return nil, fmt.Errorf("certificate not found for Alipay provider %s", provider.Name)
}
providerInfo.ClientSecret = cert.PrivateKey
}
return providerInfo
return providerInfo, nil
}
func GetIdvProviderFromProvider(provider *Provider) idv.IdvProvider {

View File

@@ -80,7 +80,7 @@ func NewRecord(ctx *context.Context) (*casvisorsdk.Record, error) {
return nil, err
}
if action != "buy-product" {
if action != "buy-product" && action != "notify-payment" {
resp.Data = nil
}

View File

@@ -175,8 +175,10 @@ func DeleteSession(id, curSessionId string) (bool, error) {
return false, err
}
// If session doesn't exist, return success with no rows affected
// This is a valid state (e.g., when a user has no active session)
if session == nil {
return false, fmt.Errorf("session is nil")
return false, nil
}
if slices.Contains(session.SessionId, curSessionId) {

View File

@@ -28,6 +28,8 @@ func getSmsClient(provider *Provider) (sender.SmsClient, error) {
client, err = sender.NewSmsClient(provider.Type, provider.ClientId, provider.ClientSecret, provider.SignName, provider.TemplateCode, provider.ProviderUrl, provider.AppId)
} else if provider.Type == "Custom HTTP SMS" {
client, err = newHttpSmsClient(provider.Endpoint, provider.Method, provider.Title, provider.TemplateCode, provider.HttpHeaders, provider.UserMapping, provider.IssuerUrl, provider.EnableProxy)
} else if provider.Type == "Alibaba Cloud PNVS SMS" {
client, err = newPnvsSmsClient(provider.ClientId, provider.ClientSecret, provider.SignName, provider.TemplateCode, provider.RegionId)
} else {
client, err = sender.NewSmsClient(provider.Type, provider.ClientId, provider.ClientSecret, provider.SignName, provider.TemplateCode, provider.AppId)
}
@@ -48,7 +50,7 @@ func SendSms(provider *Provider, content string, phoneNumbers ...string) error {
if provider.AppId != "" {
phoneNumbers = append([]string{provider.AppId}, phoneNumbers...)
}
} else if provider.Type == sender.Aliyun {
} else if provider.Type == sender.Aliyun || provider.Type == "Alibaba Cloud PNVS SMS" {
for i, number := range phoneNumbers {
phoneNumbers[i] = strings.TrimPrefix(number, "+86")
}

86
object/sms_pnvs.go Normal file
View File

@@ -0,0 +1,86 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dypnsapi"
)
type PnvsSmsClient struct {
template string
sign string
core *dypnsapi.Client
}
func newPnvsSmsClient(accessId string, accessKey string, sign string, template string, regionId string) (*PnvsSmsClient, error) {
if regionId == "" {
regionId = "cn-hangzhou"
}
client, err := dypnsapi.NewClientWithAccessKey(regionId, accessId, accessKey)
if err != nil {
return nil, err
}
pnvsClient := &PnvsSmsClient{
template: template,
core: client,
sign: sign,
}
return pnvsClient, nil
}
func (c *PnvsSmsClient) SendMessage(param map[string]string, targetPhoneNumber ...string) error {
if len(targetPhoneNumber) == 0 {
return fmt.Errorf("missing parameter: targetPhoneNumber")
}
// PNVS sends to one phone number at a time
phoneNumber := targetPhoneNumber[0]
request := dypnsapi.CreateSendSmsVerifyCodeRequest()
request.Scheme = "https"
request.PhoneNumber = phoneNumber
request.TemplateCode = c.template
request.SignName = c.sign
// TemplateParam is optional for PNVS as it can auto-generate verification codes
// But if params are provided, we'll pass them
if len(param) > 0 {
templateParam, err := json.Marshal(param)
if err != nil {
return err
}
request.TemplateParam = string(templateParam)
}
response, err := c.core.SendSmsVerifyCode(request)
if err != nil {
return err
}
if response.Code != "OK" {
if response.Message != "" {
return fmt.Errorf(response.Message)
}
return fmt.Errorf("PNVS SMS send failed with code: %s", response.Code)
}
return nil
}

View File

@@ -217,6 +217,26 @@ func GetSubscription(id string) (*Subscription, error) {
return getSubscription(owner, name)
}
func HasActiveSubscriptionForPlan(owner, userName, planName string) (bool, error) {
subscriptions := []*Subscription{}
err := ormer.Engine.Find(&subscriptions, &Subscription{Owner: owner, User: userName, Plan: planName})
if err != nil {
return false, err
}
for _, sub := range subscriptions {
err = sub.UpdateState()
if err != nil {
return false, err
}
// Check if subscription is active, upcoming, or pending (not expired, error, or suspended)
if sub.State == SubStateActive || sub.State == SubStateUpcoming || sub.State == SubStatePending {
return true, nil
}
}
return false, nil
}
func UpdateSubscription(id string, subscription *Subscription) (bool, error) {
owner, name, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {

View File

@@ -370,3 +370,15 @@ func (p *ActiveDirectorySyncerProvider) adEntryToOriginalUser(entry *goldap.Entr
return user
}
// GetOriginalGroups retrieves all groups from Active Directory (not implemented yet)
func (p *ActiveDirectorySyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Active Directory group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *ActiveDirectorySyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Active Directory user group membership sync
return []string{}, nil
}

327
object/syncer_awsiam.go Normal file
View File

@@ -0,0 +1,327 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/casdoor/casdoor/util"
)
// AwsIamSyncerProvider implements SyncerProvider for AWS IAM API-based syncers
type AwsIamSyncerProvider struct {
Syncer *Syncer
iamClient *iam.IAM
}
// InitAdapter initializes the AWS IAM syncer
func (p *AwsIamSyncerProvider) InitAdapter() error {
// syncer.Host should be the AWS region (e.g., "us-east-1")
// syncer.User should be the AWS Access Key ID
// syncer.Password should be the AWS Secret Access Key
region := p.Syncer.Host
if region == "" {
return fmt.Errorf("AWS region (host field) is required for AWS IAM syncer")
}
accessKeyId := p.Syncer.User
if accessKeyId == "" {
return fmt.Errorf("AWS Access Key ID (user field) is required for AWS IAM syncer")
}
secretAccessKey := p.Syncer.Password
if secretAccessKey == "" {
return fmt.Errorf("AWS Secret Access Key (password field) is required for AWS IAM syncer")
}
// Create AWS session
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""),
})
if err != nil {
return fmt.Errorf("failed to create AWS session: %w", err)
}
// Create IAM client
p.iamClient = iam.New(sess)
return nil
}
// GetOriginalUsers retrieves all users from AWS IAM API
func (p *AwsIamSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error) {
if p.iamClient == nil {
if err := p.InitAdapter(); err != nil {
return nil, err
}
}
return p.getAwsIamUsers()
}
// AddUser adds a new user to AWS IAM (not supported for read-only API)
func (p *AwsIamSyncerProvider) AddUser(user *OriginalUser) (bool, error) {
// AWS IAM syncer is typically read-only
return false, fmt.Errorf("adding users to AWS IAM is not supported")
}
// UpdateUser updates an existing user in AWS IAM (not supported for read-only API)
func (p *AwsIamSyncerProvider) UpdateUser(user *OriginalUser) (bool, error) {
// AWS IAM syncer is typically read-only
return false, fmt.Errorf("updating users in AWS IAM is not supported")
}
// TestConnection tests the AWS IAM API connection
func (p *AwsIamSyncerProvider) TestConnection() error {
if p.iamClient == nil {
if err := p.InitAdapter(); err != nil {
return err
}
}
// Try to list users with a limit of 1 to test the connection
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
input := &iam.ListUsersInput{
MaxItems: aws.Int64(1),
}
_, err := p.iamClient.ListUsersWithContext(ctx, input)
return err
}
// Close closes any open connections
func (p *AwsIamSyncerProvider) Close() error {
// AWS IAM client doesn't require explicit cleanup
p.iamClient = nil
return nil
}
// getAwsIamUsers gets all users from AWS IAM API
func (p *AwsIamSyncerProvider) getAwsIamUsers() ([]*OriginalUser, error) {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
allUsers := []*iam.User{}
var marker *string
// Paginate through all users
for {
input := &iam.ListUsersInput{
Marker: marker,
}
result, err := p.iamClient.ListUsersWithContext(ctx, input)
if err != nil {
return nil, fmt.Errorf("failed to list IAM users: %w", err)
}
allUsers = append(allUsers, result.Users...)
if result.IsTruncated == nil || !*result.IsTruncated {
break
}
marker = result.Marker
}
// Convert AWS IAM users to Casdoor OriginalUser
originalUsers := []*OriginalUser{}
for _, iamUser := range allUsers {
originalUser, err := p.awsIamUserToOriginalUser(iamUser)
if err != nil {
// Log error but continue processing other users
userName := "unknown"
if iamUser.UserName != nil {
userName = *iamUser.UserName
}
fmt.Printf("Warning: Failed to convert IAM user %s: %v\n", userName, err)
continue
}
originalUsers = append(originalUsers, originalUser)
}
return originalUsers, nil
}
// awsIamUserToOriginalUser converts AWS IAM user to Casdoor OriginalUser
func (p *AwsIamSyncerProvider) awsIamUserToOriginalUser(iamUser *iam.User) (*OriginalUser, error) {
if iamUser == nil {
return nil, fmt.Errorf("IAM user is nil")
}
user := &OriginalUser{
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
}
// Set ID from UserId (unique identifier)
if iamUser.UserId != nil {
user.Id = *iamUser.UserId
}
// Set Name from UserName
if iamUser.UserName != nil {
user.Name = *iamUser.UserName
}
// Set DisplayName (use UserName if not available separately)
if iamUser.UserName != nil {
user.DisplayName = *iamUser.UserName
}
// Set CreatedTime from CreateDate
if iamUser.CreateDate != nil {
user.CreatedTime = iamUser.CreateDate.Format(time.RFC3339)
} else {
user.CreatedTime = util.GetCurrentTime()
}
// Get user tags which might contain additional information
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
tagsInput := &iam.ListUserTagsInput{
UserName: iamUser.UserName,
}
tagsResult, err := p.iamClient.ListUserTagsWithContext(ctx, tagsInput)
if err == nil && tagsResult != nil {
// Process tags to extract additional user information
for _, tag := range tagsResult.Tags {
if tag.Key != nil && tag.Value != nil {
key := *tag.Key
value := *tag.Value
switch key {
case "Email", "email":
user.Email = value
case "Phone", "phone":
user.Phone = value
case "DisplayName", "displayName":
user.DisplayName = value
case "FirstName", "firstName":
user.FirstName = value
case "LastName", "lastName":
user.LastName = value
case "Title", "title":
user.Title = value
case "Department", "department":
user.Affiliation = value
default:
// Store other tags in Properties
user.Properties[key] = value
}
}
}
}
// AWS IAM users are active by default unless specified in tags
// Check if there's a "Status" or "Active" tag
if status, ok := user.Properties["Status"]; ok {
if status == "Inactive" || status == "Disabled" {
user.IsForbidden = true
}
}
if active, ok := user.Properties["Active"]; ok {
if active == "false" || active == "False" || active == "0" {
user.IsForbidden = true
}
}
return user, nil
}
// GetOriginalGroups retrieves all groups from AWS IAM
func (p *AwsIamSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
if p.iamClient == nil {
if err := p.InitAdapter(); err != nil {
return nil, err
}
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
allGroups := []*iam.Group{}
var marker *string
// Paginate through all groups
for {
input := &iam.ListGroupsInput{
Marker: marker,
}
result, err := p.iamClient.ListGroupsWithContext(ctx, input)
if err != nil {
return nil, fmt.Errorf("failed to list IAM groups: %w", err)
}
allGroups = append(allGroups, result.Groups...)
if result.IsTruncated == nil || !*result.IsTruncated {
break
}
marker = result.Marker
}
// Convert AWS IAM groups to Casdoor OriginalGroup
originalGroups := []*OriginalGroup{}
for _, iamGroup := range allGroups {
if iamGroup.GroupId != nil && iamGroup.GroupName != nil {
group := &OriginalGroup{
Id: *iamGroup.GroupId,
Name: *iamGroup.GroupName,
}
if iamGroup.GroupName != nil {
group.DisplayName = *iamGroup.GroupName
}
originalGroups = append(originalGroups, group)
}
}
return originalGroups, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to
func (p *AwsIamSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
if p.iamClient == nil {
if err := p.InitAdapter(); err != nil {
return nil, err
}
}
// Note: AWS IAM API requires UserName to query groups, but this interface provides UserId.
// This is a known limitation. To properly implement this, we would need to:
// 1. Maintain a mapping cache from UserId to UserName, or
// 2. Modify the interface to accept both UserId and UserName
// For now, returning empty groups to maintain interface compatibility.
// TODO: Implement user group synchronization by maintaining a UserId->UserName mapping
return []string{}, nil
}

View File

@@ -274,3 +274,15 @@ func (p *AzureAdSyncerProvider) getAzureAdOriginalUsers() ([]*OriginalUser, erro
return originalUsers, nil
}
// GetOriginalGroups retrieves all groups from Azure AD (not implemented yet)
func (p *AzureAdSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Azure AD group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *AzureAdSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Azure AD user group membership sync
return []string{}, nil
}

View File

@@ -60,9 +60,19 @@ func addSyncerJob(syncer *Syncer) error {
return err
}
// Sync groups as well
err = syncer.syncGroups()
if err != nil {
// Log error but don't fail the entire sync
fmt.Printf("Warning: syncGroups() error: %s\n", err.Error())
}
schedule := fmt.Sprintf("@every %ds", syncer.SyncInterval)
cron := getCronMap(syncer.Name)
_, err = cron.AddFunc(schedule, syncer.syncUsersNoError)
_, err = cron.AddFunc(schedule, func() {
syncer.syncUsersNoError()
syncer.syncGroupsNoError()
})
if err != nil {
return err
}

View File

@@ -164,3 +164,15 @@ func (t dsnConnector) Connect(ctx context.Context) (driver.Conn, error) {
func (t dsnConnector) Driver() driver.Driver {
return t.driver
}
// GetOriginalGroups retrieves all groups from Database (not implemented yet)
func (p *DatabaseSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Database group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *DatabaseSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Database user group membership sync
return []string{}, nil
}

View File

@@ -109,6 +109,21 @@ type DingtalkDeptListResp struct {
RequestId string `json:"request_id"`
}
type DingtalkDepartment struct {
DeptId int64 `json:"dept_id"`
Name string `json:"name"`
ParentId int64 `json:"parent_id"`
CreateDeptGroup bool `json:"create_dept_group"`
AutoAddUser bool `json:"auto_add_user"`
}
type DingtalkDeptDetailResp struct {
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
Result *DingtalkDepartment `json:"result"`
RequestId string `json:"request_id"`
}
// getDingtalkAccessToken gets access token from DingTalk API
func (p *DingtalkSyncerProvider) getDingtalkAccessToken() (string, error) {
// syncer.User should be the appKey
@@ -160,14 +175,18 @@ func (p *DingtalkSyncerProvider) getDingtalkAccessToken() (string, error) {
return tokenResp.AccessToken, nil
}
// getDingtalkDepartments gets all department IDs from DingTalk API
// getDingtalkDepartments gets all department IDs from DingTalk API recursively
func (p *DingtalkSyncerProvider) getDingtalkDepartments(accessToken string) ([]int64, error) {
return p.getDingtalkDepartmentsRecursive(accessToken, 1)
}
// getDingtalkDepartmentsRecursive recursively fetches all departments starting from parentDeptId
func (p *DingtalkSyncerProvider) getDingtalkDepartmentsRecursive(accessToken string, parentDeptId int64) ([]int64, error) {
apiUrl := fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token=%s",
url.QueryEscape(accessToken))
// Get root department (dept_id=1)
postData := map[string]interface{}{
"dept_id": 1,
"dept_id": parentDeptId,
}
data, err := p.postJSON(apiUrl, postData)
@@ -186,14 +205,49 @@ func (p *DingtalkSyncerProvider) getDingtalkDepartments(accessToken string) ([]i
deptResp.Errcode, deptResp.Errmsg)
}
deptIds := []int64{1} // Include root department
// Start with the parent department itself
deptIds := []int64{parentDeptId}
// Recursively fetch all child departments
for _, dept := range deptResp.Result {
deptIds = append(deptIds, dept.DeptId)
childDeptIds, err := p.getDingtalkDepartmentsRecursive(accessToken, dept.DeptId)
if err != nil {
return nil, err
}
deptIds = append(deptIds, childDeptIds...)
}
return deptIds, nil
}
// getDingtalkDepartmentDetails gets detailed department information
func (p *DingtalkSyncerProvider) getDingtalkDepartmentDetails(accessToken string, deptId int64) (*DingtalkDepartment, error) {
apiUrl := fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/department/get?access_token=%s",
url.QueryEscape(accessToken))
postData := map[string]interface{}{
"dept_id": deptId,
}
data, err := p.postJSON(apiUrl, postData)
if err != nil {
return nil, err
}
var resp DingtalkDeptDetailResp
err = json.Unmarshal(data, &resp)
if err != nil {
return nil, err
}
if resp.Errcode != 0 {
return nil, fmt.Errorf("failed to get department details for %d: errcode=%d, errmsg=%s",
deptId, resp.Errcode, resp.Errmsg)
}
return resp.Result, nil
}
// getDingtalkUsersFromDept gets users from a specific department
func (p *DingtalkSyncerProvider) getDingtalkUsersFromDept(accessToken string, deptId int64) ([]*DingtalkUser, error) {
allUsers := []*DingtalkUser{}
@@ -372,6 +426,12 @@ func (p *DingtalkSyncerProvider) dingtalkUserToOriginalUser(dingtalkUser *Dingta
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
DingTalk: dingtalkUser.UserId, // Link DingTalk provider account
}
// Add department IDs to Groups field
for _, deptId := range dingtalkUser.Department {
user.Groups = append(user.Groups, fmt.Sprintf("%d", deptId))
}
// Set IsForbidden based on active status (active=false means user is forbidden)
@@ -384,3 +444,73 @@ func (p *DingtalkSyncerProvider) dingtalkUserToOriginalUser(dingtalkUser *Dingta
return user
}
// GetOriginalGroups retrieves all groups (departments) from DingTalk
func (p *DingtalkSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// Get access token
accessToken, err := p.getDingtalkAccessToken()
if err != nil {
return nil, err
}
// Get all department IDs
deptIds, err := p.getDingtalkDepartments(accessToken)
if err != nil {
return nil, err
}
// Get detailed information for each department
originalGroups := []*OriginalGroup{}
for _, deptId := range deptIds {
dept, err := p.getDingtalkDepartmentDetails(accessToken, deptId)
if err != nil {
// Log error but continue with other departments
fmt.Printf("Warning: failed to get details for department %d: %v\n", deptId, err)
continue
}
originalGroup := p.dingtalkDepartmentToOriginalGroup(dept)
originalGroups = append(originalGroups, originalGroup)
}
return originalGroups, nil
}
// dingtalkDepartmentToOriginalGroup converts DingTalk department to Casdoor OriginalGroup
func (p *DingtalkSyncerProvider) dingtalkDepartmentToOriginalGroup(dept *DingtalkDepartment) *OriginalGroup {
// Convert department ID to string for group ID
deptIdStr := fmt.Sprintf("%d", dept.DeptId)
return &OriginalGroup{
Id: deptIdStr,
Name: deptIdStr, // Use ID as name for uniqueness
DisplayName: dept.Name, // Use actual name as display name
Description: "", // DingTalk doesn't provide description
Type: "department", // Mark as department type
Manager: "", // DingTalk doesn't provide manager in dept details
Email: "", // DingTalk doesn't provide email for departments
}
}
// GetOriginalUserGroups retrieves the group (department) IDs that a user belongs to
func (p *DingtalkSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// Get access token
accessToken, err := p.getDingtalkAccessToken()
if err != nil {
return nil, err
}
// Get detailed user information which includes department list
user, err := p.getDingtalkUserDetails(accessToken, userId)
if err != nil {
return nil, err
}
// Convert department IDs to strings
groupIds := []string{}
for _, deptId := range user.Department {
groupIds = append(groupIds, fmt.Sprintf("%d", deptId))
}
return groupIds, nil
}

View File

@@ -101,6 +101,7 @@ func (p *GoogleWorkspaceSyncerProvider) getAdminService() (*admin.Service, error
PrivateKey: []byte(serviceAccount.PrivateKey),
Scopes: []string{
admin.AdminDirectoryUserReadonlyScope,
admin.AdminDirectoryGroupReadonlyScope,
},
TokenURL: google.JWTTokenURL,
Subject: adminEmail, // Impersonate the admin user
@@ -202,12 +203,189 @@ func (p *GoogleWorkspaceSyncerProvider) getGoogleWorkspaceOriginalUsers() ([]*Or
return nil, err
}
// Get all groups and their members to build a user-to-groups mapping
// This avoids N+1 queries by fetching group memberships upfront
userGroupsMap, err := p.buildUserGroupsMap(service)
if err != nil {
fmt.Printf("Warning: failed to fetch group memberships: %v. Users will have no groups assigned.\n", err)
userGroupsMap = make(map[string][]string)
}
// Convert Google Workspace users to Casdoor OriginalUser
originalUsers := []*OriginalUser{}
for _, gwUser := range gwUsers {
originalUser := p.googleWorkspaceUserToOriginalUser(gwUser)
// Assign groups from the pre-built map
if groups, exists := userGroupsMap[gwUser.PrimaryEmail]; exists {
originalUser.Groups = groups
} else {
originalUser.Groups = []string{}
}
originalUsers = append(originalUsers, originalUser)
}
return originalUsers, nil
}
// buildUserGroupsMap builds a map of user email to group emails by iterating through all groups
// and their members. This is more efficient than querying groups for each user individually.
func (p *GoogleWorkspaceSyncerProvider) buildUserGroupsMap(service *admin.Service) (map[string][]string, error) {
userGroupsMap := make(map[string][]string)
// Get all groups
groups, err := p.getGoogleWorkspaceGroups(service)
if err != nil {
return nil, fmt.Errorf("failed to fetch groups: %v", err)
}
// For each group, get its members and populate the user-to-groups map
for _, group := range groups {
members, err := p.getGroupMembers(service, group.Id)
if err != nil {
fmt.Printf("Warning: failed to get members for group %s: %v\n", group.Email, err)
continue
}
// Add this group to each member's group list
for _, member := range members {
userGroupsMap[member.Email] = append(userGroupsMap[member.Email], group.Email)
}
}
return userGroupsMap, nil
}
// getGroupMembers retrieves all members of a specific group
func (p *GoogleWorkspaceSyncerProvider) getGroupMembers(service *admin.Service, groupId string) ([]*admin.Member, error) {
allMembers := []*admin.Member{}
pageToken := ""
for {
call := service.Members.List(groupId).MaxResults(500)
if pageToken != "" {
call = call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return nil, fmt.Errorf("failed to list members: %v", err)
}
allMembers = append(allMembers, resp.Members...)
// Handle pagination
if resp.NextPageToken == "" {
break
}
pageToken = resp.NextPageToken
}
return allMembers, nil
}
// GetOriginalGroups retrieves all groups from Google Workspace
func (p *GoogleWorkspaceSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// Get Admin SDK service
service, err := p.getAdminService()
if err != nil {
return nil, err
}
// Get all groups from Google Workspace
gwGroups, err := p.getGoogleWorkspaceGroups(service)
if err != nil {
return nil, err
}
// Convert Google Workspace groups to Casdoor OriginalGroup
originalGroups := []*OriginalGroup{}
for _, gwGroup := range gwGroups {
originalGroup := p.googleWorkspaceGroupToOriginalGroup(gwGroup)
originalGroups = append(originalGroups, originalGroup)
}
return originalGroups, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to
func (p *GoogleWorkspaceSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// Get Admin SDK service
service, err := p.getAdminService()
if err != nil {
return nil, err
}
// Get groups for the user
groupIds := []string{}
pageToken := ""
for {
call := service.Groups.List().UserKey(userId)
if pageToken != "" {
call = call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return nil, fmt.Errorf("failed to list user groups: %v", err)
}
for _, group := range resp.Groups {
groupIds = append(groupIds, group.Email)
}
// Handle pagination
if resp.NextPageToken == "" {
break
}
pageToken = resp.NextPageToken
}
return groupIds, nil
}
// getGoogleWorkspaceGroups gets all groups from Google Workspace using Admin SDK API
func (p *GoogleWorkspaceSyncerProvider) getGoogleWorkspaceGroups(service *admin.Service) ([]*admin.Group, error) {
allGroups := []*admin.Group{}
pageToken := ""
// Get the customer ID (use "my_customer" for the domain)
customer := "my_customer"
for {
call := service.Groups.List().Customer(customer).MaxResults(500)
if pageToken != "" {
call = call.PageToken(pageToken)
}
resp, err := call.Do()
if err != nil {
return nil, fmt.Errorf("failed to list groups: %v", err)
}
allGroups = append(allGroups, resp.Groups...)
// Handle pagination
if resp.NextPageToken == "" {
break
}
pageToken = resp.NextPageToken
}
return allGroups, nil
}
// googleWorkspaceGroupToOriginalGroup converts Google Workspace group to Casdoor OriginalGroup
func (p *GoogleWorkspaceSyncerProvider) googleWorkspaceGroupToOriginalGroup(gwGroup *admin.Group) *OriginalGroup {
group := &OriginalGroup{
Id: gwGroup.Id,
Name: gwGroup.Email,
DisplayName: gwGroup.Name,
Description: gwGroup.Description,
Email: gwGroup.Email,
}
return group
}

View File

@@ -0,0 +1,204 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"testing"
admin "google.golang.org/api/admin/directory/v1"
)
func TestGoogleWorkspaceUserToOriginalUser(t *testing.T) {
provider := &GoogleWorkspaceSyncerProvider{
Syncer: &Syncer{},
}
// Test case 1: Full Google Workspace user with all fields
gwUser := &admin.User{
Id: "user-123",
PrimaryEmail: "john.doe@example.com",
Name: &admin.UserName{
FullName: "John Doe",
GivenName: "John",
FamilyName: "Doe",
},
ThumbnailPhotoUrl: "https://example.com/avatar.jpg",
Suspended: false,
IsAdmin: true,
CreationTime: "2024-01-01T00:00:00Z",
}
originalUser := provider.googleWorkspaceUserToOriginalUser(gwUser)
// Verify basic fields
if originalUser.Id != "user-123" {
t.Errorf("Expected Id to be 'user-123', got '%s'", originalUser.Id)
}
if originalUser.Name != "john.doe@example.com" {
t.Errorf("Expected Name to be 'john.doe@example.com', got '%s'", originalUser.Name)
}
if originalUser.Email != "john.doe@example.com" {
t.Errorf("Expected Email to be 'john.doe@example.com', got '%s'", originalUser.Email)
}
if originalUser.DisplayName != "John Doe" {
t.Errorf("Expected DisplayName to be 'John Doe', got '%s'", originalUser.DisplayName)
}
if originalUser.FirstName != "John" {
t.Errorf("Expected FirstName to be 'John', got '%s'", originalUser.FirstName)
}
if originalUser.LastName != "Doe" {
t.Errorf("Expected LastName to be 'Doe', got '%s'", originalUser.LastName)
}
if originalUser.Avatar != "https://example.com/avatar.jpg" {
t.Errorf("Expected Avatar to be 'https://example.com/avatar.jpg', got '%s'", originalUser.Avatar)
}
if originalUser.IsForbidden != false {
t.Errorf("Expected IsForbidden to be false for non-suspended user, got %v", originalUser.IsForbidden)
}
if originalUser.IsAdmin != true {
t.Errorf("Expected IsAdmin to be true, got %v", originalUser.IsAdmin)
}
// Test case 2: Suspended Google Workspace user
suspendedUser := &admin.User{
Id: "user-456",
PrimaryEmail: "jane.doe@example.com",
Name: &admin.UserName{
FullName: "Jane Doe",
},
Suspended: true,
}
suspendedOriginalUser := provider.googleWorkspaceUserToOriginalUser(suspendedUser)
if suspendedOriginalUser.IsForbidden != true {
t.Errorf("Expected IsForbidden to be true for suspended user, got %v", suspendedOriginalUser.IsForbidden)
}
// Test case 3: User with no Name object (should not panic)
minimalUser := &admin.User{
Id: "user-789",
PrimaryEmail: "bob@example.com",
}
minimalOriginalUser := provider.googleWorkspaceUserToOriginalUser(minimalUser)
if minimalOriginalUser.DisplayName != "" {
t.Errorf("Expected DisplayName to be empty for minimal user, got '%s'", minimalOriginalUser.DisplayName)
}
// Test case 4: Display name construction from first/last name when FullName is empty
noFullNameUser := &admin.User{
Id: "user-101",
PrimaryEmail: "alice@example.com",
Name: &admin.UserName{
GivenName: "Alice",
FamilyName: "Jones",
},
}
noFullNameOriginalUser := provider.googleWorkspaceUserToOriginalUser(noFullNameUser)
if noFullNameOriginalUser.DisplayName != "Alice Jones" {
t.Errorf("Expected DisplayName to be constructed as 'Alice Jones', got '%s'", noFullNameOriginalUser.DisplayName)
}
}
func TestGoogleWorkspaceGroupToOriginalGroup(t *testing.T) {
provider := &GoogleWorkspaceSyncerProvider{
Syncer: &Syncer{},
}
// Test case 1: Full Google Workspace group with all fields
gwGroup := &admin.Group{
Id: "group-123",
Email: "team@example.com",
Name: "Engineering Team",
Description: "All engineering staff",
}
originalGroup := provider.googleWorkspaceGroupToOriginalGroup(gwGroup)
// Verify all fields
if originalGroup.Id != "group-123" {
t.Errorf("Expected Id to be 'group-123', got '%s'", originalGroup.Id)
}
if originalGroup.Name != "team@example.com" {
t.Errorf("Expected Name to be 'team@example.com', got '%s'", originalGroup.Name)
}
if originalGroup.DisplayName != "Engineering Team" {
t.Errorf("Expected DisplayName to be 'Engineering Team', got '%s'", originalGroup.DisplayName)
}
if originalGroup.Description != "All engineering staff" {
t.Errorf("Expected Description to be 'All engineering staff', got '%s'", originalGroup.Description)
}
if originalGroup.Email != "team@example.com" {
t.Errorf("Expected Email to be 'team@example.com', got '%s'", originalGroup.Email)
}
// Test case 2: Minimal group
minimalGroup := &admin.Group{
Id: "group-456",
Email: "minimal@example.com",
}
minimalOriginalGroup := provider.googleWorkspaceGroupToOriginalGroup(minimalGroup)
if minimalOriginalGroup.DisplayName != "" {
t.Errorf("Expected DisplayName to be empty for minimal group, got '%s'", minimalOriginalGroup.DisplayName)
}
if minimalOriginalGroup.Description != "" {
t.Errorf("Expected Description to be empty for minimal group, got '%s'", minimalOriginalGroup.Description)
}
}
func TestGetSyncerProviderGoogleWorkspace(t *testing.T) {
syncer := &Syncer{
Type: "Google Workspace",
Host: "admin@example.com",
}
provider := GetSyncerProvider(syncer)
if _, ok := provider.(*GoogleWorkspaceSyncerProvider); !ok {
t.Errorf("Expected GoogleWorkspaceSyncerProvider for type 'Google Workspace', got %T", provider)
}
}
func TestGoogleWorkspaceSyncerProviderEmptyMethods(t *testing.T) {
provider := &GoogleWorkspaceSyncerProvider{
Syncer: &Syncer{},
}
// Test AddUser returns error
_, err := provider.AddUser(&OriginalUser{})
if err == nil {
t.Error("Expected AddUser to return error for read-only syncer")
}
// Test UpdateUser returns error
_, err = provider.UpdateUser(&OriginalUser{})
if err == nil {
t.Error("Expected UpdateUser to return error for read-only syncer")
}
// Test Close returns no error
err = provider.Close()
if err != nil {
t.Errorf("Expected Close to return nil, got error: %v", err)
}
// Test InitAdapter returns no error
err = provider.InitAdapter()
if err != nil {
t.Errorf("Expected InitAdapter to return nil, got error: %v", err)
}
}

121
object/syncer_group.go Normal file
View File

@@ -0,0 +1,121 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"fmt"
"github.com/casdoor/casdoor/util"
)
func (syncer *Syncer) getOriginalGroups() ([]*OriginalGroup, error) {
provider := GetSyncerProvider(syncer)
return provider.GetOriginalGroups()
}
func (syncer *Syncer) createGroupFromOriginalGroup(originalGroup *OriginalGroup) *Group {
group := &Group{
Owner: syncer.Organization,
Name: originalGroup.Name,
CreatedTime: util.GetCurrentTime(),
UpdatedTime: util.GetCurrentTime(),
DisplayName: originalGroup.DisplayName,
Type: originalGroup.Type,
Manager: originalGroup.Manager,
IsEnabled: true,
IsTopGroup: true,
}
if originalGroup.Email != "" {
group.ContactEmail = originalGroup.Email
}
return group
}
func (syncer *Syncer) syncGroups() error {
fmt.Printf("Running syncGroups()..\n")
// Get existing groups from Casdoor
groups, err := GetGroups(syncer.Organization)
if err != nil {
line := fmt.Sprintf("[%s] %s\n", util.GetCurrentTime(), err.Error())
_, err2 := updateSyncerErrorText(syncer, line)
if err2 != nil {
panic(err2)
}
return err
}
// Get groups from the external system
oGroups, err := syncer.getOriginalGroups()
if err != nil {
line := fmt.Sprintf("[%s] %s\n", util.GetCurrentTime(), err.Error())
_, err2 := updateSyncerErrorText(syncer, line)
if err2 != nil {
panic(err2)
}
return err
}
fmt.Printf("Groups: %d, oGroups: %d\n", len(groups), len(oGroups))
// Create a map of existing groups by name
myGroups := map[string]*Group{}
for _, group := range groups {
myGroups[group.Name] = group
}
// Sync groups from external system to Casdoor
newGroups := []*Group{}
for _, oGroup := range oGroups {
if _, ok := myGroups[oGroup.Name]; !ok {
newGroup := syncer.createGroupFromOriginalGroup(oGroup)
fmt.Printf("New group: %v\n", newGroup)
newGroups = append(newGroups, newGroup)
} else {
// Group already exists, could update it here if needed
existingGroup := myGroups[oGroup.Name]
// Update group display name and other fields if they've changed
if existingGroup.DisplayName != oGroup.DisplayName {
existingGroup.DisplayName = oGroup.DisplayName
existingGroup.UpdatedTime = util.GetCurrentTime()
_, err = UpdateGroup(existingGroup.GetId(), existingGroup)
if err != nil {
fmt.Printf("Failed to update group %s: %v\n", existingGroup.Name, err)
} else {
fmt.Printf("Updated group: %s\n", existingGroup.Name)
}
}
}
}
if len(newGroups) != 0 {
_, err = AddGroupsInBatch(newGroups)
if err != nil {
return err
}
}
return nil
}
func (syncer *Syncer) syncGroupsNoError() {
err := syncer.syncGroups()
if err != nil {
fmt.Printf("syncGroupsNoError() error: %s\n", err.Error())
}
}

View File

@@ -14,6 +14,17 @@
package object
// OriginalGroup represents a group from an external system
type OriginalGroup struct {
Id string
Name string
DisplayName string
Description string
Type string
Manager string
Email string
}
// SyncerProvider defines the interface that all syncer implementations must satisfy.
// Different syncer types (Database, Keycloak, WeCom, Azure AD) implement this interface.
type SyncerProvider interface {
@@ -23,6 +34,12 @@ type SyncerProvider interface {
// GetOriginalUsers retrieves all users from the external system
GetOriginalUsers() ([]*OriginalUser, error)
// GetOriginalGroups retrieves all groups from the external system
GetOriginalGroups() ([]*OriginalGroup, error)
// GetOriginalUserGroups retrieves the group IDs that a user belongs to
GetOriginalUserGroups(userId string) ([]string, error)
// AddUser adds a new user to the external system
AddUser(user *OriginalUser) (bool, error)
@@ -49,6 +66,14 @@ func GetSyncerProvider(syncer *Syncer) SyncerProvider {
return &ActiveDirectorySyncerProvider{Syncer: syncer}
case "DingTalk":
return &DingtalkSyncerProvider{Syncer: syncer}
case "Lark":
return &LarkSyncerProvider{Syncer: syncer}
case "Okta":
return &OktaSyncerProvider{Syncer: syncer}
case "SCIM":
return &SCIMSyncerProvider{Syncer: syncer}
case "AWS IAM":
return &AwsIamSyncerProvider{Syncer: syncer}
case "Keycloak":
return &KeycloakSyncerProvider{
DatabaseSyncerProvider: DatabaseSyncerProvider{Syncer: syncer},

View File

@@ -29,3 +29,15 @@ func (p *KeycloakSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error) {
// Note: Keycloak-specific user mapping is handled in syncer_util.go
// via getOriginalUsersFromMap which checks syncer.Type == "Keycloak"
// GetOriginalGroups retrieves all groups from Keycloak (not implemented yet)
func (p *KeycloakSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Keycloak group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *KeycloakSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Keycloak user group membership sync
return []string{}, nil
}

429
object/syncer_lark.go Normal file
View File

@@ -0,0 +1,429 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/casdoor/casdoor/util"
)
// LarkSyncerProvider implements SyncerProvider for Lark API-based syncers
type LarkSyncerProvider struct {
Syncer *Syncer
}
// InitAdapter initializes the Lark syncer (no database adapter needed)
func (p *LarkSyncerProvider) InitAdapter() error {
// Lark syncer doesn't need database adapter
return nil
}
// GetOriginalUsers retrieves all users from Lark API
func (p *LarkSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error) {
return p.getLarkUsers()
}
// AddUser adds a new user to Lark (not supported for read-only API)
func (p *LarkSyncerProvider) AddUser(user *OriginalUser) (bool, error) {
// Lark syncer is typically read-only
return false, fmt.Errorf("adding users to Lark is not supported")
}
// UpdateUser updates an existing user in Lark (not supported for read-only API)
func (p *LarkSyncerProvider) UpdateUser(user *OriginalUser) (bool, error) {
// Lark syncer is typically read-only
return false, fmt.Errorf("updating users in Lark is not supported")
}
// TestConnection tests the Lark API connection
func (p *LarkSyncerProvider) TestConnection() error {
_, err := p.getLarkAccessToken()
return err
}
// Close closes any open connections (no-op for Lark API-based syncer)
func (p *LarkSyncerProvider) Close() error {
// Lark syncer doesn't maintain persistent connections
return nil
}
type LarkAccessTokenResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
TenantAccessToken string `json:"tenant_access_token"`
Expire int `json:"expire"`
}
type LarkUser struct {
UserId string `json:"user_id"`
UnionId string `json:"union_id"`
OpenId string `json:"open_id"`
Name string `json:"name"`
EnName string `json:"en_name"`
Email string `json:"email"`
Mobile string `json:"mobile"`
Gender int `json:"gender"`
Avatar *LarkAvatar `json:"avatar"`
Status *LarkStatus `json:"status"`
DepartmentIds []string `json:"department_ids"`
JobTitle string `json:"job_title"`
}
type LarkAvatar struct {
Avatar72 string `json:"avatar_72"`
Avatar240 string `json:"avatar_240"`
Avatar640 string `json:"avatar_640"`
AvatarOrigin string `json:"avatar_origin"`
}
type LarkStatus struct {
IsFrozen bool `json:"is_frozen"`
IsResigned bool `json:"is_resigned"`
IsActivated bool `json:"is_activated"`
IsExited bool `json:"is_exited"`
}
type LarkUserListResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Items []*LarkUser `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
} `json:"data"`
}
type LarkDeptListResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Items []struct {
DepartmentId string `json:"department_id"`
} `json:"items"`
HasMore bool `json:"has_more"`
PageToken string `json:"page_token"`
} `json:"data"`
}
// getLarkDomain returns the Lark API domain based on whether global endpoint is used
func (p *LarkSyncerProvider) getLarkDomain() string {
// syncer.Host can be used to specify custom endpoint
// If empty, default to global endpoint (larksuite.com)
if p.Syncer.Host != "" {
return p.Syncer.Host
}
return "https://open.larksuite.com"
}
// getLarkAccessToken gets access token from Lark API
func (p *LarkSyncerProvider) getLarkAccessToken() (string, error) {
// syncer.User should be the app_id
// syncer.Password should be the app_secret
appId := p.Syncer.User
if appId == "" {
return "", fmt.Errorf("app_id (user field) is required for Lark syncer")
}
appSecret := p.Syncer.Password
if appSecret == "" {
return "", fmt.Errorf("app_secret (password field) is required for Lark syncer")
}
domain := p.getLarkDomain()
apiUrl := fmt.Sprintf("%s/open-apis/auth/v3/tenant_access_token/internal", domain)
postData := map[string]string{
"app_id": appId,
"app_secret": appSecret,
}
data, err := p.postJSON(apiUrl, postData)
if err != nil {
return "", err
}
var tokenResp LarkAccessTokenResp
err = json.Unmarshal(data, &tokenResp)
if err != nil {
return "", err
}
if tokenResp.Code != 0 {
return "", fmt.Errorf("failed to get access token: code=%d, msg=%s",
tokenResp.Code, tokenResp.Msg)
}
return tokenResp.TenantAccessToken, nil
}
// getLarkDepartments gets all department IDs from Lark API
func (p *LarkSyncerProvider) getLarkDepartments(accessToken string) ([]string, error) {
domain := p.getLarkDomain()
allDeptIds := []string{"0"} // Start with root department
pageToken := ""
for {
apiUrl := fmt.Sprintf("%s/open-apis/contact/v3/departments?parent_department_id=0&fetch_child=true&page_size=50", domain)
if pageToken != "" {
apiUrl += fmt.Sprintf("&page_token=%s", pageToken)
}
data, err := p.getWithAuth(apiUrl, accessToken)
if err != nil {
return nil, err
}
var deptResp LarkDeptListResp
err = json.Unmarshal(data, &deptResp)
if err != nil {
return nil, err
}
if deptResp.Code != 0 {
return nil, fmt.Errorf("failed to get departments: code=%d, msg=%s",
deptResp.Code, deptResp.Msg)
}
for _, dept := range deptResp.Data.Items {
allDeptIds = append(allDeptIds, dept.DepartmentId)
}
if !deptResp.Data.HasMore {
break
}
pageToken = deptResp.Data.PageToken
}
return allDeptIds, nil
}
// getLarkUsersFromDept gets users from a specific department
func (p *LarkSyncerProvider) getLarkUsersFromDept(accessToken string, deptId string) ([]*LarkUser, error) {
domain := p.getLarkDomain()
allUsers := []*LarkUser{}
pageToken := ""
for {
apiUrl := fmt.Sprintf("%s/open-apis/contact/v3/users/find_by_department?department_id=%s&page_size=50", domain, deptId)
if pageToken != "" {
apiUrl += fmt.Sprintf("&page_token=%s", pageToken)
}
data, err := p.getWithAuth(apiUrl, accessToken)
if err != nil {
return nil, err
}
var userResp LarkUserListResp
err = json.Unmarshal(data, &userResp)
if err != nil {
return nil, err
}
if userResp.Code != 0 {
return nil, fmt.Errorf("failed to get users from dept %s: code=%d, msg=%s",
deptId, userResp.Code, userResp.Msg)
}
allUsers = append(allUsers, userResp.Data.Items...)
if !userResp.Data.HasMore {
break
}
pageToken = userResp.Data.PageToken
}
return allUsers, nil
}
// postJSON sends a POST request with JSON body
func (p *LarkSyncerProvider) postJSON(url string, data interface{}) ([]byte, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonData))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respData, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respData, nil
}
// getWithAuth sends a GET request with authorization header
func (p *LarkSyncerProvider) getWithAuth(url string, accessToken string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}
// getLarkUsers gets all users from Lark API
func (p *LarkSyncerProvider) getLarkUsers() ([]*OriginalUser, error) {
// Get access token
accessToken, err := p.getLarkAccessToken()
if err != nil {
return nil, err
}
// Get all departments
deptIds, err := p.getLarkDepartments(accessToken)
if err != nil {
return nil, err
}
// Get users from all departments (deduplicate by user_id)
userMap := make(map[string]*LarkUser)
for _, deptId := range deptIds {
users, err := p.getLarkUsersFromDept(accessToken, deptId)
if err != nil {
return nil, err
}
for _, user := range users {
// Deduplicate users by user_id
if _, exists := userMap[user.UserId]; !exists {
userMap[user.UserId] = user
}
}
}
// Convert Lark users to Casdoor OriginalUser
originalUsers := []*OriginalUser{}
for _, larkUser := range userMap {
originalUser := p.larkUserToOriginalUser(larkUser)
originalUsers = append(originalUsers, originalUser)
}
return originalUsers, nil
}
// larkUserToOriginalUser converts Lark user to Casdoor OriginalUser
func (p *LarkSyncerProvider) larkUserToOriginalUser(larkUser *LarkUser) *OriginalUser {
// Use user_id as name, fallback to union_id or open_id
userName := larkUser.UserId
if userName == "" && larkUser.UnionId != "" {
userName = larkUser.UnionId
}
if userName == "" && larkUser.OpenId != "" {
userName = larkUser.OpenId
}
user := &OriginalUser{
Id: larkUser.UserId,
Name: userName,
DisplayName: larkUser.Name,
Email: larkUser.Email,
Phone: larkUser.Mobile,
Title: larkUser.JobTitle,
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
Lark: larkUser.UserId, // Link Lark provider account
}
// Set avatar if available
if larkUser.Avatar != nil {
if larkUser.Avatar.Avatar240 != "" {
user.Avatar = larkUser.Avatar.Avatar240
} else if larkUser.Avatar.Avatar72 != "" {
user.Avatar = larkUser.Avatar.Avatar72
}
}
// Set gender
switch larkUser.Gender {
case 1:
user.Gender = "Male"
case 2:
user.Gender = "Female"
default:
user.Gender = ""
}
// Set IsForbidden based on status
// User is forbidden if frozen, resigned, not activated, or exited
if larkUser.Status != nil {
if larkUser.Status.IsFrozen || larkUser.Status.IsResigned || !larkUser.Status.IsActivated || larkUser.Status.IsExited {
user.IsForbidden = true
} else {
user.IsForbidden = false
}
}
// Set CreatedTime to current time if not set
if user.CreatedTime == "" {
user.CreatedTime = util.GetCurrentTime()
}
return user
}
// GetOriginalGroups retrieves all groups from Lark (not implemented yet)
func (p *LarkSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Lark group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *LarkSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Lark user group membership sync
return []string{}, nil
}

310
object/syncer_okta.go Normal file
View File

@@ -0,0 +1,310 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/casdoor/casdoor/util"
)
// OktaSyncerProvider implements SyncerProvider for Okta API-based syncers
type OktaSyncerProvider struct {
Syncer *Syncer
}
// InitAdapter initializes the Okta syncer (no database adapter needed)
func (p *OktaSyncerProvider) InitAdapter() error {
// Okta syncer doesn't need database adapter
return nil
}
// GetOriginalUsers retrieves all users from Okta API
func (p *OktaSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error) {
return p.getOktaOriginalUsers()
}
// AddUser adds a new user to Okta (not supported for read-only API)
func (p *OktaSyncerProvider) AddUser(user *OriginalUser) (bool, error) {
// Okta syncer is typically read-only
return false, fmt.Errorf("adding users to Okta is not supported")
}
// UpdateUser updates an existing user in Okta (not supported for read-only API)
func (p *OktaSyncerProvider) UpdateUser(user *OriginalUser) (bool, error) {
// Okta syncer is typically read-only
return false, fmt.Errorf("updating users in Okta is not supported")
}
// TestConnection tests the Okta API connection
func (p *OktaSyncerProvider) TestConnection() error {
// Try to fetch first page of users to verify connection
_, _, err := p.getOktaUsers("")
return err
}
// Close closes any open connections (no-op for Okta API-based syncer)
func (p *OktaSyncerProvider) Close() error {
// Okta syncer doesn't maintain persistent connections
return nil
}
// OktaUser represents a user from Okta API
type OktaUser struct {
Id string `json:"id"`
Status string `json:"status"`
Created string `json:"created"`
Profile struct {
Login string `json:"login"`
Email string `json:"email"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
DisplayName string `json:"displayName"`
MobilePhone string `json:"mobilePhone"`
PrimaryPhone string `json:"primaryPhone"`
StreetAddress string `json:"streetAddress"`
City string `json:"city"`
State string `json:"state"`
ZipCode string `json:"zipCode"`
CountryCode string `json:"countryCode"`
PostalAddress string `json:"postalAddress"`
PreferredLanguage string `json:"preferredLanguage"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
Title string `json:"title"`
Department string `json:"department"`
Organization string `json:"organization"`
} `json:"profile"`
}
// parseLinkHeader parses the HTTP Link header
// Format: <https://example.com/api/v1/users?after=xyz>; rel="next"
func parseLinkHeader(header string) map[string]string {
links := make(map[string]string)
parts := strings.Split(header, ",")
for _, part := range parts {
section := strings.Split(strings.TrimSpace(part), ";")
if len(section) != 2 {
continue
}
url := strings.Trim(strings.TrimSpace(section[0]), "<>")
rel := strings.TrimSpace(section[1])
if strings.HasPrefix(rel, "rel=\"") && strings.HasSuffix(rel, "\"") {
relValue := rel[5 : len(rel)-1]
links[relValue] = url
}
}
return links
}
// getOktaUsers retrieves users from Okta API with pagination support
// Returns users and the next page link (if any)
func (p *OktaSyncerProvider) getOktaUsers(nextLink string) ([]*OktaUser, string, error) {
// syncer.Host should be the Okta domain (e.g., "dev-12345.okta.com" or full URL)
// syncer.Password should be the API token
domain := p.Syncer.Host
if domain == "" {
return nil, "", fmt.Errorf("Okta domain (host field) is required for Okta syncer")
}
apiToken := p.Syncer.Password
if apiToken == "" {
return nil, "", fmt.Errorf("API token (password field) is required for Okta syncer")
}
// Construct API URL
var apiUrl string
if nextLink != "" {
apiUrl = nextLink
} else {
// Remove https:// or http:// prefix if present in domain
domain = strings.TrimPrefix(strings.TrimPrefix(domain, "https://"), "http://")
apiUrl = fmt.Sprintf("https://%s/api/v1/users?limit=200", domain)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", apiUrl, nil)
if err != nil {
return nil, "", err
}
req.Header.Set("Authorization", "SSWS "+apiToken)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, "", fmt.Errorf("failed to get users from Okta: status=%d, body=%s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
var users []*OktaUser
err = json.Unmarshal(body, &users)
if err != nil {
return nil, "", err
}
// Parse Link header for next page
// Link header format: <https://...>; rel="next"
nextPageLink := ""
linkHeader := resp.Header.Get("Link")
if linkHeader != "" {
links := parseLinkHeader(linkHeader)
if next, ok := links["next"]; ok {
nextPageLink = next
}
}
return users, nextPageLink, nil
}
// oktaUserToOriginalUser converts Okta user to Casdoor OriginalUser
func (p *OktaSyncerProvider) oktaUserToOriginalUser(oktaUser *OktaUser) *OriginalUser {
user := &OriginalUser{
Id: oktaUser.Id,
Name: oktaUser.Profile.Login,
DisplayName: oktaUser.Profile.DisplayName,
FirstName: oktaUser.Profile.FirstName,
LastName: oktaUser.Profile.LastName,
Email: oktaUser.Profile.Email,
Phone: oktaUser.Profile.MobilePhone,
Title: oktaUser.Profile.Title,
Language: oktaUser.Profile.PreferredLanguage,
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
}
// Build address from street, city, state, zip
if oktaUser.Profile.StreetAddress != "" {
user.Address = append(user.Address, oktaUser.Profile.StreetAddress)
}
if oktaUser.Profile.City != "" {
user.Address = append(user.Address, oktaUser.Profile.City)
}
if oktaUser.Profile.State != "" {
user.Address = append(user.Address, oktaUser.Profile.State)
}
if oktaUser.Profile.ZipCode != "" {
user.Address = append(user.Address, oktaUser.Profile.ZipCode)
}
// Store additional properties
if oktaUser.Profile.Department != "" {
user.Properties["department"] = oktaUser.Profile.Department
}
if oktaUser.Profile.Organization != "" {
user.Properties["organization"] = oktaUser.Profile.Organization
}
if oktaUser.Profile.Timezone != "" {
user.Properties["timezone"] = oktaUser.Profile.Timezone
}
// Set IsForbidden based on status
// Okta status values: STAGED, PROVISIONED, ACTIVE, RECOVERY, PASSWORD_EXPIRED, LOCKED_OUT, SUSPENDED, DEPROVISIONED
if oktaUser.Status == "SUSPENDED" || oktaUser.Status == "DEPROVISIONED" || oktaUser.Status == "LOCKED_OUT" {
user.IsForbidden = true
} else {
user.IsForbidden = false
}
// If display name is empty, construct from first and last name
if user.DisplayName == "" && (user.FirstName != "" || user.LastName != "") {
user.DisplayName = strings.TrimSpace(fmt.Sprintf("%s %s", user.FirstName, user.LastName))
}
// If email is empty, use login as email (typically login is an email)
if user.Email == "" && oktaUser.Profile.Login != "" {
user.Email = oktaUser.Profile.Login
}
// If mobile phone is empty, try primary phone
if user.Phone == "" && oktaUser.Profile.PrimaryPhone != "" {
user.Phone = oktaUser.Profile.PrimaryPhone
}
// Set CreatedTime to current time if not set
if user.CreatedTime == "" {
user.CreatedTime = util.GetCurrentTime()
}
return user
}
// getOktaOriginalUsers is the main entry point for Okta syncer
func (p *OktaSyncerProvider) getOktaOriginalUsers() ([]*OriginalUser, error) {
allUsers := []*OktaUser{}
nextLink := ""
// Fetch all users with pagination
for {
users, next, err := p.getOktaUsers(nextLink)
if err != nil {
return nil, err
}
allUsers = append(allUsers, users...)
// If there's no next link, we've fetched all users
if next == "" {
break
}
nextLink = next
}
// Convert Okta users to Casdoor OriginalUser
originalUsers := []*OriginalUser{}
for _, oktaUser := range allUsers {
originalUser := p.oktaUserToOriginalUser(oktaUser)
originalUsers = append(originalUsers, originalUser)
}
return originalUsers, nil
}
// GetOriginalGroups retrieves all groups from Okta (not implemented yet)
func (p *OktaSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement Okta group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *OktaSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement Okta user group membership sync
return []string{}, nil
}

349
object/syncer_scim.go Normal file
View File

@@ -0,0 +1,349 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/casdoor/casdoor/util"
)
// SCIMSyncerProvider implements SyncerProvider for SCIM 2.0 API-based syncers
type SCIMSyncerProvider struct {
Syncer *Syncer
}
// InitAdapter initializes the SCIM syncer (no database adapter needed)
func (p *SCIMSyncerProvider) InitAdapter() error {
// SCIM syncer doesn't need database adapter
return nil
}
// GetOriginalUsers retrieves all users from SCIM API
func (p *SCIMSyncerProvider) GetOriginalUsers() ([]*OriginalUser, error) {
return p.getSCIMUsers()
}
// AddUser adds a new user to SCIM (not supported for read-only API)
func (p *SCIMSyncerProvider) AddUser(user *OriginalUser) (bool, error) {
// SCIM syncer is typically read-only
return false, fmt.Errorf("adding users to SCIM is not supported")
}
// UpdateUser updates an existing user in SCIM (not supported for read-only API)
func (p *SCIMSyncerProvider) UpdateUser(user *OriginalUser) (bool, error) {
// SCIM syncer is typically read-only
return false, fmt.Errorf("updating users in SCIM is not supported")
}
// TestConnection tests the SCIM API connection
func (p *SCIMSyncerProvider) TestConnection() error {
// Test by trying to fetch users with a limit of 1
endpoint := p.buildSCIMEndpoint()
endpoint = fmt.Sprintf("%s?startIndex=1&count=1", endpoint)
req, err := p.createSCIMRequest("GET", endpoint, nil)
if err != nil {
return err
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("SCIM connection test failed: status=%d, body=%s", resp.StatusCode, string(body))
}
return nil
}
// Close closes any open connections (no-op for SCIM API-based syncer)
func (p *SCIMSyncerProvider) Close() error {
// SCIM syncer doesn't maintain persistent connections
return nil
}
// SCIMName represents a SCIM user name structure
type SCIMName struct {
FamilyName string `json:"familyName"`
GivenName string `json:"givenName"`
Formatted string `json:"formatted"`
}
// SCIMEmail represents a SCIM user email structure
type SCIMEmail struct {
Value string `json:"value"`
Type string `json:"type"`
Primary bool `json:"primary"`
}
// SCIMPhoneNumber represents a SCIM user phone number structure
type SCIMPhoneNumber struct {
Value string `json:"value"`
Type string `json:"type"`
Primary bool `json:"primary"`
}
// SCIMAddress represents a SCIM user address structure
type SCIMAddress struct {
StreetAddress string `json:"streetAddress"`
Locality string `json:"locality"`
Region string `json:"region"`
PostalCode string `json:"postalCode"`
Country string `json:"country"`
Formatted string `json:"formatted"`
Type string `json:"type"`
Primary bool `json:"primary"`
}
// SCIMUser represents a SCIM 2.0 user resource
type SCIMUser struct {
ID string `json:"id"`
ExternalID string `json:"externalId"`
UserName string `json:"userName"`
Name SCIMName `json:"name"`
DisplayName string `json:"displayName"`
NickName string `json:"nickName"`
ProfileURL string `json:"profileUrl"`
Title string `json:"title"`
UserType string `json:"userType"`
PreferredLan string `json:"preferredLanguage"`
Locale string `json:"locale"`
Timezone string `json:"timezone"`
Active bool `json:"active"`
Emails []SCIMEmail `json:"emails"`
PhoneNumbers []SCIMPhoneNumber `json:"phoneNumbers"`
Addresses []SCIMAddress `json:"addresses"`
}
// SCIMListResponse represents a SCIM list response
type SCIMListResponse struct {
TotalResults int `json:"totalResults"`
ItemsPerPage int `json:"itemsPerPage"`
StartIndex int `json:"startIndex"`
Resources []*SCIMUser `json:"Resources"`
}
// buildSCIMEndpoint builds the SCIM API endpoint URL
func (p *SCIMSyncerProvider) buildSCIMEndpoint() string {
// syncer.Host should be the SCIM server URL (e.g., https://example.com/scim/v2)
host := strings.TrimSuffix(p.Syncer.Host, "/")
return fmt.Sprintf("%s/Users", host)
}
// createSCIMRequest creates an HTTP request with proper authentication
func (p *SCIMSyncerProvider) createSCIMRequest(method, url string, body io.Reader) (*http.Request, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
// Set SCIM headers
req.Header.Set("Content-Type", "application/scim+json")
req.Header.Set("Accept", "application/scim+json")
// Add authentication
// syncer.User should be the authentication token or username
// syncer.Password should be the password or API key
if p.Syncer.User != "" && p.Syncer.Password != "" {
// Try Basic Auth
req.SetBasicAuth(p.Syncer.User, p.Syncer.Password)
} else if p.Syncer.Password != "" {
// Try Bearer token (assuming password field contains the token)
req.Header.Set("Authorization", "Bearer "+p.Syncer.Password)
} else if p.Syncer.User != "" {
// Try Bearer token (assuming user field contains the token)
req.Header.Set("Authorization", "Bearer "+p.Syncer.User)
}
return req, nil
}
// getSCIMUsers retrieves all users from SCIM API with pagination
func (p *SCIMSyncerProvider) getSCIMUsers() ([]*OriginalUser, error) {
allUsers := []*SCIMUser{}
startIndex := 1
count := 100 // Fetch 100 users per page
for {
endpoint := p.buildSCIMEndpoint()
endpoint = fmt.Sprintf("%s?startIndex=%d&count=%d", endpoint, startIndex, count)
req, err := p.createSCIMRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("failed to get users: status=%d, body=%s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var listResp SCIMListResponse
err = json.Unmarshal(body, &listResp)
if err != nil {
return nil, err
}
allUsers = append(allUsers, listResp.Resources...)
// Check if we've fetched all users
if len(allUsers) >= listResp.TotalResults {
break
}
// Move to the next page
startIndex += count
}
// Convert SCIM users to Casdoor OriginalUser
originalUsers := []*OriginalUser{}
for _, scimUser := range allUsers {
originalUser := p.scimUserToOriginalUser(scimUser)
originalUsers = append(originalUsers, originalUser)
}
return originalUsers, nil
}
// scimUserToOriginalUser converts SCIM user to Casdoor OriginalUser
func (p *SCIMSyncerProvider) scimUserToOriginalUser(scimUser *SCIMUser) *OriginalUser {
user := &OriginalUser{
Id: scimUser.ID,
ExternalId: scimUser.ExternalID,
Name: scimUser.UserName,
DisplayName: scimUser.DisplayName,
FirstName: scimUser.Name.GivenName,
LastName: scimUser.Name.FamilyName,
Title: scimUser.Title,
Language: scimUser.PreferredLan,
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
}
// If display name is from name structure
if user.DisplayName == "" && scimUser.Name.Formatted != "" {
user.DisplayName = scimUser.Name.Formatted
}
// If display name is still empty, construct from first and last name
if user.DisplayName == "" && (user.FirstName != "" || user.LastName != "") {
user.DisplayName = strings.TrimSpace(fmt.Sprintf("%s %s", user.FirstName, user.LastName))
}
// Extract primary email or first email
if len(scimUser.Emails) > 0 {
for _, email := range scimUser.Emails {
if email.Primary {
user.Email = email.Value
break
}
}
// If no primary email, use the first one
if user.Email == "" && len(scimUser.Emails) > 0 {
user.Email = scimUser.Emails[0].Value
}
}
// Extract primary phone or first phone
if len(scimUser.PhoneNumbers) > 0 {
for _, phone := range scimUser.PhoneNumbers {
if phone.Primary {
user.Phone = phone.Value
break
}
}
// If no primary phone, use the first one
if user.Phone == "" && len(scimUser.PhoneNumbers) > 0 {
user.Phone = scimUser.PhoneNumbers[0].Value
}
}
// Extract primary address or first address
if len(scimUser.Addresses) > 0 {
for _, addr := range scimUser.Addresses {
if addr.Primary {
if addr.Formatted != "" {
user.Address = []string{addr.Formatted}
} else {
user.Address = []string{addr.StreetAddress, addr.Locality, addr.Region, addr.PostalCode, addr.Country}
}
user.Location = addr.Locality
user.Region = addr.Region
break
}
}
// If no primary address, use the first one
if len(user.Address) == 0 && len(scimUser.Addresses) > 0 {
addr := scimUser.Addresses[0]
if addr.Formatted != "" {
user.Address = []string{addr.Formatted}
} else {
user.Address = []string{addr.StreetAddress, addr.Locality, addr.Region, addr.PostalCode, addr.Country}
}
user.Location = addr.Locality
user.Region = addr.Region
}
}
// Set IsForbidden based on Active status
user.IsForbidden = !scimUser.Active
// Set CreatedTime to current time if not set
if user.CreatedTime == "" {
user.CreatedTime = util.GetCurrentTime()
}
return user
}
// GetOriginalGroups retrieves all groups from SCIM (not implemented yet)
func (p *SCIMSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement SCIM group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *SCIMSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement SCIM user group membership sync
return []string{}, nil
}

198
object/syncer_scim_test.go Normal file
View File

@@ -0,0 +1,198 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"testing"
)
func TestSCIMUserToOriginalUser(t *testing.T) {
provider := &SCIMSyncerProvider{
Syncer: &Syncer{
Host: "https://example.com/scim/v2",
User: "testuser",
Password: "testtoken",
},
}
// Test case 1: Full SCIM user with all fields
scimUser := &SCIMUser{
ID: "user-123",
ExternalID: "ext-123",
UserName: "john.doe",
DisplayName: "John Doe",
Name: SCIMName{
GivenName: "John",
FamilyName: "Doe",
Formatted: "John Doe",
},
Title: "Software Engineer",
PreferredLan: "en-US",
Active: true,
Emails: []SCIMEmail{
{Value: "john.doe@example.com", Primary: true, Type: "work"},
{Value: "john@personal.com", Primary: false, Type: "home"},
},
PhoneNumbers: []SCIMPhoneNumber{
{Value: "+1-555-1234", Primary: true, Type: "work"},
{Value: "+1-555-5678", Primary: false, Type: "mobile"},
},
Addresses: []SCIMAddress{
{
StreetAddress: "123 Main St",
Locality: "San Francisco",
Region: "CA",
PostalCode: "94102",
Country: "USA",
Formatted: "123 Main St, San Francisco, CA 94102, USA",
Primary: true,
Type: "work",
},
},
}
originalUser := provider.scimUserToOriginalUser(scimUser)
// Verify basic fields
if originalUser.Id != "user-123" {
t.Errorf("Expected Id to be 'user-123', got '%s'", originalUser.Id)
}
if originalUser.ExternalId != "ext-123" {
t.Errorf("Expected ExternalId to be 'ext-123', got '%s'", originalUser.ExternalId)
}
if originalUser.Name != "john.doe" {
t.Errorf("Expected Name to be 'john.doe', got '%s'", originalUser.Name)
}
if originalUser.DisplayName != "John Doe" {
t.Errorf("Expected DisplayName to be 'John Doe', got '%s'", originalUser.DisplayName)
}
if originalUser.FirstName != "John" {
t.Errorf("Expected FirstName to be 'John', got '%s'", originalUser.FirstName)
}
if originalUser.LastName != "Doe" {
t.Errorf("Expected LastName to be 'Doe', got '%s'", originalUser.LastName)
}
if originalUser.Title != "Software Engineer" {
t.Errorf("Expected Title to be 'Software Engineer', got '%s'", originalUser.Title)
}
if originalUser.Language != "en-US" {
t.Errorf("Expected Language to be 'en-US', got '%s'", originalUser.Language)
}
// Verify primary email is selected
if originalUser.Email != "john.doe@example.com" {
t.Errorf("Expected Email to be 'john.doe@example.com', got '%s'", originalUser.Email)
}
// Verify primary phone is selected
if originalUser.Phone != "+1-555-1234" {
t.Errorf("Expected Phone to be '+1-555-1234', got '%s'", originalUser.Phone)
}
// Verify address fields
if originalUser.Location != "San Francisco" {
t.Errorf("Expected Location to be 'San Francisco', got '%s'", originalUser.Location)
}
if originalUser.Region != "CA" {
t.Errorf("Expected Region to be 'CA', got '%s'", originalUser.Region)
}
// Verify active status is inverted to IsForbidden
if originalUser.IsForbidden != false {
t.Errorf("Expected IsForbidden to be false for active user, got %v", originalUser.IsForbidden)
}
// Test case 2: Inactive SCIM user
inactiveUser := &SCIMUser{
ID: "user-456",
UserName: "jane.doe",
Active: false,
}
inactiveOriginalUser := provider.scimUserToOriginalUser(inactiveUser)
if inactiveOriginalUser.IsForbidden != true {
t.Errorf("Expected IsForbidden to be true for inactive user, got %v", inactiveOriginalUser.IsForbidden)
}
// Test case 3: SCIM user with no primary email/phone (should use first)
noPrimaryUser := &SCIMUser{
ID: "user-789",
UserName: "bob.smith",
Emails: []SCIMEmail{
{Value: "bob@example.com", Primary: false, Type: "work"},
{Value: "bob@personal.com", Primary: false, Type: "home"},
},
PhoneNumbers: []SCIMPhoneNumber{
{Value: "+1-555-9999", Primary: false, Type: "work"},
},
}
noPrimaryOriginalUser := provider.scimUserToOriginalUser(noPrimaryUser)
if noPrimaryOriginalUser.Email != "bob@example.com" {
t.Errorf("Expected first email when no primary, got '%s'", noPrimaryOriginalUser.Email)
}
if noPrimaryOriginalUser.Phone != "+1-555-9999" {
t.Errorf("Expected first phone when no primary, got '%s'", noPrimaryOriginalUser.Phone)
}
// Test case 4: Display name construction from first/last name when empty
noDisplayNameUser := &SCIMUser{
ID: "user-101",
UserName: "alice.jones",
Name: SCIMName{
GivenName: "Alice",
FamilyName: "Jones",
},
}
noDisplayNameOriginalUser := provider.scimUserToOriginalUser(noDisplayNameUser)
if noDisplayNameOriginalUser.DisplayName != "Alice Jones" {
t.Errorf("Expected DisplayName to be constructed as 'Alice Jones', got '%s'", noDisplayNameOriginalUser.DisplayName)
}
}
func TestSCIMBuildEndpoint(t *testing.T) {
tests := []struct {
host string
expected string
}{
{"https://example.com/scim/v2", "https://example.com/scim/v2/Users"},
{"https://example.com/scim/v2/", "https://example.com/scim/v2/Users"},
{"http://localhost:8080/scim", "http://localhost:8080/scim/Users"},
}
for _, test := range tests {
provider := &SCIMSyncerProvider{
Syncer: &Syncer{Host: test.host},
}
endpoint := provider.buildSCIMEndpoint()
if endpoint != test.expected {
t.Errorf("For host '%s', expected endpoint '%s', got '%s'", test.host, test.expected, endpoint)
}
}
}
func TestGetSyncerProviderSCIM(t *testing.T) {
syncer := &Syncer{
Type: "SCIM",
Host: "https://example.com/scim/v2",
}
provider := GetSyncerProvider(syncer)
if _, ok := provider.(*SCIMSyncerProvider); !ok {
t.Errorf("Expected SCIMSyncerProvider for type 'SCIM', got %T", provider)
}
}

View File

@@ -70,6 +70,18 @@ func (syncer *Syncer) updateUserForOriginalFields(user *User, key string) (bool,
columns := syncer.getCasdoorColumns()
columns = append(columns, "affiliation", "hash", "pre_hash")
// Add provider-specific field for API-based syncers to enable login binding
// This allows synced users to login via their provider accounts
switch syncer.Type {
case "WeCom":
columns = append(columns, "wecom")
case "DingTalk":
columns = append(columns, "dingtalk")
case "Lark":
columns = append(columns, "lark")
}
affected, err := ormer.Engine.Where(key+" = ? and owner = ?", syncer.getUserValue(&oldUser, key), oldUser.Owner).Cols(columns...).Update(user)
if err != nil {
return false, err

View File

@@ -275,6 +275,7 @@ func (p *WecomSyncerProvider) wecomUserToOriginalUser(wecomUser *WecomUser) *Ori
Address: []string{},
Properties: map[string]string{},
Groups: []string{},
Wecom: wecomUser.UserId, // Link WeCom provider account
}
// Set gender
@@ -303,3 +304,15 @@ func (p *WecomSyncerProvider) wecomUserToOriginalUser(wecomUser *WecomUser) *Ori
return user
}
// GetOriginalGroups retrieves all groups from WeCom (not implemented yet)
func (p *WecomSyncerProvider) GetOriginalGroups() ([]*OriginalGroup, error) {
// TODO: Implement WeCom group sync
return []*OriginalGroup{}, nil
}
// GetOriginalUserGroups retrieves the group IDs that a user belongs to (not implemented yet)
func (p *WecomSyncerProvider) GetOriginalUserGroups(userId string) ([]string, error) {
// TODO: Implement WeCom user group membership sync
return []string{}, nil
}

View File

@@ -43,6 +43,7 @@ type Token struct {
CodeChallenge string `xorm:"varchar(100)" json:"codeChallenge"`
CodeIsUsed bool `json:"codeIsUsed"`
CodeExpireIn int64 `json:"codeExpireIn"`
Resource string `xorm:"varchar(255)" json:"resource"` // RFC 8707 Resource Indicator
}
func GetTokenCount(owner, organization, field, value string) (int64, error) {

View File

@@ -338,6 +338,50 @@ func getClaimsWithoutThirdIdp(claims Claims) ClaimsWithoutThirdIdp {
return res
}
// getUserFieldValue gets the value of a user field by name, handling special cases like Roles and Permissions
func getUserFieldValue(user *User, fieldName string) (interface{}, bool) {
if user == nil {
return nil, false
}
// Handle special fields that need conversion
switch fieldName {
case "Roles":
return getUserRoleNames(user), true
case "Permissions":
return getUserPermissionNames(user), true
case "permissionNames":
permissionNames := []string{}
for _, val := range user.Permissions {
permissionNames = append(permissionNames, val.Name)
}
return permissionNames, true
}
// Handle Properties fields (e.g., Properties.my_field)
if strings.HasPrefix(fieldName, "Properties.") {
parts := strings.Split(fieldName, ".")
if len(parts) == 2 {
propName := parts[1]
if user.Properties != nil {
if value, exists := user.Properties[propName]; exists {
return value, true
}
}
}
return nil, false
}
// Use reflection to get the field value
userValue := reflect.ValueOf(user).Elem()
userField := userValue.FieldByName(fieldName)
if userField.IsValid() {
return userField.Interface(), true
}
return nil, false
}
func getClaimsCustom(claims Claims, tokenField []string, tokenAttributes []*JwtItem) jwt.MapClaims {
res := make(jwt.MapClaims)
@@ -414,16 +458,30 @@ func getClaimsCustom(claims Claims, tokenField []string, tokenAttributes []*JwtI
}
for _, item := range tokenAttributes {
valueList := replaceAttributeValue(claims.User, item.Value)
if len(valueList) == 0 {
continue
var value interface{}
// If Category is "Existing Field", get the actual field value from the user
if item.Category == "Existing Field" {
fieldValue, found := getUserFieldValue(claims.User, item.Value)
if !found {
continue
}
value = fieldValue
} else {
// Default behavior: use replaceAttributeValue for "Static Value" or empty category
valueList := replaceAttributeValue(claims.User, item.Value)
if len(valueList) == 0 {
continue
}
if item.Type == "String" {
value = valueList[0]
} else {
value = valueList
}
}
if item.Type == "String" {
res[item.Name] = valueList[0]
} else {
res[item.Name] = valueList
}
res[item.Name] = value
}
return res
@@ -451,7 +509,7 @@ func refineUser(user *User) *User {
return user
}
func generateJwtToken(application *Application, user *User, provider string, signinMethod string, nonce string, scope string, host string) (string, string, string, error) {
func generateJwtToken(application *Application, user *User, provider string, signinMethod string, nonce string, scope string, resource string, host string) (string, string, string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(time.Duration(application.ExpireInHours * float64(time.Hour)))
refreshExpireTime := nowTime.Add(time.Duration(application.RefreshExpireInHours * float64(time.Hour)))
@@ -495,7 +553,10 @@ func generateJwtToken(application *Application, user *User, provider string, sig
},
}
if application.IsShared {
// RFC 8707: Use resource as audience when provided
if resource != "" {
claims.Audience = []string{resource}
} else if application.IsShared {
claims.Audience = []string{application.ClientId + "-org-" + user.Owner}
}

View File

@@ -18,6 +18,8 @@ import (
"crypto/sha256"
"encoding/base64"
"fmt"
"net/url"
"strings"
"sync"
"time"
@@ -91,6 +93,26 @@ type DeviceAuthResponse struct {
Interval int `json:"interval"`
}
// validateResourceURI validates that the resource parameter is a valid absolute URI
// according to RFC 8707 Section 2
func validateResourceURI(resource string) error {
if resource == "" {
return nil // empty resource is allowed (backward compatibility)
}
parsedURL, err := url.Parse(resource)
if err != nil {
return fmt.Errorf("resource must be a valid URI")
}
// RFC 8707: The resource parameter must be an absolute URI
if !parsedURL.IsAbs() {
return fmt.Errorf("resource must be an absolute URI")
}
return nil
}
func ExpireTokenByAccessToken(accessToken string) (bool, *Application, *Token, error) {
token, err := GetTokenByAccessToken(accessToken)
if err != nil {
@@ -137,7 +159,7 @@ func CheckOAuthLogin(clientId string, responseType string, redirectUri string, s
return "", application, nil
}
func GetOAuthCode(userId string, clientId string, provider string, signinMethod string, responseType string, redirectUri string, scope string, state string, nonce string, challenge string, host string, lang string) (*Code, error) {
func GetOAuthCode(userId string, clientId string, provider string, signinMethod string, responseType string, redirectUri string, scope string, state string, nonce string, challenge string, resource string, host string, lang string) (*Code, error) {
user, err := GetUser(userId)
if err != nil {
return nil, err
@@ -168,11 +190,19 @@ func GetOAuthCode(userId string, clientId string, provider string, signinMethod
}, nil
}
// Validate resource parameter (RFC 8707)
if err := validateResourceURI(resource); err != nil {
return &Code{
Message: err.Error(),
Code: "",
}, nil
}
err = ExtendUserWithRolesAndPermissions(user)
if err != nil {
return nil, err
}
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, provider, signinMethod, nonce, scope, host)
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, provider, signinMethod, nonce, scope, resource, host)
if err != nil {
return nil, err
}
@@ -197,6 +227,7 @@ func GetOAuthCode(userId string, clientId string, provider string, signinMethod
CodeChallenge: challenge,
CodeIsUsed: false,
CodeExpireIn: time.Now().Add(time.Minute * 5).Unix(),
Resource: resource,
}
_, err = AddToken(token)
if err != nil {
@@ -209,7 +240,7 @@ func GetOAuthCode(userId string, clientId string, provider string, signinMethod
}, nil
}
func GetOAuthToken(grantType string, clientId string, clientSecret string, code string, verifier string, scope string, nonce string, username string, password string, host string, refreshToken string, tag string, avatar string, lang string) (interface{}, error) {
func GetOAuthToken(grantType string, clientId string, clientSecret string, code string, verifier string, scope string, nonce string, username string, password string, host string, refreshToken string, tag string, avatar string, lang string, subjectToken string, subjectTokenType string, audience string, resource string) (interface{}, error) {
application, err := GetApplicationByClientId(clientId)
if err != nil {
return nil, err
@@ -235,7 +266,7 @@ func GetOAuthToken(grantType string, clientId string, clientSecret string, code
var tokenError *TokenError
switch grantType {
case "authorization_code": // Authorization Code Grant
token, tokenError, err = GetAuthorizationCodeToken(application, clientSecret, code, verifier)
token, tokenError, err = GetAuthorizationCodeToken(application, clientSecret, code, verifier, resource)
case "password": // Resource Owner Password Credentials Grant
token, tokenError, err = GetPasswordToken(application, username, password, scope, host)
case "client_credentials": // Client Credentials Grant
@@ -244,6 +275,8 @@ func GetOAuthToken(grantType string, clientId string, clientSecret string, code
token, tokenError, err = GetImplicitToken(application, username, scope, nonce, host)
case "urn:ietf:params:oauth:grant-type:device_code":
token, tokenError, err = GetImplicitToken(application, username, scope, nonce, host)
case "urn:ietf:params:oauth:grant-type:token-exchange": // Token Exchange Grant (RFC 8693)
token, tokenError, err = GetTokenExchangeToken(application, clientSecret, subjectToken, subjectTokenType, audience, scope, host)
case "refresh_token":
refreshToken2, err := RefreshToken(grantType, refreshToken, scope, clientId, clientSecret, host)
if err != nil {
@@ -388,7 +421,7 @@ func RefreshToken(grantType string, refreshToken string, scope string, clientId
return nil, err
}
newAccessToken, newRefreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", scope, host)
newAccessToken, newRefreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", scope, "", host)
if err != nil {
return &TokenError{
Error: EndpointError,
@@ -542,7 +575,7 @@ func createGuestUserToken(application *Application, clientSecret string, verifie
}
// Generate JWT token
accessToken, refreshToken, tokenName, err := generateJwtToken(application, guestUser, "", "", "", "", "")
accessToken, refreshToken, tokenName, err := generateJwtToken(application, guestUser, "", "", "", "", "", "")
if err != nil {
return nil, &TokenError{
Error: EndpointError,
@@ -592,7 +625,7 @@ func generateGuestUsername() string {
// GetAuthorizationCodeToken
// Authorization code flow
func GetAuthorizationCodeToken(application *Application, clientSecret string, code string, verifier string) (*Token, *TokenError, error) {
func GetAuthorizationCodeToken(application *Application, clientSecret string, code string, verifier string, resource string) (*Token, *TokenError, error) {
if code == "" {
return nil, &TokenError{
Error: InvalidRequest,
@@ -660,6 +693,14 @@ func GetAuthorizationCodeToken(application *Application, clientSecret string, co
}, nil
}
// RFC 8707: Validate resource parameter matches the one in the authorization request
if resource != token.Resource {
return nil, &TokenError{
Error: InvalidGrant,
ErrorDescription: fmt.Sprintf("resource parameter does not match authorization request, expected: [%s], got: [%s]", token.Resource, resource),
}, nil
}
nowUnix := time.Now().Unix()
if nowUnix > token.CodeExpireIn {
// code must be used within 5 minutes
@@ -716,7 +757,7 @@ func GetPasswordToken(application *Application, username string, password string
return nil, nil, err
}
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", scope, host)
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", scope, "", host)
if err != nil {
return nil, &TokenError{
Error: EndpointError,
@@ -762,7 +803,7 @@ func GetClientCredentialsToken(application *Application, clientSecret string, sc
Type: "application",
}
accessToken, _, tokenName, err := generateJwtToken(application, nullUser, "", "", "", scope, host)
accessToken, _, tokenName, err := generateJwtToken(application, nullUser, "", "", "", scope, "", host)
if err != nil {
return nil, &TokenError{
Error: EndpointError,
@@ -826,7 +867,7 @@ func GetTokenByUser(application *Application, user *User, scope string, nonce st
return nil, err
}
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", nonce, scope, host)
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", nonce, scope, "", host)
if err != nil {
return nil, err
}
@@ -933,7 +974,7 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin
return nil, nil, err
}
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", "", host)
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", "", "", host)
if err != nil {
return nil, &TokenError{
Error: EndpointError,
@@ -963,6 +1004,183 @@ func GetWechatMiniProgramToken(application *Application, code string, host strin
return token, nil, nil
}
// GetTokenExchangeToken
// Token Exchange Grant (RFC 8693)
// Exchanges a subject token for a new token with different audience or scope
func GetTokenExchangeToken(application *Application, clientSecret string, subjectToken string, subjectTokenType string, audience string, scope string, host string) (*Token, *TokenError, error) {
// Verify client secret
if application.ClientSecret != clientSecret {
return nil, &TokenError{
Error: InvalidClient,
ErrorDescription: "client_secret is invalid",
}, nil
}
// Validate subject_token parameter
if subjectToken == "" {
return nil, &TokenError{
Error: InvalidRequest,
ErrorDescription: "subject_token is required",
}, nil
}
// Validate subject_token_type parameter
// RFC 8693 defines standard token type identifiers
if subjectTokenType == "" {
subjectTokenType = "urn:ietf:params:oauth:token-type:access_token" // Default to access_token
}
// Support common token types
supportedTokenTypes := []string{
"urn:ietf:params:oauth:token-type:access_token",
"urn:ietf:params:oauth:token-type:jwt",
"urn:ietf:params:oauth:token-type:id_token",
}
isValidTokenType := false
for _, tokenType := range supportedTokenTypes {
if subjectTokenType == tokenType {
isValidTokenType = true
break
}
}
if !isValidTokenType {
return nil, &TokenError{
Error: InvalidRequest,
ErrorDescription: fmt.Sprintf("unsupported subject_token_type: %s", subjectTokenType),
}, nil
}
// Get certificate for token validation
cert, err := getCertByApplication(application)
if err != nil {
return nil, nil, err
}
if cert == nil {
return nil, &TokenError{
Error: EndpointError,
ErrorDescription: fmt.Sprintf("cert: %s cannot be found", application.Cert),
}, nil
}
// Parse and validate the subject token
var subjectOwner, subjectName, subjectScope string
if application.TokenFormat == "JWT-Standard" {
standardClaims, err := ParseStandardJwtToken(subjectToken, cert)
if err != nil {
return nil, &TokenError{
Error: InvalidGrant,
ErrorDescription: fmt.Sprintf("invalid subject_token: %s", err.Error()),
}, nil
}
subjectOwner = standardClaims.Owner
subjectName = standardClaims.Name
subjectScope = standardClaims.Scope
} else {
claims, err := ParseJwtToken(subjectToken, cert)
if err != nil {
return nil, &TokenError{
Error: InvalidGrant,
ErrorDescription: fmt.Sprintf("invalid subject_token: %s", err.Error()),
}, nil
}
subjectOwner = claims.Owner
subjectName = claims.Name
subjectScope = claims.Scope
}
// Get the user from the subject token
user, err := getUser(subjectOwner, subjectName)
if err != nil {
return nil, nil, err
}
if user == nil {
return nil, &TokenError{
Error: InvalidGrant,
ErrorDescription: fmt.Sprintf("user from subject_token does not exist: %s", util.GetId(subjectOwner, subjectName)),
}, nil
}
if user.IsForbidden {
return nil, &TokenError{
Error: InvalidGrant,
ErrorDescription: "the user is forbidden to sign in, please contact the administrator",
}, nil
}
// Handle scope parameter
// If scope is not provided, use the scope from the subject token
// If scope is provided, it should be a subset of the subject token's scope (downscoping)
if scope == "" {
scope = subjectScope
} else {
// Validate scope downscoping (basic implementation)
// In a production environment, you would implement more sophisticated scope validation
if subjectScope != "" {
subjectScopes := strings.Split(subjectScope, " ")
requestedScopes := strings.Split(scope, " ")
for _, requestedScope := range requestedScopes {
if requestedScope == "" {
continue // Skip empty strings
}
found := false
for _, existingScope := range subjectScopes {
if existingScope != "" && requestedScope == existingScope {
found = true
break
}
}
if !found {
return nil, &TokenError{
Error: InvalidScope,
ErrorDescription: fmt.Sprintf("requested scope '%s' is not in subject token's scope", requestedScope),
}, nil
}
}
}
}
// Extend user with roles and permissions
err = ExtendUserWithRolesAndPermissions(user)
if err != nil {
return nil, nil, err
}
// Generate new JWT token
accessToken, refreshToken, tokenName, err := generateJwtToken(application, user, "", "", "", scope, "", host)
if err != nil {
return nil, &TokenError{
Error: EndpointError,
ErrorDescription: fmt.Sprintf("generate jwt token error: %s", err.Error()),
}, nil
}
// Create token object
token := &Token{
Owner: application.Owner,
Name: tokenName,
CreatedTime: util.GetCurrentTime(),
Application: application.Name,
Organization: user.Owner,
User: user.Name,
Code: util.GenerateClientId(),
AccessToken: accessToken,
RefreshToken: refreshToken,
ExpiresIn: int(application.ExpireInHours * float64(hourSeconds)),
Scope: scope,
TokenType: "Bearer",
CodeIsUsed: true,
}
_, err = AddToken(token)
if err != nil {
return nil, nil, err
}
return token, nil, nil
}
func GetAccessTokenByUser(user *User, host string) (string, error) {
application, err := GetApplicationByUser(user)
if err != nil {

View File

@@ -58,60 +58,61 @@ type User struct {
UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
DeletedTime string `xorm:"varchar(100)" json:"deletedTime"`
Id string `xorm:"varchar(100) index" json:"id"`
ExternalId string `xorm:"varchar(100) index" json:"externalId"`
Type string `xorm:"varchar(100)" json:"type"`
Password string `xorm:"varchar(150)" json:"password"`
PasswordSalt string `xorm:"varchar(100)" json:"passwordSalt"`
PasswordType string `xorm:"varchar(100)" json:"passwordType"`
DisplayName string `xorm:"varchar(100)" json:"displayName"`
FirstName string `xorm:"varchar(100)" json:"firstName"`
LastName string `xorm:"varchar(100)" json:"lastName"`
Avatar string `xorm:"text" json:"avatar"`
AvatarType string `xorm:"varchar(100)" json:"avatarType"`
PermanentAvatar string `xorm:"varchar(500)" json:"permanentAvatar"`
Email string `xorm:"varchar(100) index" json:"email"`
EmailVerified bool `json:"emailVerified"`
Phone string `xorm:"varchar(100) index" json:"phone"`
CountryCode string `xorm:"varchar(6)" json:"countryCode"`
Region string `xorm:"varchar(100)" json:"region"`
Location string `xorm:"varchar(100)" json:"location"`
Address []string `json:"address"`
Affiliation string `xorm:"varchar(100)" json:"affiliation"`
Title string `xorm:"varchar(100)" json:"title"`
IdCardType string `xorm:"varchar(100)" json:"idCardType"`
IdCard string `xorm:"varchar(100) index" json:"idCard"`
RealName string `xorm:"varchar(100)" json:"realName"`
IsVerified bool `json:"isVerified"`
Homepage string `xorm:"varchar(100)" json:"homepage"`
Bio string `xorm:"varchar(100)" json:"bio"`
Tag string `xorm:"varchar(100)" json:"tag"`
Language string `xorm:"varchar(100)" json:"language"`
Gender string `xorm:"varchar(100)" json:"gender"`
Birthday string `xorm:"varchar(100)" json:"birthday"`
Education string `xorm:"varchar(100)" json:"education"`
Score int `json:"score"`
Karma int `json:"karma"`
Ranking int `json:"ranking"`
Balance float64 `json:"balance"`
BalanceCredit float64 `json:"balanceCredit"`
Currency string `xorm:"varchar(100)" json:"currency"`
BalanceCurrency string `xorm:"varchar(100)" json:"balanceCurrency"`
IsDefaultAvatar bool `json:"isDefaultAvatar"`
IsOnline bool `json:"isOnline"`
IsAdmin bool `json:"isAdmin"`
IsForbidden bool `json:"isForbidden"`
IsDeleted bool `json:"isDeleted"`
SignupApplication string `xorm:"varchar(100)" json:"signupApplication"`
Hash string `xorm:"varchar(100)" json:"hash"`
PreHash string `xorm:"varchar(100)" json:"preHash"`
RegisterType string `xorm:"varchar(100)" json:"registerType"`
RegisterSource string `xorm:"varchar(100)" json:"registerSource"`
AccessKey string `xorm:"varchar(100)" json:"accessKey"`
AccessSecret string `xorm:"varchar(100)" json:"accessSecret"`
AccessToken string `xorm:"mediumtext" json:"accessToken"`
OriginalToken string `xorm:"mediumtext" json:"originalToken"`
OriginalRefreshToken string `xorm:"mediumtext" json:"originalRefreshToken"`
Id string `xorm:"varchar(100) index" json:"id"`
ExternalId string `xorm:"varchar(100) index" json:"externalId"`
Type string `xorm:"varchar(100)" json:"type"`
Password string `xorm:"varchar(150)" json:"password"`
PasswordSalt string `xorm:"varchar(100)" json:"passwordSalt"`
PasswordType string `xorm:"varchar(100)" json:"passwordType"`
DisplayName string `xorm:"varchar(100)" json:"displayName"`
FirstName string `xorm:"varchar(100)" json:"firstName"`
LastName string `xorm:"varchar(100)" json:"lastName"`
Avatar string `xorm:"text" json:"avatar"`
AvatarType string `xorm:"varchar(100)" json:"avatarType"`
PermanentAvatar string `xorm:"varchar(500)" json:"permanentAvatar"`
Email string `xorm:"varchar(100) index" json:"email"`
EmailVerified bool `json:"emailVerified"`
Phone string `xorm:"varchar(100) index" json:"phone"`
CountryCode string `xorm:"varchar(6)" json:"countryCode"`
Region string `xorm:"varchar(100)" json:"region"`
Location string `xorm:"varchar(100)" json:"location"`
Address []string `json:"address"`
Addresses []*Address `xorm:"addresses blob" json:"addresses"`
Affiliation string `xorm:"varchar(100)" json:"affiliation"`
Title string `xorm:"varchar(100)" json:"title"`
IdCardType string `xorm:"varchar(100)" json:"idCardType"`
IdCard string `xorm:"varchar(100) index" json:"idCard"`
RealName string `xorm:"varchar(100)" json:"realName"`
IsVerified bool `json:"isVerified"`
Homepage string `xorm:"varchar(100)" json:"homepage"`
Bio string `xorm:"varchar(100)" json:"bio"`
Tag string `xorm:"varchar(100)" json:"tag"`
Language string `xorm:"varchar(100)" json:"language"`
Gender string `xorm:"varchar(100)" json:"gender"`
Birthday string `xorm:"varchar(100)" json:"birthday"`
Education string `xorm:"varchar(100)" json:"education"`
Score int `json:"score"`
Karma int `json:"karma"`
Ranking int `json:"ranking"`
Balance float64 `json:"balance"`
BalanceCredit float64 `json:"balanceCredit"`
Currency string `xorm:"varchar(100)" json:"currency"`
BalanceCurrency string `xorm:"varchar(100)" json:"balanceCurrency"`
IsDefaultAvatar bool `json:"isDefaultAvatar"`
IsOnline bool `json:"isOnline"`
IsAdmin bool `json:"isAdmin"`
IsForbidden bool `json:"isForbidden"`
IsDeleted bool `json:"isDeleted"`
SignupApplication string `xorm:"varchar(100)" json:"signupApplication"`
Hash string `xorm:"varchar(100)" json:"hash"`
PreHash string `xorm:"varchar(100)" json:"preHash"`
RegisterType string `xorm:"varchar(100)" json:"registerType"`
RegisterSource string `xorm:"varchar(100)" json:"registerSource"`
AccessKey string `xorm:"varchar(100)" json:"accessKey"`
AccessSecret string `xorm:"varchar(100)" json:"accessSecret"`
AccessToken string `xorm:"mediumtext" json:"accessToken"`
OriginalToken string `xorm:"mediumtext" json:"originalToken"`
OriginalRefreshToken string `xorm:"mediumtext" json:"originalRefreshToken"`
CreatedIp string `xorm:"varchar(100)" json:"createdIp"`
LastSigninTime string `xorm:"varchar(100)" json:"lastSigninTime"`
@@ -274,6 +275,16 @@ type MfaAccount struct {
Origin string `xorm:"varchar(100)" json:"origin"`
}
type Address struct {
Tag string `xorm:"varchar(100)" json:"tag"`
Line1 string `xorm:"varchar(100)" json:"line1"`
Line2 string `xorm:"varchar(100)" json:"line2"`
City string `xorm:"varchar(100)" json:"city"`
State string `xorm:"varchar(100)" json:"state"`
ZipCode string `xorm:"varchar(100)" json:"zipCode"`
Region string `xorm:"varchar(100)" json:"region"`
}
type FaceId struct {
Name string `xorm:"varchar(100) notnull pk" json:"name"`
FaceIdData []float64 `json:"faceIdData"`
@@ -678,6 +689,15 @@ func GetMaskedUser(user *User, isAdminOrSelf bool, errs ...error) (*User, error)
if user.OriginalRefreshToken != "" {
user.OriginalRefreshToken = "***"
}
// Mask per-provider OAuth tokens in Properties
if user.Properties != nil {
for key := range user.Properties {
// More specific pattern matching to avoid masking unrelated properties
if strings.HasPrefix(key, "oauth_") && (strings.HasSuffix(key, "_accessToken") || strings.HasSuffix(key, "_refreshToken")) {
user.Properties[key] = "***"
}
}
}
}
if user.ManagedAccounts != nil {

View File

@@ -184,9 +184,32 @@ func getUserExtraProperty(user *User, providerType, key string) (string, error)
return extra[key], nil
}
// getOAuthTokenPropertyKey returns the property key for storing OAuth tokens
func getOAuthTokenPropertyKey(providerType string, tokenType string) string {
return fmt.Sprintf("oauth_%s_%s", providerType, tokenType)
}
// GetUserOAuthAccessToken retrieves the OAuth access token for a specific provider
func GetUserOAuthAccessToken(user *User, providerType string) string {
return getUserProperty(user, getOAuthTokenPropertyKey(providerType, "accessToken"))
}
// GetUserOAuthRefreshToken retrieves the OAuth refresh token for a specific provider
func GetUserOAuthRefreshToken(user *User, providerType string) string {
return getUserProperty(user, getOAuthTokenPropertyKey(providerType, "refreshToken"))
}
func SetUserOAuthProperties(organization *Organization, user *User, providerType string, userInfo *idp.UserInfo, token *oauth2.Token, userMapping ...map[string]string) (bool, error) {
// Store the original OAuth provider token if available
if token != nil && token.AccessToken != "" {
// Store tokens per provider in Properties map
setUserProperty(user, getOAuthTokenPropertyKey(providerType, "accessToken"), token.AccessToken)
if token.RefreshToken != "" {
setUserProperty(user, getOAuthTokenPropertyKey(providerType, "refreshToken"), token.RefreshToken)
}
// Also update the legacy fields for backward compatibility
user.OriginalToken = token.AccessToken
user.OriginalRefreshToken = token.RefreshToken
}
@@ -382,7 +405,7 @@ func ClearUserOAuthProperties(user *User, providerType string) (bool, error) {
func userVisible(isAdmin bool, item *AccountItem) bool {
if item == nil {
return false
return true
}
if item.ViewRule == "Admin" && !isAdmin {
@@ -541,10 +564,11 @@ func CheckPermissionForUpdateUser(oldUser, newUser *User, isAdmin bool, allowDis
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.SignupApplication != newUser.SignupApplication {
item := GetAccountItemByName("Signup application", organization)
if oldUser.Language != newUser.Language {
item := GetAccountItemByName("Language", organization)
if !userVisible(isAdmin, item) {
newUser.SignupApplication = oldUser.SignupApplication
newUser.Language = oldUser.Language
} else {
itemsChanged = append(itemsChanged, item)
}
@@ -577,6 +601,83 @@ func CheckPermissionForUpdateUser(oldUser, newUser *User, isAdmin bool, allowDis
}
}
if oldUser.Balance != newUser.Balance {
item := GetAccountItemByName("Balance", organization)
if !userVisible(isAdmin, item) {
newUser.Balance = oldUser.Balance
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.BalanceCredit != newUser.BalanceCredit {
item := GetAccountItemByName("Balance credit", organization)
if !userVisible(isAdmin, item) {
newUser.BalanceCredit = oldUser.BalanceCredit
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.BalanceCurrency != newUser.BalanceCurrency {
item := GetAccountItemByName("Balance currency", organization)
if !userVisible(isAdmin, item) {
newUser.BalanceCurrency = oldUser.BalanceCurrency
} else {
itemsChanged = append(itemsChanged, item)
}
}
oldUserCartJson, _ := json.Marshal(oldUser.Cart)
if newUser.Cart == nil {
newUser.Cart = []ProductInfo{}
}
newUserCartJson, _ := json.Marshal(newUser.Cart)
if string(oldUserCartJson) != string(newUserCartJson) {
item := GetAccountItemByName("Cart", organization)
if !userVisible(isAdmin, item) {
newUser.Cart = oldUser.Cart
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Score != newUser.Score {
item := GetAccountItemByName("Score", organization)
if !userVisible(isAdmin, item) {
newUser.Score = oldUser.Score
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Karma != newUser.Karma {
item := GetAccountItemByName("Karma", organization)
if !userVisible(isAdmin, item) {
newUser.Karma = oldUser.Karma
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Ranking != newUser.Ranking {
item := GetAccountItemByName("Ranking", organization)
if !userVisible(isAdmin, item) {
newUser.Ranking = oldUser.Ranking
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.SignupApplication != newUser.SignupApplication {
item := GetAccountItemByName("Signup application", organization)
if !userVisible(isAdmin, item) {
newUser.SignupApplication = oldUser.SignupApplication
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.IdCard != newUser.IdCard {
item := GetAccountItemByName("ID card", organization)
if !userVisible(isAdmin, item) {
@@ -705,51 +806,6 @@ func CheckPermissionForUpdateUser(oldUser, newUser *User, isAdmin bool, allowDis
}
}
if oldUser.Balance != newUser.Balance {
item := GetAccountItemByName("Balance", organization)
if !userVisible(isAdmin, item) {
newUser.Balance = oldUser.Balance
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Score != newUser.Score {
item := GetAccountItemByName("Score", organization)
if !userVisible(isAdmin, item) {
newUser.Score = oldUser.Score
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Karma != newUser.Karma {
item := GetAccountItemByName("Karma", organization)
if !userVisible(isAdmin, item) {
newUser.Karma = oldUser.Karma
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Language != newUser.Language {
item := GetAccountItemByName("Language", organization)
if !userVisible(isAdmin, item) {
newUser.Language = oldUser.Language
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Ranking != newUser.Ranking {
item := GetAccountItemByName("Ranking", organization)
if !userVisible(isAdmin, item) {
newUser.Ranking = oldUser.Ranking
} else {
itemsChanged = append(itemsChanged, item)
}
}
if oldUser.Currency != newUser.Currency {
item := GetAccountItemByName("Currency", organization)
if !userVisible(isAdmin, item) {
@@ -769,6 +825,11 @@ func CheckPermissionForUpdateUser(oldUser, newUser *User, isAdmin bool, allowDis
}
for _, accountItem := range itemsChanged {
// Skip nil items - these occur when a field doesn't have a corresponding
// account item configuration, meaning no validation rules apply
if accountItem == nil {
continue
}
if pass, err := CheckAccountItemModifyRule(accountItem, isAdmin, lang); !pass {
return pass, err
@@ -918,6 +979,8 @@ func StringArrayToStruct[T any](stringArray [][]string) ([]*T, error) {
err = setReflectAttr[[]MfaAccount](&fv, v)
case reflect.TypeOf([]webauthn.Credential{}):
err = setReflectAttr[[]webauthn.Credential](&fv, v)
case reflect.TypeOf(map[string]string{}):
err = setReflectAttr[map[string]string](&fv, v)
}
if err != nil {

View File

@@ -21,7 +21,7 @@ import (
"net"
"time"
mssql "github.com/denisenkom/go-mssqldb"
mssql "github.com/microsoft/go-mssqldb"
"github.com/lib/pq"
"golang.org/x/crypto/ssh"

View File

@@ -0,0 +1,59 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"fmt"
)
// OauthProtectedResourceMetadata represents RFC 9728 OAuth 2.0 Protected Resource Metadata
type OauthProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResourceSigningAlg []string `json:"resource_signing_alg_values_supported,omitempty"`
ResourceDocumentation string `json:"resource_documentation,omitempty"`
}
// GetOauthProtectedResourceMetadata returns RFC 9728 Protected Resource Metadata for global discovery
func GetOauthProtectedResourceMetadata(host string) OauthProtectedResourceMetadata {
_, originBackend := getOriginFromHost(host)
return OauthProtectedResourceMetadata{
Resource: originBackend,
AuthorizationServers: []string{originBackend},
BearerMethodsSupported: []string{"header"},
ScopesSupported: []string{"openid", "profile", "email", "read", "write"},
ResourceSigningAlg: []string{"RS256"},
}
}
// GetOauthProtectedResourceMetadataByApplication returns RFC 9728 Protected Resource Metadata for application-specific discovery
func GetOauthProtectedResourceMetadataByApplication(host string, applicationName string) OauthProtectedResourceMetadata {
_, originBackend := getOriginFromHost(host)
// For application-specific discovery, the resource identifier includes the application name
resourceIdentifier := fmt.Sprintf("%s/.well-known/%s", originBackend, applicationName)
authServer := fmt.Sprintf("%s/.well-known/%s", originBackend, applicationName)
return OauthProtectedResourceMetadata{
Resource: resourceIdentifier,
AuthorizationServers: []string{authServer},
BearerMethodsSupported: []string{"header"},
ScopesSupported: []string{"openid", "profile", "email", "read", "write"},
ResourceSigningAlg: []string{"RS256"},
}
}

View File

@@ -32,6 +32,7 @@ type OidcDiscovery struct {
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
JwksUri string `json:"jwks_uri"`
IntrospectionEndpoint string `json:"introspection_endpoint"`
ResponseTypesSupported []string `json:"response_types_supported"`
@@ -40,6 +41,7 @@ type OidcDiscovery struct {
SubjectTypesSupported []string `json:"subject_types_supported"`
IdTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
ScopesSupported []string `json:"scopes_supported"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
ClaimsSupported []string `json:"claims_supported"`
RequestParameterSupported bool `json:"request_parameter_supported"`
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
@@ -123,6 +125,23 @@ func GetOidcDiscovery(host string, applicationName string) OidcDiscovery {
jwksUri = fmt.Sprintf("%s/.well-known/jwks", originBackend)
}
// Default OIDC scopes
scopes := []string{"openid", "email", "profile", "address", "phone", "offline_access"}
// Merge application-specific custom scopes if application is provided
if applicationName != "" {
applicationId := util.GetId("admin", applicationName)
application, err := GetApplication(applicationId)
if err == nil && application != nil && len(application.Scopes) > 0 {
for _, scope := range application.Scopes {
// Add custom scope names to the scopes list
if scope.Name != "" {
scopes = append(scopes, scope.Name)
}
}
}
}
// Examples:
// https://login.okta.com/.well-known/openid-configuration
// https://auth0.auth0.com/.well-known/openid-configuration
@@ -134,14 +153,16 @@ func GetOidcDiscovery(host string, applicationName string) OidcDiscovery {
TokenEndpoint: fmt.Sprintf("%s/api/login/oauth/access_token", originBackend),
UserinfoEndpoint: fmt.Sprintf("%s/api/userinfo", originBackend),
DeviceAuthorizationEndpoint: fmt.Sprintf("%s/api/device-auth", originBackend),
RegistrationEndpoint: fmt.Sprintf("%s/api/oauth/register", originBackend),
JwksUri: jwksUri,
IntrospectionEndpoint: fmt.Sprintf("%s/api/login/oauth/introspect", originBackend),
ResponseTypesSupported: []string{"code", "token", "id_token", "code token", "code id_token", "token id_token", "code token id_token", "none"},
ResponseModesSupported: []string{"query", "fragment", "form_post"},
GrantTypesSupported: []string{"authorization_code", "implicit", "password", "client_credentials", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"},
GrantTypesSupported: []string{"authorization_code", "implicit", "password", "client_credentials", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code", "urn:ietf:params:oauth:grant-type:token-exchange"},
SubjectTypesSupported: []string{"public"},
IdTokenSigningAlgValuesSupported: []string{"RS256", "RS512", "ES256", "ES384", "ES512"},
ScopesSupported: []string{"openid", "email", "profile", "address", "phone", "offline_access"},
ScopesSupported: scopes,
CodeChallengeMethodsSupported: []string{"S256"},
ClaimsSupported: []string{"iss", "ver", "sub", "aud", "iat", "exp", "id", "type", "displayName", "avatar", "permanentAvatar", "email", "phone", "location", "affiliation", "title", "homepage", "bio", "tag", "region", "language", "score", "ranking", "isOnline", "isAdmin", "isForbidden", "signupApplication", "ldap"},
RequestParameterSupported: true,
RequestObjectSigningAlgValuesSupported: []string{"HS256", "HS384", "HS512"},

View File

@@ -14,22 +14,59 @@
package pp
import (
"encoding/json"
"fmt"
)
type DummyPaymentProvider struct{}
type DummyOrderInfo struct {
Price float64 `json:"price"`
Currency string `json:"currency"`
ProductDisplayName string `json:"productDisplayName"`
}
func NewDummyPaymentProvider() (*DummyPaymentProvider, error) {
pp := &DummyPaymentProvider{}
return pp, nil
}
func (pp *DummyPaymentProvider) Pay(r *PayReq) (*PayResp, error) {
// Encode payment information in OrderId for later retrieval in Notify.
// Note: This is a test/mock provider and the OrderId is only used internally for testing.
// Real payment providers would receive this information from their external payment gateway.
orderInfo := DummyOrderInfo{
Price: r.Price,
Currency: r.Currency,
ProductDisplayName: "",
}
orderInfoBytes, err := json.Marshal(orderInfo)
if err != nil {
return nil, fmt.Errorf("failed to encode order info: %w", err)
}
return &PayResp{
PayUrl: r.ReturnUrl,
PayUrl: r.ReturnUrl,
OrderId: string(orderInfoBytes),
}, nil
}
func (pp *DummyPaymentProvider) Notify(body []byte, orderId string) (*NotifyResult, error) {
// Decode payment information from OrderId
var orderInfo DummyOrderInfo
if orderId != "" {
err := json.Unmarshal([]byte(orderId), &orderInfo)
if err != nil {
return nil, fmt.Errorf("failed to decode order info: %w", err)
}
}
return &NotifyResult{
PaymentStatus: PaymentStatePaid,
PaymentStatus: PaymentStatePaid,
Price: orderInfo.Price,
Currency: orderInfo.Currency,
ProductDisplayName: orderInfo.ProductDisplayName,
}, nil
}

View File

@@ -24,6 +24,12 @@ const (
PaymentStateError PaymentState = "Error"
)
// IsTerminalState checks if a payment state is terminal (cannot transition to other states)
func IsTerminalState(state PaymentState) bool {
return state == PaymentStatePaid || state == PaymentStateError ||
state == PaymentStateCanceled || state == PaymentStateTimeout
}
const (
PaymentEnvWechatBrowser = "WechatBrowser"
)

View File

@@ -94,6 +94,17 @@ func denyMcpRequest(ctx *context.Context) {
Data: T(ctx, "auth:Unauthorized operation"),
})
// Add WWW-Authenticate header per MCP Authorization spec (RFC 9728)
// Use the same logic as getOriginFromHost to determine the scheme
host := ctx.Request.Host
scheme := "https"
if !strings.Contains(host, ".") {
// localhost:8000 or computer-name:80
scheme = "http"
}
resourceMetadataUrl := fmt.Sprintf("%s://%s/.well-known/oauth-protected-resource", scheme, host)
ctx.Output.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"casdoor\", resource_metadata=\"%s\"", resourceMetadataUrl))
ctx.Output.SetStatus(http.StatusUnauthorized)
_ = ctx.Output.JSON(resp, true, false)
}

View File

@@ -65,6 +65,22 @@ func RecordMessage(ctx *context.Context) {
userId := getUser(ctx)
// Special handling for set-password endpoint to capture target user
if ctx.Request.URL.Path == "/api/set-password" {
// Parse form if not already parsed
if err := ctx.Request.ParseForm(); err != nil {
fmt.Printf("RecordMessage() error parsing form: %s\n", err.Error())
} else {
userOwner := ctx.Request.Form.Get("userOwner")
userName := ctx.Request.Form.Get("userName")
if userOwner != "" && userName != "" {
targetUserId := util.GetId(userOwner, userName)
ctx.Input.SetParam("recordTargetUserId", targetUserId)
}
}
}
ctx.Input.SetParam("recordUserId", userId)
}
@@ -76,7 +92,20 @@ func AfterRecordMessage(ctx *context.Context) {
}
userId := ctx.Input.Params()["recordUserId"]
if userId != "" {
targetUserId := ctx.Input.Params()["recordTargetUserId"]
// For set-password endpoint, use target user if available
// We use defensive error handling here (log instead of panic) because target user
// parsing is a new feature. If it fails, we gracefully fall back to the regular
// userId flow or empty user/org fields, maintaining backward compatibility.
if record.Action == "set-password" && targetUserId != "" {
owner, user, err := util.GetOwnerAndNameFromIdWithError(targetUserId)
if err != nil {
fmt.Printf("AfterRecordMessage() error parsing target user %s: %s\n", targetUserId, err.Error())
} else {
record.Organization, record.User = owner, user
}
} else if userId != "" {
owner, user, err := util.GetOwnerAndNameFromIdWithError(userId)
if err != nil {
panic(err)

View File

@@ -298,6 +298,7 @@ func InitAPI() {
web.Router("/api/login/oauth/access_token", &controllers.ApiController{}, "POST:GetOAuthToken")
web.Router("/api/login/oauth/refresh_token", &controllers.ApiController{}, "POST:RefreshToken")
web.Router("/api/login/oauth/introspect", &controllers.ApiController{}, "POST:IntrospectToken")
web.Router("/api/oauth/register", &controllers.ApiController{}, "POST:DynamicClientRegister")
web.Router("/api/get-records", &controllers.ApiController{}, "GET:GetRecords")
web.Router("/api/get-records-filter", &controllers.ApiController{}, "POST:GetRecordsByFilter")
@@ -320,10 +321,14 @@ func InitAPI() {
web.Router("/.well-known/openid-configuration", &controllers.RootController{}, "GET:GetOidcDiscovery")
web.Router("/.well-known/:application/openid-configuration", &controllers.RootController{}, "GET:GetOidcDiscoveryByApplication")
web.Router("/.well-known/oauth-authorization-server", &controllers.RootController{}, "GET:GetOAuthServerMetadata")
web.Router("/.well-known/:application/oauth-authorization-server", &controllers.RootController{}, "GET:GetOAuthServerMetadataByApplication")
web.Router("/.well-known/jwks", &controllers.RootController{}, "*:GetJwks")
web.Router("/.well-known/:application/jwks", &controllers.RootController{}, "*:GetJwksByApplication")
web.Router("/.well-known/webfinger", &controllers.RootController{}, "GET:GetWebFinger")
web.Router("/.well-known/:application/webfinger", &controllers.RootController{}, "GET:GetWebFingerByApplication")
web.Router("/.well-known/oauth-protected-resource", &controllers.RootController{}, "GET:GetOauthProtectedResourceMetadata")
web.Router("/.well-known/:application/oauth-protected-resource", &controllers.RootController{}, "GET:GetOauthProtectedResourceMetadataByApplication")
web.Router("/cas/:organization/:application/serviceValidate", &controllers.RootController{}, "GET:CasServiceValidate")
web.Router("/cas/:organization/:application/proxyValidate", &controllers.RootController{}, "GET:CasProxyValidate")

View File

@@ -89,7 +89,7 @@ func fastAutoSignin(ctx *context.Context) (string, error) {
return "", nil
}
code, err := object.GetOAuthCode(userId, clientId, "", "autoSignin", responseType, redirectUri, scope, state, nonce, codeChallenge, ctx.Request.Host, getAcceptLanguage(ctx))
code, err := object.GetOAuthCode(userId, clientId, "", "autoSignin", responseType, redirectUri, scope, state, nonce, codeChallenge, "", ctx.Request.Host, getAcceptLanguage(ctx))
if err != nil {
return "", err
} else if code.Message != "" {

View File

@@ -850,6 +850,69 @@
}
}
},
"/api/add-ticket": {
"post": {
"tags": [
"Ticket API"
],
"description": "add ticket",
"operationId": "ApiController.AddTicket",
"parameters": [
{
"in": "body",
"name": "body",
"description": "The details of the ticket",
"required": true,
"schema": {
"$ref": "#/definitions/object.Ticket"
}
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/add-ticket-message": {
"post": {
"tags": [
"Ticket API"
],
"description": "add a message to a ticket",
"operationId": "ApiController.AddTicketMessage",
"parameters": [
{
"in": "query",
"name": "id",
"description": "The id ( owner/name ) of the ticket",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "body",
"description": "The message to add",
"required": true,
"schema": {
"$ref": "#/definitions/object.TicketMessage"
}
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/add-token": {
"post": {
"tags": [
@@ -1707,6 +1770,34 @@
}
}
},
"/api/delete-ticket": {
"post": {
"tags": [
"Ticket API"
],
"description": "delete ticket",
"operationId": "ApiController.DeleteTicket",
"parameters": [
{
"in": "body",
"name": "body",
"description": "The details of the ticket",
"required": true,
"schema": {
"$ref": "#/definitions/object.Ticket"
}
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/delete-token": {
"post": {
"tags": [
@@ -1891,6 +1982,23 @@
}
}
},
"/api/exit-impersonation-user": {
"post": {
"tags": [
"User API"
],
"description": "clear impersonation info for current session",
"operationId": "ApiController.ExitImpersonateUser",
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/faceid-signin-begin": {
"get": {
"tags": [
@@ -1996,6 +2104,81 @@
}
}
},
"/api/get-all-actions": {
"get": {
"tags": [
"Enforcer API"
],
"description": "Get all actions for a user (Casbin API)",
"operationId": "ApiController.GetAllActions",
"parameters": [
{
"in": "query",
"name": "userId",
"description": "user id like built-in/admin",
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/get-all-objects": {
"get": {
"tags": [
"Enforcer API"
],
"description": "Get all objects for a user (Casbin API)",
"operationId": "ApiController.GetAllObjects",
"parameters": [
{
"in": "query",
"name": "userId",
"description": "user id like built-in/admin",
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/get-all-roles": {
"get": {
"tags": [
"Enforcer API"
],
"description": "Get all roles for a user (Casbin API)",
"operationId": "ApiController.GetAllRoles",
"parameters": [
{
"in": "query",
"name": "userId",
"description": "user id like built-in/admin",
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/get-app-login": {
"get": {
"tags": [
@@ -3843,6 +4026,61 @@
}
}
},
"/api/get-ticket": {
"get": {
"tags": [
"Ticket API"
],
"description": "get ticket",
"operationId": "ApiController.GetTicket",
"parameters": [
{
"in": "query",
"name": "id",
"description": "The id ( owner/name ) of the ticket",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/object.Ticket"
}
}
}
}
},
"/api/get-tickets": {
"get": {
"tags": [
"Ticket API"
],
"description": "get tickets",
"operationId": "ApiController.GetTickets",
"parameters": [
{
"in": "query",
"name": "owner",
"description": "The owner of tickets",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/object.Ticket"
}
}
}
}
}
},
"/api/get-token": {
"get": {
"tags": [
@@ -4299,6 +4537,32 @@
}
}
},
"/api/impersonation-user": {
"post": {
"tags": [
"User API"
],
"description": "set impersonation user for current admin session",
"operationId": "ApiController.ImpersonateUser",
"parameters": [
{
"in": "formData",
"name": "username",
"description": "The username to impersonate (owner/name)",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/invoice-payment": {
"post": {
"tags": [
@@ -5219,8 +5483,16 @@
"tags": [
"Login API"
],
"description": "logout the current user from all applications",
"description": "logout the current user from all applications or current session only",
"operationId": "ApiController.SsoLogout",
"parameters": [
{
"in": "query",
"name": "logoutAll",
"description": "Whether to logout from all sessions. Accepted values: 'true', '1', or empty (default: true). Any other value means false.",
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
@@ -5234,8 +5506,16 @@
"tags": [
"Login API"
],
"description": "logout the current user from all applications",
"description": "logout the current user from all applications or current session only",
"operationId": "ApiController.SsoLogout",
"parameters": [
{
"in": "query",
"name": "logoutAll",
"description": "Whether to logout from all sessions. Accepted values: 'true', '1', or empty (default: true). Any other value means false.",
"type": "string"
}
],
"responses": {
"200": {
"description": "The Response object",
@@ -6082,6 +6362,41 @@
}
}
},
"/api/update-ticket": {
"post": {
"tags": [
"Ticket API"
],
"description": "update ticket",
"operationId": "ApiController.UpdateTicket",
"parameters": [
{
"in": "query",
"name": "id",
"description": "The id ( owner/name ) of the ticket",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "body",
"description": "The details of the ticket",
"required": true,
"schema": {
"$ref": "#/definitions/object.Ticket"
}
}
],
"responses": {
"200": {
"description": "The Response object",
"schema": {
"$ref": "#/definitions/controllers.Response"
}
}
}
}
},
"/api/update-token": {
"post": {
"tags": [
@@ -6564,14 +6879,18 @@
}
},
"definitions": {
"217748.\u003cnil\u003e.string": {
"232967.\u003cnil\u003e.string": {
"title": "string",
"type": "object"
},
"217806.string.string": {
"233025.string.string": {
"title": "string",
"type": "object"
},
"McpResponse": {
"title": "McpResponse",
"type": "object"
},
"Response": {
"title": "Response",
"type": "object"
@@ -6763,6 +7082,9 @@
"regex": {
"type": "string"
},
"tab": {
"type": "string"
},
"viewRule": {
"type": "string"
},
@@ -6814,6 +7136,33 @@
}
}
},
"object.Address": {
"title": "Address",
"type": "object",
"properties": {
"city": {
"type": "string"
},
"line1": {
"type": "string"
},
"line2": {
"type": "string"
},
"region": {
"type": "string"
},
"state": {
"type": "string"
},
"tag": {
"type": "string"
},
"zipCode": {
"type": "string"
}
}
},
"object.Application": {
"title": "Application",
"type": "object",
@@ -6837,6 +7186,10 @@
"type": "integer",
"format": "int64"
},
"cookieExpireInHours": {
"type": "integer",
"format": "int64"
},
"createdTime": {
"type": "string"
},
@@ -6870,6 +7223,9 @@
"enablePassword": {
"type": "boolean"
},
"enableSamlAssertionSignature": {
"type": "boolean"
},
"enableSamlC14n10": {
"type": "boolean"
},
@@ -7822,9 +8178,6 @@
"displayName": {
"type": "string"
},
"endTime": {
"type": "string"
},
"message": {
"type": "string"
},
@@ -7837,18 +8190,15 @@
"payment": {
"type": "string"
},
"planName": {
"type": "string"
},
"price": {
"type": "number",
"format": "double"
},
"pricingName": {
"type": "string"
},
"productName": {
"type": "string"
"productInfos": {
"type": "array",
"items": {
"$ref": "#/definitions/object.ProductInfo"
}
},
"products": {
"type": "array",
@@ -7856,10 +8206,10 @@
"type": "string"
}
},
"startTime": {
"state": {
"type": "string"
},
"state": {
"updateTime": {
"type": "string"
},
"user": {
@@ -7877,6 +8227,9 @@
"$ref": "#/definitions/object.AccountItem"
}
},
"accountMenu": {
"type": "string"
},
"balanceCredit": {
"type": "number",
"format": "double"
@@ -8090,9 +8443,6 @@
"invoiceUrl": {
"type": "string"
},
"isRecharge": {
"type": "boolean"
},
"message": {
"type": "string"
},
@@ -8102,6 +8452,9 @@
"order": {
"type": "string"
},
"orderObj": {
"$ref": "#/definitions/object.Order"
},
"outOrderId": {
"type": "string"
},
@@ -8127,10 +8480,13 @@
"type": "number",
"format": "double"
},
"productDisplayName": {
"type": "string"
"products": {
"type": "array",
"items": {
"type": "string"
}
},
"productName": {
"productsDisplayName": {
"type": "string"
},
"provider": {
@@ -8142,9 +8498,6 @@
"successUrl": {
"type": "string"
},
"tag": {
"type": "string"
},
"type": {
"type": "string"
},
@@ -8402,6 +8755,47 @@
}
}
},
"object.ProductInfo": {
"title": "ProductInfo",
"type": "object",
"properties": {
"currency": {
"type": "string"
},
"detail": {
"type": "string"
},
"displayName": {
"type": "string"
},
"image": {
"type": "string"
},
"isRecharge": {
"type": "boolean"
},
"name": {
"type": "string"
},
"owner": {
"type": "string"
},
"planName": {
"type": "string"
},
"price": {
"type": "number",
"format": "double"
},
"pricingName": {
"type": "string"
},
"quantity": {
"type": "integer",
"format": "int64"
}
}
},
"object.PrometheusInfo": {
"title": "PrometheusInfo",
"type": "object",
@@ -8482,6 +8876,9 @@
"emailRegex": {
"type": "string"
},
"enablePkce": {
"type": "boolean"
},
"enableProxy": {
"type": "boolean"
},
@@ -9024,6 +9421,63 @@
}
}
},
"object.Ticket": {
"title": "Ticket",
"type": "object",
"properties": {
"content": {
"type": "string"
},
"createdTime": {
"type": "string"
},
"displayName": {
"type": "string"
},
"messages": {
"type": "array",
"items": {
"$ref": "#/definitions/object.TicketMessage"
}
},
"name": {
"type": "string"
},
"owner": {
"type": "string"
},
"state": {
"type": "string"
},
"title": {
"type": "string"
},
"updatedTime": {
"type": "string"
},
"user": {
"type": "string"
}
}
},
"object.TicketMessage": {
"title": "TicketMessage",
"type": "object",
"properties": {
"author": {
"type": "string"
},
"isAdmin": {
"type": "boolean"
},
"text": {
"type": "string"
},
"timestamp": {
"type": "string"
}
}
},
"object.Token": {
"title": "Token",
"type": "object",
@@ -9132,7 +9586,7 @@
"type": "string"
},
"category": {
"type": "string"
"$ref": "#/definitions/object.TransactionCategory"
},
"createdTime": {
"type": "string"
@@ -9159,7 +9613,7 @@
"type": "string"
},
"state": {
"$ref": "#/definitions/pp.PaymentState"
"type": "string"
},
"subtype": {
"type": "string"
@@ -9175,6 +9629,15 @@
}
}
},
"object.TransactionCategory": {
"title": "TransactionCategory",
"type": "string",
"enum": [
"TransactionCategoryPurchase = \"Purchase\"",
"TransactionCategoryRecharge = \"Recharge\""
],
"example": "Purchase"
},
"object.User": {
"title": "User",
"type": "object",
@@ -9194,6 +9657,12 @@
"type": "string"
}
},
"addresses": {
"type": "array",
"items": {
"$ref": "#/definitions/object.Address"
}
},
"adfs": {
"type": "string"
},
@@ -9256,6 +9725,12 @@
"box": {
"type": "string"
},
"cart": {
"type": "array",
"items": {
"$ref": "#/definitions/object.ProductInfo"
}
},
"casdoor": {
"type": "string"
},
@@ -9569,10 +10044,10 @@
"onedrive": {
"type": "string"
},
"originalToken": {
"originalRefreshToken": {
"type": "string"
},
"originalRefreshToken": {
"originalToken": {
"type": "string"
},
"oura": {
@@ -9828,7 +10303,7 @@
"type": "object",
"properties": {
"aliases": {
"$ref": "#/definitions/217748.\u003cnil\u003e.string"
"$ref": "#/definitions/232967.\u003cnil\u003e.string"
},
"links": {
"type": "array",
@@ -9837,7 +10312,7 @@
}
},
"properties": {
"$ref": "#/definitions/217806.string.string"
"$ref": "#/definitions/233025.string.string"
},
"subject": {
"type": "string"

View File

@@ -548,6 +548,47 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/add-ticket:
post:
tags:
- Ticket API
description: add ticket
operationId: ApiController.AddTicket
parameters:
- in: body
name: body
description: The details of the ticket
required: true
schema:
$ref: '#/definitions/object.Ticket'
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/add-ticket-message:
post:
tags:
- Ticket API
description: add a message to a ticket
operationId: ApiController.AddTicketMessage
parameters:
- in: query
name: id
description: The id ( owner/name ) of the ticket
required: true
type: string
- in: body
name: body
description: The message to add
required: true
schema:
$ref: '#/definitions/object.TicketMessage'
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/add-token:
post:
tags:
@@ -1099,6 +1140,24 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/delete-ticket:
post:
tags:
- Ticket API
description: delete ticket
operationId: ApiController.DeleteTicket
parameters:
- in: body
name: body
description: The details of the ticket
required: true
schema:
$ref: '#/definitions/object.Ticket'
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/delete-token:
post:
tags:
@@ -1218,6 +1277,17 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/exit-impersonation-user:
post:
tags:
- User API
description: clear impersonation info for current session
operationId: ApiController.ExitImpersonateUser
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/faceid-signin-begin:
get:
tags:
@@ -1287,6 +1357,54 @@ paths:
type: array
items:
$ref: '#/definitions/object.Adapter'
/api/get-all-actions:
get:
tags:
- Enforcer API
description: Get all actions for a user (Casbin API)
operationId: ApiController.GetAllActions
parameters:
- in: query
name: userId
description: user id like built-in/admin
type: string
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/get-all-objects:
get:
tags:
- Enforcer API
description: Get all objects for a user (Casbin API)
operationId: ApiController.GetAllObjects
parameters:
- in: query
name: userId
description: user id like built-in/admin
type: string
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/get-all-roles:
get:
tags:
- Enforcer API
description: Get all roles for a user (Casbin API)
operationId: ApiController.GetAllRoles
parameters:
- in: query
name: userId
description: user id like built-in/admin
type: string
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/get-app-login:
get:
tags:
@@ -2498,6 +2616,42 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/util.SystemInfo'
/api/get-ticket:
get:
tags:
- Ticket API
description: get ticket
operationId: ApiController.GetTicket
parameters:
- in: query
name: id
description: The id ( owner/name ) of the ticket
required: true
type: string
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/object.Ticket'
/api/get-tickets:
get:
tags:
- Ticket API
description: get tickets
operationId: ApiController.GetTickets
parameters:
- in: query
name: owner
description: The owner of tickets
required: true
type: string
responses:
"200":
description: The Response object
schema:
type: array
items:
$ref: '#/definitions/object.Ticket'
/api/get-token:
get:
tags:
@@ -2797,6 +2951,23 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/impersonation-user:
post:
tags:
- User API
description: set impersonation user for current admin session
operationId: ApiController.ImpersonateUser
parameters:
- in: formData
name: username
description: The username to impersonate (owner/name)
required: true
type: string
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/invoice-payment:
post:
tags:
@@ -3406,8 +3577,13 @@ paths:
get:
tags:
- Login API
description: logout the current user from all applications
description: logout the current user from all applications or current session only
operationId: ApiController.SsoLogout
parameters:
- in: query
name: logoutAll
description: 'Whether to logout from all sessions. Accepted values: ''true'', ''1'', or empty (default: true). Any other value means false.'
type: string
responses:
"200":
description: The Response object
@@ -3416,8 +3592,13 @@ paths:
post:
tags:
- Login API
description: logout the current user from all applications
description: logout the current user from all applications or current session only
operationId: ApiController.SsoLogout
parameters:
- in: query
name: logoutAll
description: 'Whether to logout from all sessions. Accepted values: ''true'', ''1'', or empty (default: true). Any other value means false.'
type: string
responses:
"200":
description: The Response object
@@ -3971,6 +4152,29 @@ paths:
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/update-ticket:
post:
tags:
- Ticket API
description: update ticket
operationId: ApiController.UpdateTicket
parameters:
- in: query
name: id
description: The id ( owner/name ) of the ticket
required: true
type: string
- in: body
name: body
description: The details of the ticket
required: true
schema:
$ref: '#/definitions/object.Ticket'
responses:
"200":
description: The Response object
schema:
$ref: '#/definitions/controllers.Response'
/api/update-token:
post:
tags:
@@ -4286,12 +4490,15 @@ paths:
schema:
$ref: '#/definitions/controllers.Response'
definitions:
217748.<nil>.string:
232967.<nil>.string:
title: string
type: object
217806.string.string:
233025.string.string:
title: string
type: object
McpResponse:
title: McpResponse
type: object
Response:
title: Response
type: object
@@ -4423,6 +4630,8 @@ definitions:
type: string
regex:
type: string
tab:
type: string
viewRule:
type: string
visible:
@@ -4456,6 +4665,24 @@ definitions:
type: boolean
user:
type: string
object.Address:
title: Address
type: object
properties:
city:
type: string
line1:
type: string
line2:
type: string
region:
type: string
state:
type: string
tag:
type: string
zipCode:
type: string
object.Application:
title: Application
type: object
@@ -4473,6 +4700,9 @@ definitions:
codeResendTimeout:
type: integer
format: int64
cookieExpireInHours:
type: integer
format: int64
createdTime:
type: string
defaultGroup:
@@ -4495,6 +4725,8 @@ definitions:
type: boolean
enablePassword:
type: boolean
enableSamlAssertionSignature:
type: boolean
enableSamlC14n10:
type: boolean
enableSamlCompress:
@@ -5136,8 +5368,6 @@ definitions:
type: string
displayName:
type: string
endTime:
type: string
message:
type: string
name:
@@ -5146,23 +5376,21 @@ definitions:
type: string
payment:
type: string
planName:
type: string
price:
type: number
format: double
pricingName:
type: string
productName:
type: string
productInfos:
type: array
items:
$ref: '#/definitions/object.ProductInfo'
products:
type: array
items:
type: string
startTime:
type: string
state:
type: string
updateTime:
type: string
user:
type: string
object.Organization:
@@ -5173,6 +5401,8 @@ definitions:
type: array
items:
$ref: '#/definitions/object.AccountItem'
accountMenu:
type: string
balanceCredit:
type: number
format: double
@@ -5317,14 +5547,14 @@ definitions:
type: string
invoiceUrl:
type: string
isRecharge:
type: boolean
message:
type: string
name:
type: string
order:
type: string
orderObj:
$ref: '#/definitions/object.Order'
outOrderId:
type: string
owner:
@@ -5342,9 +5572,11 @@ definitions:
price:
type: number
format: double
productDisplayName:
type: string
productName:
products:
type: array
items:
type: string
productsDisplayName:
type: string
provider:
type: string
@@ -5352,8 +5584,6 @@ definitions:
$ref: '#/definitions/pp.PaymentState'
successUrl:
type: string
tag:
type: string
type:
type: string
user:
@@ -5526,6 +5756,34 @@ definitions:
type: string
tag:
type: string
object.ProductInfo:
title: ProductInfo
type: object
properties:
currency:
type: string
detail:
type: string
displayName:
type: string
image:
type: string
isRecharge:
type: boolean
name:
type: string
owner:
type: string
planName:
type: string
price:
type: number
format: double
pricingName:
type: string
quantity:
type: integer
format: int64
object.PrometheusInfo:
title: PrometheusInfo
type: object
@@ -5581,6 +5839,8 @@ definitions:
type: string
emailRegex:
type: string
enablePkce:
type: boolean
enableProxy:
type: boolean
enableSignAuthnRequest:
@@ -5945,6 +6205,44 @@ definitions:
type: boolean
themeType:
type: string
object.Ticket:
title: Ticket
type: object
properties:
content:
type: string
createdTime:
type: string
displayName:
type: string
messages:
type: array
items:
$ref: '#/definitions/object.TicketMessage'
name:
type: string
owner:
type: string
state:
type: string
title:
type: string
updatedTime:
type: string
user:
type: string
object.TicketMessage:
title: TicketMessage
type: object
properties:
author:
type: string
isAdmin:
type: boolean
text:
type: string
timestamp:
type: string
object.Token:
title: Token
type: object
@@ -6020,7 +6318,7 @@ definitions:
application:
type: string
category:
type: string
$ref: '#/definitions/object.TransactionCategory'
createdTime:
type: string
currency:
@@ -6038,7 +6336,7 @@ definitions:
provider:
type: string
state:
$ref: '#/definitions/pp.PaymentState'
type: string
subtype:
type: string
tag:
@@ -6047,6 +6345,13 @@ definitions:
type: string
user:
type: string
object.TransactionCategory:
title: TransactionCategory
type: string
enum:
- TransactionCategoryPurchase = "Purchase"
- TransactionCategoryRecharge = "Recharge"
example: Purchase
object.User:
title: User
type: object
@@ -6061,6 +6366,10 @@ definitions:
type: array
items:
type: string
addresses:
type: array
items:
$ref: '#/definitions/object.Address'
adfs:
type: string
affiliation:
@@ -6103,6 +6412,10 @@ definitions:
type: string
box:
type: string
cart:
type: array
items:
$ref: '#/definitions/object.ProductInfo'
casdoor:
type: string
cloudfoundry:
@@ -6312,10 +6625,10 @@ definitions:
type: string
onedrive:
type: string
originalToken:
type: string
originalRefreshToken:
type: string
originalToken:
type: string
oura:
type: string
owner:
@@ -6486,13 +6799,13 @@ definitions:
type: object
properties:
aliases:
$ref: '#/definitions/217748.<nil>.string'
$ref: '#/definitions/232967.<nil>.string'
links:
type: array
items:
$ref: '#/definitions/object.WebFingerLink'
properties:
$ref: '#/definitions/217806.string.string'
$ref: '#/definitions/233025.string.string'
subject:
type: string
object.WebFingerLink:

View File

@@ -158,7 +158,7 @@ class AdapterEditPage extends React.Component {
<React.Fragment>
<Row style={{marginTop: "20px"}} >
<Col style={{marginTop: "5px"}} span={(Setting.isMobile()) ? 22 : 2}>
{Setting.getLabel(i18next.t("provider:Type"), i18next.t("provider:Type - Tooltip"))} :
{Setting.getLabel(i18next.t("general:Type"), i18next.t("general:Type - Tooltip"))} :
</Col>
<Col span={22} >
<Select virtual={false} disabled={Setting.builtInObject(this.state.adapter)} style={{width: "100%"}} value={this.state.adapter.type} onChange={(value => {

View File

@@ -134,7 +134,7 @@ class AdapterListPage extends BaseListPage {
},
},
{
title: i18next.t("provider:Type"),
title: i18next.t("general:Type"),
dataIndex: "type",
key: "type",
width: "100px",

Some files were not shown because too many files have changed in this diff Show More