Compare commits

...

18 Commits

Author SHA1 Message Date
Robin Ye
1fb3249bfd fix: improve "Copy signup page URL" button UI in invitation edit page (#4038) 2025-08-10 23:03:13 +08:00
DacongDA
ff8f61a84c feat: fix missing search params bug in switchLoginOrganization() (#4058) 2025-08-10 22:11:06 +08:00
DacongDA
a118879dc0 feat: allow user to select organization in login page when using shared app (#4053) 2025-08-10 20:40:30 +08:00
DacongDA
386b673446 feat: support scanning code to login in the login page (#4052) 2025-08-10 00:09:43 +08:00
DacongDA
6abd46fe81 feat: fix issue that signing up with shared application will create user in wrong org (#4051) 2025-08-09 22:25:01 +08:00
IsAurora6
49d734d249 feat: standardize Resource APIs by handling path prefix internally and returning clean paths (#4047) 2025-08-08 23:31:22 +08:00
iderr
f5b4cd7fab feat: Fix GetFilteredPoliciesMulti when filtering only by ptype (#4039) 2025-08-05 22:51:40 +08:00
iderr
76f322861a feat: Refactor GetFilteredPolicies to support multiple filters via POST (#4037) 2025-08-04 19:51:25 +08:00
Seele.Clover
124c28f1e1 feat: allow Custom OAuth provider to not fill in email and avatarUrl in configuring user_mapping (#4035) 2025-08-04 12:26:12 +08:00
DacongDA
e0d9cc7ed1 feat: improve error handling on signInWithWebAuthn (#4033) 2025-08-03 01:26:18 +08:00
Seele.Clover
75c1ae4366 feat: support nested fields for configuring user_mapping in the Custom OAuth provider (#4032) 2025-08-03 00:33:52 +08:00
DacongDA
d537377b31 feat: show placeholder QR code with loading instead of "Loading" text in QR code login page (#4031) 2025-08-02 15:58:49 +08:00
raiki02
462ecce43b feat: check args in Enforce and BatchEnforce APIs (#4029) 2025-08-02 13:39:05 +08:00
raiki02
a84664b55d feat: remove toLower conversion in getPolicies() (#4030) 2025-08-02 13:38:49 +08:00
Justin Judd
941c56e69e feat(jwt): Enable using User Properties as custom claims (#3571) 2025-08-02 10:34:11 +08:00
DacongDA
a28b871a46 feat: add useGroupPathInToken boolean field in app.conf (#4026) 2025-08-02 01:40:26 +08:00
Robin Ye
387f5d58f7 feat: prevent two captcha providers are added to one single application (#4025) 2025-08-01 22:50:12 +08:00
Xiao Mao
7d846b2060 feat: implement root DSE handling and schema query in LDAP server (#4020) 2025-07-31 01:23:25 +08:00
24 changed files with 409 additions and 83 deletions

View File

@@ -40,6 +40,18 @@ func (c *ApiController) Enforce() {
enforcerId := c.Input().Get("enforcerId")
owner := c.Input().Get("owner")
params := []string{permissionId, modelId, resourceId, enforcerId, owner}
nonEmpty := 0
for _, param := range params {
if param != "" {
nonEmpty++
}
}
if nonEmpty > 1 {
c.ResponseError("Only one of the parameters (permissionId, modelId, resourceId, enforcerId, owner) should be provided")
return
}
if len(c.Ctx.Input.RequestBody) == 0 {
c.ResponseError("The request body should not be empty")
return
@@ -169,6 +181,18 @@ func (c *ApiController) BatchEnforce() {
enforcerId := c.Input().Get("enforcerId")
owner := c.Input().Get("owner")
params := []string{permissionId, modelId, enforcerId, owner}
nonEmpty := 0
for _, param := range params {
if param != "" {
nonEmpty++
}
}
if nonEmpty > 1 {
c.ResponseError("Only one of the parameters (permissionId, modelId, enforcerId, owner) should be provided")
return
}
var requests [][]string
err := json.Unmarshal(c.Ctx.Input.RequestBody, &requests)
if err != nil {

View File

@@ -17,7 +17,6 @@ package controllers
import (
"encoding/json"
"fmt"
"strings"
"github.com/beego/beego/utils/pagination"
"github.com/casdoor/casdoor/object"
@@ -200,37 +199,28 @@ func (c *ApiController) GetPolicies() {
// GetFilteredPolicies
// @Title GetFilteredPolicies
// @Tag Enforcer API
// @Description get filtered policies
// @Description get filtered policies with support for multiple filters via POST body
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param ptype query string false "Policy type, default is 'p'"
// @Param fieldIndex query int false "Field index for filtering"
// @Param fieldValues query string false "Field values for filtering, comma-separated"
// @Param body body []object.Filter true "Array of filter objects for multiple filters"
// @Success 200 {array} xormadapter.CasbinRule
// @router /get-filtered-policies [get]
// @router /get-filtered-policies [post]
func (c *ApiController) GetFilteredPolicies() {
id := c.Input().Get("id")
ptype := c.Input().Get("ptype")
fieldIndexStr := c.Input().Get("fieldIndex")
fieldValuesStr := c.Input().Get("fieldValues")
if ptype == "" {
ptype = "p"
}
fieldIndex := util.ParseInt(fieldIndexStr)
var fieldValues []string
if fieldValuesStr != "" {
fieldValues = strings.Split(fieldValuesStr, ",")
}
policies, err := object.GetFilteredPolicies(id, ptype, fieldIndex, fieldValues...)
var filters []object.Filter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &filters)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(policies)
filteredPolicies, err := object.GetFilteredPoliciesMulti(id, filters)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(filteredPolicies)
}
// UpdatePolicy

View File

@@ -20,6 +20,7 @@ import (
"fmt"
"io"
"mime"
"path"
"path/filepath"
"strings"
@@ -187,6 +188,11 @@ func (c *ApiController) DeleteResource() {
}
_, resource.Name = refineFullFilePath(resource.Name)
tag := c.Input().Get("tag")
if tag == "Direct" {
resource.Name = path.Join(provider.PathPrefix, resource.Name)
}
err = object.DeleteFile(provider, resource.Name, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())

1
go.mod
View File

@@ -52,7 +52,6 @@ require (
github.com/sendgrid/sendgrid-go v3.14.0+incompatible
github.com/shirou/gopsutil v3.21.11+incompatible
github.com/siddontang/go-log v0.0.0-20190221022429-1e957dd83bed
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/stretchr/testify v1.10.0
github.com/stripe/stripe-go/v74 v74.29.0
github.com/tealeg/xlsx v1.0.5

2
go.sum
View File

@@ -872,8 +872,6 @@ github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/skeema/knownhosts v1.3.0 h1:AM+y0rI04VksttfwjkSTNQorvGqmwATnvnAHpSgc0LY=
github.com/skeema/knownhosts v1.3.0/go.mod h1:sPINvnADmT/qYH1kfv+ePMmOBTH6Tbl7b5LvTDjFK7M=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/slack-go/slack v0.12.3 h1:92/dfFU8Q5XP6Wp5rr5/T5JHLM5c5Smtn53fhToAP88=
github.com/slack-go/slack v0.12.3/go.mod h1:hlGi5oXA+Gt+yWTPP0plCdRKmjsDxecdHxYQdlMQKOw=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=

View File

@@ -20,6 +20,7 @@ import (
"fmt"
"io"
"net/http"
"strings"
"github.com/casdoor/casdoor/util"
"github.com/mitchellh/mapstructure"
@@ -64,6 +65,25 @@ func (idp *CustomIdProvider) GetToken(code string) (*oauth2.Token, error) {
return idp.Config.Exchange(ctx, code)
}
func getNestedValue(data map[string]interface{}, path string) (interface{}, error) {
keys := strings.Split(path, ".")
var val interface{} = data
for _, key := range keys {
m, ok := val.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("path '%s' is not valid: %s is not a map", path, key)
}
val, ok = m[key]
if !ok {
return nil, fmt.Errorf("key '%s' not found in path '%s'", key, path)
}
}
return val, nil
}
type CustomUserInfo struct {
Id string `mapstructure:"id"`
Username string `mapstructure:"username"`
@@ -108,11 +128,11 @@ func (idp *CustomIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error)
// map user info
for k, v := range idp.UserMapping {
_, ok := dataMap[v]
if !ok {
return nil, fmt.Errorf("cannot find %s in user from custom provider", v)
val, err := getNestedValue(dataMap, v)
if err != nil {
return nil, fmt.Errorf("cannot find %s in user from custom provider: %v", v, err)
}
dataMap[k] = dataMap[v]
dataMap[k] = val
}
// try to parse id to string

View File

@@ -17,7 +17,6 @@ package idp
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
@@ -29,7 +28,6 @@ import (
"sync"
"time"
"github.com/skip2/go-qrcode"
"golang.org/x/oauth2"
)
@@ -324,10 +322,7 @@ func GetWechatOfficialAccountQRCode(clientId string, clientSecret string, provid
return "", "", err
}
var png []byte
png, err = qrcode.Encode(data.URL, qrcode.Medium, 256)
base64Image := base64.StdEncoding.EncodeToString(png)
return base64Image, data.Ticket, nil
return data.URL, data.Ticket, nil
}
func VerifyWechatSignature(token string, nonce string, timestamp string, signature string) bool {

View File

@@ -159,6 +159,11 @@ func handleSearch(w ldap.ResponseWriter, m *ldap.Message) {
default:
}
if strings.EqualFold(r.FilterString(), "(objectClass=*)") && (string(r.BaseObject()) == "" || strings.EqualFold(string(r.BaseObject()), "cn=Subschema")) {
handleRootSearch(w, &r, &res, m)
return
}
var isGroupSearch bool = false
filter := r.Filter()
if eq, ok := filter.(message.FilterEqualityMatch); ok && strings.EqualFold(string(eq.AttributeDesc()), "objectClass") && strings.EqualFold(string(eq.AssertionValue()), "posixGroup") {
@@ -229,6 +234,46 @@ func handleSearch(w ldap.ResponseWriter, m *ldap.Message) {
w.Write(res)
}
func handleRootSearch(w ldap.ResponseWriter, r *message.SearchRequest, res *message.SearchResultDone, m *ldap.Message) {
if len(r.Attributes()) == 0 {
w.Write(res)
return
}
firstAttr := string(r.Attributes()[0])
if string(r.BaseObject()) == "" {
// Handle special root DSE requests
if strings.EqualFold(firstAttr, "namingContexts") {
orgs, code := GetFilteredOrganizations(m)
if code != ldap.LDAPResultSuccess {
res.SetResultCode(code)
w.Write(res)
return
}
e := ldap.NewSearchResultEntry(string(r.BaseObject()))
dnlist := make([]message.AttributeValue, len(orgs))
for i, org := range orgs {
dnlist[i] = message.AttributeValue(fmt.Sprintf("ou=%s", org.Name))
}
e.AddAttribute("namingContexts", dnlist...)
w.Write(e)
} else if strings.EqualFold(firstAttr, "subschemaSubentry") {
e := ldap.NewSearchResultEntry(string(r.BaseObject()))
e.AddAttribute("subschemaSubentry", message.AttributeValue("cn=Subschema"))
w.Write(e)
}
} else if strings.EqualFold(firstAttr, "objectclasses") && strings.EqualFold(string(r.BaseObject()), "cn=Subschema") {
e := ldap.NewSearchResultEntry(string(r.BaseObject()))
e.AddAttribute("objectClasses", []message.AttributeValue{
"( 1.3.6.1.1.1.2.0 NAME 'posixAccount' DESC 'Abstraction of an account with POSIX attributes' SUP top AUXILIARY MUST ( cn $ uid $ uidNumber $ gidNumber $ homeDirectory ) MAY ( userPassword $ loginShell $ gecos $ description ) )",
"( 1.3.6.1.1.1.2.2 NAME 'posixGroup' DESC 'Abstraction of a group of accounts' SUP top STRUCTURAL MUST ( cn $ gidNumber ) MAY ( userPassword $ memberUid $ description ) )",
}...)
w.Write(e)
}
w.Write(res)
}
func hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))

View File

@@ -358,6 +358,29 @@ func GetFilteredGroups(m *ldap.Message, baseDN string, filterStr string) ([]*obj
return groups, ldap.LDAPResultSuccess
}
func GetFilteredOrganizations(m *ldap.Message) ([]*object.Organization, int) {
if m.Client.IsGlobalAdmin {
organizations, err := object.GetOrganizations("")
if err != nil {
panic(err)
}
return organizations, ldap.LDAPResultSuccess
} else if m.Client.IsOrgAdmin {
requestUserId := util.GetId(m.Client.OrgName, m.Client.UserName)
user, err := object.GetUser(requestUserId)
if err != nil {
panic(err)
}
organization, err := object.GetOrganizationByUser(user)
if err != nil {
panic(err)
}
return []*object.Organization{organization}, ldap.LDAPResultSuccess
} else {
return nil, ldap.LDAPResultInsufficientAccessRights
}
}
// get user password with hash type prefix
// TODO not handle salt yet
// @return {md5}5f4dcc3b5aa765d61d8327deb882cf99

View File

@@ -16,6 +16,7 @@ package object
import (
"fmt"
"slices"
"github.com/casbin/casbin/v2"
"github.com/casdoor/casdoor/util"
@@ -206,6 +207,13 @@ func GetPolicies(id string) ([]*xormadapter.CasbinRule, error) {
return res, nil
}
// Filter represents filter criteria with optional policy type
type Filter struct {
Ptype string `json:"ptype,omitempty"`
FieldIndex *int `json:"fieldIndex,omitempty"`
FieldValues []string `json:"fieldValues"`
}
func GetFilteredPolicies(id string, ptype string, fieldIndex int, fieldValues ...string) ([]*xormadapter.CasbinRule, error) {
enforcer, err := GetInitializedEnforcer(id)
if err != nil {
@@ -236,6 +244,78 @@ func GetFilteredPolicies(id string, ptype string, fieldIndex int, fieldValues ..
return res, nil
}
// GetFilteredPoliciesMulti applies multiple filters to policies
// Doing this in our loop is more efficient than using GetFilteredGroupingPolicy / GetFilteredPolicy which
// iterates over all policies again and again
func GetFilteredPoliciesMulti(id string, filters []Filter) ([]*xormadapter.CasbinRule, error) {
// Get all policies first
allPolicies, err := GetPolicies(id)
if err != nil {
return nil, err
}
// Filter policies based on multiple criteria
var filteredPolicies []*xormadapter.CasbinRule
if len(filters) == 0 {
// No filters, return all policies
return allPolicies, nil
} else {
for _, policy := range allPolicies {
matchesAllFilters := true
for _, filter := range filters {
// Default policy type if unspecified
if filter.Ptype == "" {
filter.Ptype = "p"
}
// Always check policy type
if policy.Ptype != filter.Ptype {
matchesAllFilters = false
break
}
// If FieldIndex is nil, only filter via ptype (skip field-value checks)
if filter.FieldIndex == nil {
continue
}
fieldIndex := *filter.FieldIndex
// If FieldIndex is out of range, also only filter via ptype
if fieldIndex < 0 || fieldIndex > 5 {
continue
}
var fieldValue string
switch fieldIndex {
case 0:
fieldValue = policy.V0
case 1:
fieldValue = policy.V1
case 2:
fieldValue = policy.V2
case 3:
fieldValue = policy.V3
case 4:
fieldValue = policy.V4
case 5:
fieldValue = policy.V5
}
// When FieldIndex is provided and valid, enforce FieldValues (if any)
if len(filter.FieldValues) > 0 && !slices.Contains(filter.FieldValues, fieldValue) {
matchesAllFilters = false
break
}
}
if matchesAllFilters {
filteredPolicies = append(filteredPolicies, policy)
}
}
}
return filteredPolicies, nil
}
func UpdatePolicy(id string, ptype string, oldPolicy []string, newPolicy []string) (bool, error) {
enforcer, err := GetInitializedEnforcer(id)
if err != nil {

View File

@@ -125,10 +125,10 @@ func getPolicies(permission *Permission) [][]string {
for _, action := range permission.Actions {
if domainExist {
for _, domain := range permission.Domains {
policies = append(policies, []string{userOrRole, domain, resource, strings.ToLower(action), strings.ToLower(permission.Effect), permissionId})
policies = append(policies, []string{userOrRole, domain, resource, action, strings.ToLower(permission.Effect), permissionId})
}
} else {
policies = append(policies, []string{userOrRole, resource, strings.ToLower(action), strings.ToLower(permission.Effect), "", permissionId})
policies = append(policies, []string{userOrRole, resource, action, strings.ToLower(permission.Effect), "", permissionId})
}
}
}

View File

@@ -31,9 +31,11 @@ func GetDirectResources(owner string, user string, provider *Provider, prefix st
fullPathPrefix := util.UrlJoin(provider.PathPrefix, prefix)
objects, err := storageProvider.List(fullPathPrefix)
for _, obj := range objects {
name := strings.TrimPrefix(obj.Path, "/")
name = strings.TrimPrefix(name, provider.PathPrefix+"/")
resource := &Resource{
Owner: owner,
Name: strings.TrimPrefix(obj.Path, "/"),
Name: name,
CreatedTime: obj.LastModified.Local().Format(time.RFC3339),
User: user,
Provider: "",

View File

@@ -20,6 +20,7 @@ import (
"strings"
"time"
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/util"
"github.com/golang-jwt/jwt/v5"
)
@@ -341,10 +342,31 @@ func getClaimsCustom(claims Claims, tokenField []string) jwt.MapClaims {
res["provider"] = claims.Provider
for _, field := range tokenField {
userField := userValue.FieldByName(field)
if userField.IsValid() {
newfield := util.SnakeToCamel(util.CamelToSnakeCase(field))
res[newfield] = userField.Interface()
if strings.HasPrefix(field, "Properties") {
/*
Use selected properties fields as custom claims.
Converts `Properties.my_field` to custom claim with name `my_field`.
*/
parts := strings.Split(field, ".")
if len(parts) != 2 || parts[0] != "Properties" { // Either too many segments, or not properly scoped to `Properties`, so skip.
continue
}
base, fieldName := parts[0], parts[1]
mField := userValue.FieldByName(base)
if !mField.IsValid() { // Can't find `Properties` field, so skip.
continue
}
finalField := mField.MapIndex(reflect.ValueOf(fieldName))
if finalField.IsValid() { // // Provided field within `Properties` exists, add claim.
res[fieldName] = finalField.Interface()
}
} else { // Use selected user field as claims.
userField := userValue.FieldByName(field)
if userField.IsValid() {
newfield := util.SnakeToCamel(util.CamelToSnakeCase(field))
res[newfield] = userField.Interface()
}
}
}
@@ -381,6 +403,14 @@ func generateJwtToken(application *Application, user *User, provider string, non
refreshExpireTime = expireTime
}
if conf.GetConfigBool("useGroupPathInToken") {
groupPath, err := user.GetUserFullGroupPath()
if err != nil {
return "", "", "", err
}
user.Groups = groupPath
}
user = refineUser(user)
_, originBackend := getOriginFromHost(host)

View File

@@ -1331,6 +1331,56 @@ func (user *User) CheckUserFace(faceIdImage []string, provider *Provider) (bool,
return false, nil
}
func (user *User) GetUserFullGroupPath() ([]string, error) {
if len(user.Groups) == 0 {
return []string{}, nil
}
var orgGroups []*Group
orgGroups, err := GetGroups(user.Owner)
if err != nil {
return nil, err
}
groupMap := make(map[string]Group)
for _, group := range orgGroups {
groupMap[group.Name] = *group
}
var groupFullPath []string
for _, groupId := range user.Groups {
_, groupName := util.GetOwnerAndNameFromIdNoCheck(groupId)
group, ok := groupMap[groupName]
if !ok {
continue
}
groupPath := groupName
curGroup, ok := groupMap[group.ParentId]
if !ok {
return []string{}, fmt.Errorf("group:Group %s not exist", group.ParentId)
}
for {
groupPath = util.GetId(curGroup.Name, groupPath)
if curGroup.IsTopGroup {
break
}
curGroup, ok = groupMap[curGroup.ParentId]
if !ok {
return []string{}, fmt.Errorf("group:Group %s not exist", curGroup.ParentId)
}
}
groupPath = util.GetId(curGroup.Owner, groupPath)
groupFullPath = append(groupFullPath, groupPath)
}
return groupFullPath, nil
}
func GenerateIdForNewUser(application *Application) (string, error) {
if application == nil || application.GetSignupItemRule("ID") != "Incremental" {
return util.GenerateId(), nil

View File

@@ -160,7 +160,7 @@ func initAPI() {
beego.Router("/api/add-adapter", &controllers.ApiController{}, "POST:AddAdapter")
beego.Router("/api/delete-adapter", &controllers.ApiController{}, "POST:DeleteAdapter")
beego.Router("/api/get-policies", &controllers.ApiController{}, "GET:GetPolicies")
beego.Router("/api/get-filtered-policies", &controllers.ApiController{}, "GET:GetFilteredPolicies")
beego.Router("/api/get-filtered-policies", &controllers.ApiController{}, "POST:GetFilteredPolicies")
beego.Router("/api/update-policy", &controllers.ApiController{}, "POST:UpdatePolicy")
beego.Router("/api/add-policy", &controllers.ApiController{}, "POST:AddPolicy")
beego.Router("/api/remove-policy", &controllers.ApiController{}, "POST:RemovePolicy")

View File

@@ -14,6 +14,7 @@
import React from "react";
import {Button, Card, Col, Input, InputNumber, Row, Select} from "antd";
import {CopyOutlined} from "@ant-design/icons";
import * as InvitationBackend from "./backend/InvitationBackend";
import * as OrganizationBackend from "./backend/OrganizationBackend";
import * as ApplicationBackend from "./backend/ApplicationBackend";
@@ -130,9 +131,6 @@ class InvitationEditPage extends React.Component {
{this.state.mode === "add" ? i18next.t("invitation:New Invitation") : i18next.t("invitation:Edit Invitation")}&nbsp;&nbsp;&nbsp;&nbsp;
<Button onClick={() => this.submitInvitationEdit(false)}>{i18next.t("general:Save")}</Button>
<Button style={{marginLeft: "20px"}} type="primary" onClick={() => this.submitInvitationEdit(true)}>{i18next.t("general:Save & Exit")}</Button>
<Button style={{marginLeft: "20px"}} onClick={_ => this.copySignupLink()}>
{i18next.t("application:Copy signup page URL")}
</Button>
{this.state.mode === "add" ? <Button style={{marginLeft: "20px"}} onClick={() => this.deleteInvitation()}>{i18next.t("general:Cancel")}</Button> : null}
</div>
} style={(Setting.isMobile()) ? {margin: "5px"} : {}} type="inner">
@@ -192,6 +190,15 @@ class InvitationEditPage extends React.Component {
}} />
</Col>
</Row>
<Row style={{marginTop: "20px"}} >
<Col style={{marginTop: "5px"}} span={(Setting.isMobile()) ? 22 : 2}>
</Col>
<Col span={22} >
<Button style={{marginBottom: "10px"}} type="primary" shape="round" icon={<CopyOutlined />} onClick={_ => this.copySignupLink()}>
{i18next.t("application:Copy signup page URL")}
</Button>
</Col>
</Row>
<Row style={{marginTop: "20px"}} >
<Col style={{marginTop: "5px"}} span={(Setting.isMobile()) ? 22 : 2}>
{Setting.getLabel(i18next.t("invitation:Quota"), i18next.t("invitation:Quota - Tooltip"))} :
@@ -337,9 +344,6 @@ class InvitationEditPage extends React.Component {
<div style={{marginTop: "20px", marginLeft: "40px"}}>
<Button size="large" onClick={() => this.submitInvitationEdit(false)}>{i18next.t("general:Save")}</Button>
<Button style={{marginLeft: "20px"}} type="primary" size="large" onClick={() => this.submitInvitationEdit(true)}>{i18next.t("general:Save & Exit")}</Button>
<Button style={{marginLeft: "20px"}} size="large" onClick={_ => this.copySignupLink()}>
{i18next.t("application:Copy signup page URL")}
</Button>
{this.state.mode === "add" ? <Button style={{marginLeft: "20px"}} size="large" onClick={() => this.deleteInvitation()}>{i18next.t("general:Cancel")}</Button> : null}
</div>
</div>

View File

@@ -174,7 +174,11 @@ class ProviderEditPage extends React.Component {
}
}
provider.userMapping[key] = value;
if (value === "") {
delete provider.userMapping[key];
} else {
provider.userMapping[key] = value;
}
this.setState({
provider: provider,

View File

@@ -1296,6 +1296,9 @@ export function renderSignupLink(application, text) {
} else {
if (application.signupUrl === "") {
url = `/signup/${application.name}`;
if (application.isShared) {
url = `/signup/${application.name}-org-${application.organization}`;
}
} else {
url = application.signupUrl;
}

View File

@@ -595,6 +595,32 @@ class LoginPage extends React.Component {
return null;
}
switchLoginOrganization(name) {
const searchParams = new URLSearchParams(window.location.search);
const clientId = searchParams.get("client_id");
if (clientId) {
const clientIdSplited = clientId.split("-org-");
searchParams.set("client_id", `${clientIdSplited[0]}-org-${name}`);
Setting.goToLink(`/login/oauth/authorize?${searchParams.toString()}`);
return;
}
const application = this.getApplicationObj();
if (window.location.pathname.startsWith("/login/saml/authorize")) {
Setting.goToLink(`/login/saml/authorize/${name}/${application.name}-org-${name}?${searchParams.toString()}`);
return;
}
if (window.location.pathname.startsWith("/cas")) {
Setting.goToLink(`/cas/${application.name}-org-${name}/${name}/login?${searchParams.toString()}`);
return;
}
searchParams.set("orgChoiceMode", "None");
Setting.goToLink(`/login/${name}?${searchParams.toString()}`);
}
renderFormItem(application, signinItem) {
if (!signinItem.visible && signinItem.name !== "Forgot password?") {
return null;
@@ -648,6 +674,9 @@ class LoginPage extends React.Component {
)
;
} else if (signinItem.name === "Username") {
if (this.state.loginMethod === "wechat") {
return (<WeChatLoginPanel application={application} loginMethod={this.state.loginMethod} />);
}
return (
<div key={resultItemKey}>
<div dangerouslySetInnerHTML={{__html: ("<style>" + signinItem.customCss?.replaceAll("<style>", "").replaceAll("</style>", "") + "</style>")}} />
@@ -750,6 +779,9 @@ class LoginPage extends React.Component {
} else if (signinItem.name === "Agreement") {
return AgreementModal.isAgreementRequired(application) ? AgreementModal.renderAgreementFormItem(application, true, {}, this) : null;
} else if (signinItem.name === "Login button") {
if (this.state.loginMethod === "wechat") {
return null;
}
return (
<Form.Item key={resultItemKey} className="login-button-box">
<div dangerouslySetInnerHTML={{__html: ("<style>" + signinItem.customCss?.replaceAll("<style>", "").replaceAll("</style>", "") + "</style>")}} />
@@ -848,6 +880,17 @@ class LoginPage extends React.Component {
{this.renderFooter(application, signinItem)}
</div>
);
} else if (signinItem.name === "Select organization") {
return (
<Form.Item>
<div key={resultItemKey} style={{width: "100%"}} className="login-organization-select">
<OrganizationSelect style={{width: "100%"}} initValue={application.organization}
onSelect={(value) => {
this.switchLoginOrganization(value);
}} />
</div>
</Form.Item>
);
}
}
@@ -896,10 +939,6 @@ class LoginPage extends React.Component {
loginWidth += 10;
}
if (this.state.loginMethod === "wechat") {
return (<WeChatLoginPanel application={application} renderFormItem={this.renderFormItem.bind(this)} loginMethod={this.state.loginMethod} loginWidth={loginWidth} renderMethodChoiceBox={this.renderMethodChoiceBox.bind(this)} />);
}
return (
<Form
name="normal_login"
@@ -1109,8 +1148,7 @@ class LoginPage extends React.Component {
.then(res => res.json())
.then((credentialRequestOptions) => {
if ("status" in credentialRequestOptions) {
Setting.showMessage("error", credentialRequestOptions.msg);
throw credentialRequestOptions.status.msg;
return Promise.reject(new Error(credentialRequestOptions.msg));
}
credentialRequestOptions.publicKey.challenge = UserWebauthnBackend.webAuthnBufferDecode(credentialRequestOptions.publicKey.challenge);
@@ -1169,7 +1207,7 @@ class LoginPage extends React.Component {
Setting.showMessage("error", `${i18next.t("general:Failed to connect to server")}${error}`);
});
}).catch(error => {
Setting.showMessage("error", `${error}`);
Setting.showMessage("error", `${error.message}`);
}).finally(() => {
this.setState({
loginLoading: false,
@@ -1240,6 +1278,7 @@ class LoginPage extends React.Component {
[generateItemKey("WebAuthn", "None"), {label: i18next.t("login:WebAuthn"), key: "webAuthn"}],
[generateItemKey("LDAP", "None"), {label: i18next.t("login:LDAP"), key: "ldap"}],
[generateItemKey("Face ID", "None"), {label: i18next.t("login:Face ID"), key: "faceId"}],
[generateItemKey("WeChat", "Tab"), {label: i18next.t("login:WeChat"), key: "wechat"}],
[generateItemKey("WeChat", "None"), {label: i18next.t("login:WeChat"), key: "wechat"}],
]);
@@ -1404,6 +1443,8 @@ class LoginPage extends React.Component {
);
}
const wechatSigninMethods = application.signinMethods?.filter(method => method.name === "WeChat" && method.rule === "Login page");
return (
<React.Fragment>
<CustomGithubCorner />
@@ -1421,6 +1462,15 @@ class LoginPage extends React.Component {
}
</div>
</div>
{
wechatSigninMethods?.length > 0 ? (<div style={{display: "flex", justifyContent: "center", alignItems: "center"}}>
<div>
<h3 style={{textAlign: "center", width: 320}}>{i18next.t("provider:Please use WeChat to scan the QR code and follow the official account for sign in")}</h3>
<WeChatLoginPanel application={application} loginMethod={this.state.loginMethod} />
</div>
</div>
) : null
}
</div>
</div>
</React.Fragment>

View File

@@ -13,7 +13,7 @@
// limitations under the License.
import React from "react";
import {Alert, Button, Modal, Result} from "antd";
import {Alert, Button, Modal, QRCode, Result} from "antd";
import i18next from "i18next";
import {getWechatMessageEvent} from "./AuthBackend";
import * as Setting from "../Setting";
@@ -217,7 +217,7 @@ export async function WechatOfficialAccountModal(application, provider, method)
title: i18next.t("provider:Please use WeChat to scan the QR code and follow the official account for sign in"),
content: (
<div style={{marginRight: "34px"}}>
<img src = {"data:image/png;base64," + res.data} alt="Wechat QR code" style={{width: "100%"}} />
<QRCode style={{padding: "20px", margin: "auto"}} bordered={false} value={res.data} size={230} />
</div>
),
onOk() {

View File

@@ -16,13 +16,14 @@ import React from "react";
import * as AuthBackend from "./AuthBackend";
import i18next from "i18next";
import * as Util from "./Util";
import {QRCode} from "antd";
class WeChatLoginPanel extends React.Component {
constructor(props) {
super(props);
this.state = {
qrCode: null,
loading: false,
status: "loading",
ticket: null,
};
this.pollingTimer = null;
@@ -57,47 +58,38 @@ class WeChatLoginPanel extends React.Component {
const {application} = this.props;
const wechatProviderItem = application?.providers?.find(p => p.provider?.type === "WeChat");
if (wechatProviderItem) {
this.setState({loading: true, qrCode: null, ticket: null});
this.setState({status: "loading", qrCode: null, ticket: null});
AuthBackend.getWechatQRCode(`${wechatProviderItem.provider.owner}/${wechatProviderItem.provider.name}`).then(res => {
if (res.status === "ok" && res.data) {
this.setState({qrCode: res.data, loading: false, ticket: res.data2});
this.setState({qrCode: res.data, status: "active", ticket: res.data2});
this.clearPolling();
this.pollingTimer = setInterval(() => {
Util.getEvent(application, wechatProviderItem.provider, res.data2, "signup");
}, 1000);
} else {
this.setState({qrCode: null, loading: false, ticket: null});
this.setState({qrCode: null, status: "expired", ticket: null});
this.clearPolling();
}
}).catch(() => {
this.setState({qrCode: null, loading: false, ticket: null});
this.setState({qrCode: null, status: "expired", ticket: null});
this.clearPolling();
});
}
}
render() {
const {application, loginWidth = 320} = this.props;
const {loading, qrCode} = this.state;
const {loginWidth = 320} = this.props;
const {status, qrCode} = this.state;
return (
<div style={{width: loginWidth, margin: "0 auto", textAlign: "center", marginTop: 16}}>
{application.signinItems?.filter(item => item.name === "Logo").map(signinItem => this.props.renderFormItem(application, signinItem))}
{this.props.renderMethodChoiceBox()}
{application.signinItems?.filter(item => item.name === "Languages").map(signinItem => this.props.renderFormItem(application, signinItem))}
{loading ? (
<div style={{marginTop: 16}}>
<span>{i18next.t("login:Loading")}</span>
<div style={{marginTop: 2}}>
<QRCode style={{margin: "auto", marginTop: "20px", marginBottom: "20px"}} bordered={false} status={status} value={qrCode ?? " "} size={230} />
<div style={{marginTop: 8}}>
<a onClick={e => {e.preventDefault(); this.fetchQrCode();}}>
{i18next.t("login:Refresh")}
</a>
</div>
) : qrCode ? (
<div style={{marginTop: 2}}>
<img src={`data:image/png;base64,${qrCode}`} alt="WeChat QR code" style={{width: 250, height: 250}} />
<div style={{marginTop: 8}}>
<a onClick={e => {e.preventDefault(); this.fetchQrCode();}}>
{i18next.t("login:Refresh")}
</a>
</div>
</div>
) : null}
</div>
</div>
);
}

View File

@@ -88,7 +88,10 @@ class ProviderTable extends React.Component {
}
}} >
{
Setting.getDeduplicatedArray(this.props.providers, table, "name").map((provider, index) => <Option key={index} value={provider.name}>{provider.name}</Option>)
Setting.getDeduplicatedArray(this.props.providers, table, "name").filter(provider => provider.category !== "Captcha" || !table.some(tableItem => {
const existingProvider = Setting.getArrayItem(this.props.providers, "name", tableItem.name);
return existingProvider && existingProvider.category === "Captcha";
})).map((provider, index) => <Option key={index} value={provider.name}>{provider.name}</Option>)
}
</Select>
);

View File

@@ -96,6 +96,8 @@ class SigninMethodTable extends React.Component {
this.updateField(table, index, "displayName", value);
if (value === "Verification code" || value === "Password") {
this.updateField(table, index, "rule", "All");
} else if (value === "WeChat") {
this.updateField(table, index, "rule", "Tab");
} else {
this.updateField(table, index, "rule", "None");
}
@@ -139,6 +141,11 @@ class SigninMethodTable extends React.Component {
{id: "Non-LDAP", name: i18next.t("general:Non-LDAP")},
{id: "Hide password", name: i18next.t("general:Hide password")},
];
} else if (record.name === "WeChat") {
options = [
{id: "Tab", name: i18next.t("general:Tab")},
{id: "Login page", name: i18next.t("general:Login page")},
];
}
if (options.length === 0) {

View File

@@ -119,6 +119,7 @@ class SigninTable extends React.Component {
{name: "Signup link", displayName: i18next.t("general:Signup link")},
{name: "Captcha", displayName: i18next.t("general:Captcha")},
{name: "Auto sign in", displayName: i18next.t("login:Auto sign in")},
{name: "Select organization", displayName: i18next.t("login:Select organization")},
];
const getItemDisplayName = (text) => {