mirror of
https://github.com/casdoor/casdoor.git
synced 2025-07-16 06:33:50 +08:00
Compare commits
121 Commits
Author | SHA1 | Date | |
---|---|---|---|
86b5d72e5d | |||
6bc4e646e5 | |||
0841eb5c30 | |||
4015c221f7 | |||
dcd6328498 | |||
8080927890 | |||
a95c5b05a9 | |||
865a65d399 | |||
e8b9c67671 | |||
e5ff49f7a7 | |||
9f7924a6e0 | |||
377e200837 | |||
93a76de044 | |||
35bef969fd | |||
4dca3bd3f7 | |||
5de417ecf7 | |||
bf24594fb4 | |||
4a87b4790e | |||
fde8c4b5f6 | |||
55a84644e1 | |||
ca87dd7dea | |||
32af4a766e | |||
4d035bf66d | |||
743dcc9725 | |||
d43d7d1ae9 | |||
c906f1e5d2 | |||
37a26e2a91 | |||
e7018e3de4 | |||
3a64e4dcd8 | |||
380cdc5f7e | |||
3602d9b9a7 | |||
8a9cc2eb8f | |||
4f9a13f18a | |||
a4fc04474e | |||
bf5d4eea48 | |||
0e40a1d922 | |||
ab777c1d73 | |||
ca0fa5fc40 | |||
cfbce79e32 | |||
efc07f0919 | |||
a783315fa2 | |||
1d0af9cf7b | |||
4d48517be9 | |||
178cf7945d | |||
ab5af979c8 | |||
e31aaf5657 | |||
eaf5cb66f3 | |||
83a6b757a4 | |||
2a0dcd746f | |||
22f5ad06ec | |||
18aa70dfb2 | |||
697b3e4998 | |||
d48d515c36 | |||
a5d166c35f | |||
4915963c52 | |||
759a1421e5 | |||
c14bf9fdab | |||
e19f07c521 | |||
39ab71c5db | |||
2c97f8a8b7 | |||
21392dcc14 | |||
953d3d5bc5 | |||
ddee97f544 | |||
c58a6d8725 | |||
a5ff9549c1 | |||
fe57dcbff4 | |||
f8c4ca0f00 | |||
e738c42bd8 | |||
cbc8c58e85 | |||
07c90e048f | |||
a33076ada4 | |||
9cabc4035f | |||
274096fe9d | |||
661abd6b6e | |||
4122c94205 | |||
68ef5f8311 | |||
e35b058ab4 | |||
7d1f368bc2 | |||
0bd86baf4d | |||
adf036d8c7 | |||
2d19d366d4 | |||
db37f53d6c | |||
eacd5f59db | |||
9024010081 | |||
3aab6c8687 | |||
7391773f0e | |||
de8163a19b | |||
07abe06332 | |||
0bc29465e5 | |||
c37b0111a7 | |||
47d1448c02 | |||
eb15afec34 | |||
e1c54744dc | |||
612b5f5c2e | |||
bd38552db5 | |||
256b433e57 | |||
63161d6135 | |||
5640d258bb | |||
f85f4c0cf8 | |||
0720794e75 | |||
940aa2bc2d | |||
db44957b1f | |||
e5e1fdae76 | |||
80f01074fa | |||
d943d5cc61 | |||
19ed35f964 | |||
5757021e87 | |||
259a4e1307 | |||
034d822dd5 | |||
a8502d1173 | |||
3c2f7b7fc8 | |||
fbc73de3bb | |||
479daf4fa4 | |||
d129202b95 | |||
c1f553440e | |||
7dcae2d183 | |||
5ec0c7a890 | |||
051752340d | |||
c87c001da3 | |||
12bc419659 | |||
d5f18f2d64 |
26
.github/workflows/build.yml
vendored
26
.github/workflows/build.yml
vendored
@ -3,9 +3,33 @@ name: Build
|
|||||||
on: [push, pull_request]
|
on: [push, pull_request]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
|
||||||
|
go-tests:
|
||||||
|
name: Running Go tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:5.7
|
||||||
|
env:
|
||||||
|
MYSQL_DATABASE: casdoor
|
||||||
|
MYSQL_ROOT_PASSWORD: 123456
|
||||||
|
ports:
|
||||||
|
- 3306:3306
|
||||||
|
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- uses: actions/setup-go@v2
|
||||||
|
with:
|
||||||
|
go-version: '^1.16.5'
|
||||||
|
- name: Tests
|
||||||
|
run: |
|
||||||
|
go test -v $(go list ./...) -tags skipCi
|
||||||
|
working-directory: ./
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
name: Front-end
|
name: Front-end
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
needs: [ go-tests ]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- uses: actions/setup-node@v2
|
- uses: actions/setup-node@v2
|
||||||
@ -14,10 +38,10 @@ jobs:
|
|||||||
- run: yarn install && CI=false yarn run build
|
- run: yarn install && CI=false yarn run build
|
||||||
working-directory: ./web
|
working-directory: ./web
|
||||||
|
|
||||||
|
|
||||||
backend:
|
backend:
|
||||||
name: Back-end
|
name: Back-end
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
needs: [ go-tests ]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- uses: actions/setup-go@v2
|
- uses: actions/setup-go@v2
|
||||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -13,7 +13,8 @@
|
|||||||
*.out
|
*.out
|
||||||
|
|
||||||
# Dependency directories (remove the comment below to include it)
|
# Dependency directories (remove the comment below to include it)
|
||||||
# vendor/
|
vendor/
|
||||||
|
bin/
|
||||||
|
|
||||||
.idea/
|
.idea/
|
||||||
*.iml
|
*.iml
|
||||||
|
42
.golangci.yml
Normal file
42
.golangci.yml
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- deadcode
|
||||||
|
- dupl
|
||||||
|
- errcheck
|
||||||
|
- goconst
|
||||||
|
- gocyclo
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
|
- gosec
|
||||||
|
- gosimple
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- lll
|
||||||
|
- misspell
|
||||||
|
- nakedret
|
||||||
|
- prealloc
|
||||||
|
- staticcheck
|
||||||
|
- structcheck
|
||||||
|
- typecheck
|
||||||
|
- unconvert
|
||||||
|
- unparam
|
||||||
|
- unused
|
||||||
|
- varcheck
|
||||||
|
- revive
|
||||||
|
- exportloopref
|
||||||
|
run:
|
||||||
|
deadline: 5m
|
||||||
|
skip-dirs:
|
||||||
|
- api
|
||||||
|
# skip-files:
|
||||||
|
# - ".*_test\\.go$"
|
||||||
|
modules-download-mode: vendor
|
||||||
|
# all available settings of specific linters
|
||||||
|
linters-settings:
|
||||||
|
lll:
|
||||||
|
# max line length, lines longer will be reported. Default is 120.
|
||||||
|
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
|
||||||
|
line-length: 150
|
||||||
|
# tab width in spaces. Default to 1.
|
||||||
|
tab-width: 1
|
@ -7,12 +7,14 @@ RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GOPROXY=https://goproxy.cn,direct go b
|
|||||||
FROM node:16.13.0 AS FRONT
|
FROM node:16.13.0 AS FRONT
|
||||||
WORKDIR /web
|
WORKDIR /web
|
||||||
COPY ./web .
|
COPY ./web .
|
||||||
RUN yarn config set registry https://registry.npm.taobao.org
|
RUN yarn config set registry https://registry.npmmirror.com
|
||||||
RUN yarn install && yarn run build
|
RUN yarn install && yarn run build
|
||||||
|
|
||||||
|
|
||||||
FROM debian:latest AS ALLINONE
|
FROM debian:latest AS ALLINONE
|
||||||
RUN apt update && apt install -y mariadb-server mariadb-client&&mkdir -p web/build && chmod 777 /tmp
|
RUN apt update
|
||||||
|
RUN apt install -y ca-certificates && update-ca-certificates
|
||||||
|
RUN apt install -y mariadb-server mariadb-client && mkdir -p web/build && chmod 777 /tmp
|
||||||
LABEL MAINTAINER="https://casdoor.org/"
|
LABEL MAINTAINER="https://casdoor.org/"
|
||||||
COPY --from=BACK /go/src/casdoor/ ./
|
COPY --from=BACK /go/src/casdoor/ ./
|
||||||
COPY --from=BACK /usr/bin/wait-for-it ./
|
COPY --from=BACK /usr/bin/wait-for-it ./
|
||||||
@ -26,6 +28,7 @@ mysqladmin -u root password ${MYSQL_ROOT_PASSWORD} &&\
|
|||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
RUN sed -i 's/https/http/' /etc/apk/repositories
|
RUN sed -i 's/https/http/' /etc/apk/repositories
|
||||||
RUN apk add curl
|
RUN apk add curl
|
||||||
|
RUN apk add ca-certificates && update-ca-certificates
|
||||||
LABEL MAINTAINER="https://casdoor.org/"
|
LABEL MAINTAINER="https://casdoor.org/"
|
||||||
|
|
||||||
COPY --from=BACK /go/src/casdoor/ ./
|
COPY --from=BACK /go/src/casdoor/ ./
|
||||||
@ -33,4 +36,3 @@ COPY --from=BACK /usr/bin/wait-for-it ./
|
|||||||
RUN mkdir -p web/build && apk add --no-cache bash coreutils
|
RUN mkdir -p web/build && apk add --no-cache bash coreutils
|
||||||
COPY --from=FRONT /web/build /web/build
|
COPY --from=FRONT /web/build /web/build
|
||||||
CMD ./server
|
CMD ./server
|
||||||
|
|
||||||
|
113
Makefile
Normal file
113
Makefile
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
|
||||||
|
# Image URL to use all building/pushing image targets
|
||||||
|
REGISTRY ?= casbin
|
||||||
|
IMG ?= casdoor
|
||||||
|
IMG_TAG ?=$(shell git --no-pager log -1 --format="%ad" --date=format:"%Y%m%d")-$(shell git describe --tags --always --dirty --abbrev=6)
|
||||||
|
NAMESPACE ?= casdoor
|
||||||
|
APP ?= casdoor
|
||||||
|
HOST ?= test.com
|
||||||
|
|
||||||
|
|
||||||
|
# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set)
|
||||||
|
ifeq (,$(shell go env GOBIN))
|
||||||
|
GOBIN=$(shell go env GOPATH)/bin
|
||||||
|
else
|
||||||
|
GOBIN=$(shell go env GOBIN)
|
||||||
|
endif
|
||||||
|
|
||||||
|
# Setting SHELL to bash allows bash commands to be executed by recipes.
|
||||||
|
# This is a requirement for 'setup-envtest.sh' in the test target.
|
||||||
|
# Options are set to exit when a recipe line exits non-zero or a piped command fails.
|
||||||
|
SHELL = /usr/bin/env bash -o pipefail
|
||||||
|
.SHELLFLAGS = -ec
|
||||||
|
|
||||||
|
.PHONY: all
|
||||||
|
all: docker-build docker-push deploy
|
||||||
|
|
||||||
|
##@ General
|
||||||
|
|
||||||
|
# The help target prints out all targets with their descriptions organized
|
||||||
|
# beneath their categories. The categories are represented by '##@' and the
|
||||||
|
# target descriptions by '##'. The awk commands is responsible for reading the
|
||||||
|
# entire set of makefiles included in this invocation, looking for lines of the
|
||||||
|
# file as xyz: ## something, and then pretty-format the target and help. Then,
|
||||||
|
# if there's a line with ##@ something, that gets pretty-printed as a category.
|
||||||
|
# More info on the usage of ANSI control characters for terminal formatting:
|
||||||
|
# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters
|
||||||
|
# More info on the awk command:
|
||||||
|
# http://linuxcommand.org/lc3_adv_awk.php
|
||||||
|
|
||||||
|
.PHONY: help
|
||||||
|
help: ## Display this help.
|
||||||
|
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
|
||||||
|
|
||||||
|
##@ Development
|
||||||
|
|
||||||
|
.PHONY: fmt
|
||||||
|
fmt: ## Run go fmt against code.
|
||||||
|
go fmt ./...
|
||||||
|
|
||||||
|
.PHONY: vet
|
||||||
|
vet: ## Run go vet against code.
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
|
.PHONY: ut
|
||||||
|
ut: ## UT test
|
||||||
|
go test -v -cover -coverprofile=coverage.out ./...
|
||||||
|
go tool cover -func=coverage.out
|
||||||
|
|
||||||
|
##@ Build
|
||||||
|
|
||||||
|
.PHONY: backend
|
||||||
|
backend: fmt vet ## Build backend binary.
|
||||||
|
go build -o bin/manager main.go
|
||||||
|
|
||||||
|
.PHONY: backend-vendor
|
||||||
|
backend-vendor: vendor fmt vet ## Build backend binary with vendor.
|
||||||
|
go build -mod=vendor -o bin/manager main.go
|
||||||
|
|
||||||
|
.PHONY: frontend
|
||||||
|
frontend: ## Build backend binary.
|
||||||
|
cd web/ && yarn && yarn run build && cd -
|
||||||
|
|
||||||
|
.PHONY: vendor
|
||||||
|
vendor: ## Update vendor.
|
||||||
|
go mod vendor
|
||||||
|
|
||||||
|
.PHONY: run
|
||||||
|
run: fmt vet ## Run backend in local
|
||||||
|
go run ./main.go
|
||||||
|
|
||||||
|
.PHONY: docker-build
|
||||||
|
docker-build: ## Build docker image with the manager.
|
||||||
|
docker build -t ${REGISTRY}/${IMG}:${IMG_TAG} .
|
||||||
|
|
||||||
|
.PHONY: docker-push
|
||||||
|
docker-push: ## Push docker image with the manager.
|
||||||
|
docker push ${REGISTRY}/${IMG}:${IMG_TAG}
|
||||||
|
|
||||||
|
lint-install: ## Install golangci-lint
|
||||||
|
@# The following installs a specific version of golangci-lint, which is appropriate for a CI server to avoid different results from build to build
|
||||||
|
go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.40.1
|
||||||
|
|
||||||
|
lint: ## Run golangci-lint
|
||||||
|
@echo "---lint---"
|
||||||
|
golangci-lint run --modules-download-mode=vendor ./...
|
||||||
|
|
||||||
|
##@ Deployment
|
||||||
|
|
||||||
|
.PHONY: deploy
|
||||||
|
deploy: ## Deploy controller to the K8s cluster specified in ~/.kube/config.
|
||||||
|
helm upgrade --install ${APP} manifests/casdoor --create-namespace --set ingress.enabled=true \
|
||||||
|
--set "ingress.hosts[0].host=${HOST},ingress.hosts[0].paths[0].path=/,ingress.hosts[0].paths[0].pathType=ImplementationSpecific" \
|
||||||
|
--set image.tag=${IMG_TAG} --set image.repository=${REGISTRY} --set image.name=${IMG} --version ${IMG_TAG} -n ${NAMESPACE}
|
||||||
|
|
||||||
|
.PHONY: dry-run
|
||||||
|
dry-run: ## Dry run for helm install
|
||||||
|
helm upgrade --install ${APP} manifests/casdoor --set ingress.enabled=true \
|
||||||
|
--set "ingress.hosts[0].host=${HOST},ingress.hosts[0].paths[0].path=/,ingress.hosts[0].paths[0].pathType=ImplementationSpecific" \
|
||||||
|
--set image.tag=${IMG_TAG} --set image.repository=${REGISTRY} --set image.name=${IMG} --version ${IMG_TAG} -n ${NAMESPACE} --dry-run
|
||||||
|
|
||||||
|
.PHONY: undeploy
|
||||||
|
undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
|
||||||
|
helm delete ${APP} -n ${NAMESPACE}
|
23
README.md
23
README.md
@ -44,7 +44,7 @@
|
|||||||
|
|
||||||
## Online demo
|
## Online demo
|
||||||
|
|
||||||
Deployed site: https://door.casbin.com/
|
Deployed site: https://door.casdoor.com/
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
Run your own casdoor program in a few minutes.
|
Run your own casdoor program in a few minutes.
|
||||||
@ -82,6 +82,14 @@ Edit `conf/app.conf`, modify `dataSourceName` to correct database info, which fo
|
|||||||
username:password@tcp(database_ip:database_port)/
|
username:password@tcp(database_ip:database_port)/
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Then create an empty schema (database) named `casdoor` in your relational database. After the program runs for the first time, it will automatically create tables in this schema.
|
||||||
|
|
||||||
|
You can also edit `main.go`, modify `false` to `true`. It will automatically create the schema (database) named `casdoor` in this database.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
createDatabase := flag.Bool("createDatabase", false, "true if you need casdoor to create database")
|
||||||
|
```
|
||||||
|
|
||||||
#### Run
|
#### Run
|
||||||
|
|
||||||
Casdoor provides two run modes, the difference is binary size and user prompt.
|
Casdoor provides two run modes, the difference is binary size and user prompt.
|
||||||
@ -158,6 +166,19 @@ dataSourceName = root:123456@tcp(db:3306)/
|
|||||||
docker-compose up
|
docker-compose up
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### K8S
|
||||||
|
You could use helm to deploy casdoor in k8s. At first, you should modify the [configmap](./manifests/casdoor/templates/configmap.yaml) for your application.
|
||||||
|
And then run bellow command to deploy it.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
IMG_TAG=latest make deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
And undeploy it with:
|
||||||
|
```bash
|
||||||
|
make undeploy
|
||||||
|
```
|
||||||
|
|
||||||
That's it! Try to visit http://localhost:8000/. :small_airplane:
|
That's it! Try to visit http://localhost:8000/. :small_airplane:
|
||||||
|
|
||||||
## Detailed documentation
|
## Detailed documentation
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -54,7 +54,7 @@ m = (r.subOwner == p.subOwner || p.subOwner == "*") && \
|
|||||||
(r.urlPath == p.urlPath || p.urlPath == "*") && \
|
(r.urlPath == p.urlPath || p.urlPath == "*") && \
|
||||||
(r.objOwner == p.objOwner || p.objOwner == "*") && \
|
(r.objOwner == p.objOwner || p.objOwner == "*") && \
|
||||||
(r.objName == p.objName || p.objName == "*") || \
|
(r.objName == p.objName || p.objName == "*") || \
|
||||||
(r.urlPath == "/api/update-user" && r.subOwner == r.objOwner && r.subName == r.objName)
|
(r.subOwner == r.objOwner && r.subName == r.objName)
|
||||||
`
|
`
|
||||||
|
|
||||||
m, err := model.NewModelFromString(modelText)
|
m, err := model.NewModelFromString(modelText)
|
||||||
@ -80,16 +80,18 @@ p, *, *, POST, /api/login, *, *
|
|||||||
p, *, *, GET, /api/get-app-login, *, *
|
p, *, *, GET, /api/get-app-login, *, *
|
||||||
p, *, *, POST, /api/logout, *, *
|
p, *, *, POST, /api/logout, *, *
|
||||||
p, *, *, GET, /api/get-account, *, *
|
p, *, *, GET, /api/get-account, *, *
|
||||||
|
p, *, *, GET, /api/userinfo, *, *
|
||||||
p, *, *, POST, /api/login/oauth/access_token, *, *
|
p, *, *, POST, /api/login/oauth/access_token, *, *
|
||||||
p, *, *, POST, /api/login/oauth/refresh_token, *, *
|
p, *, *, POST, /api/login/oauth/refresh_token, *, *
|
||||||
|
p, *, *, GET, /api/login/oauth/logout, *, *
|
||||||
p, *, *, GET, /api/get-application, *, *
|
p, *, *, GET, /api/get-application, *, *
|
||||||
p, *, *, GET, /api/get-users, *, *
|
|
||||||
p, *, *, GET, /api/get-user, *, *
|
p, *, *, GET, /api/get-user, *, *
|
||||||
p, *, *, GET, /api/get-organizations, *, *
|
|
||||||
p, *, *, GET, /api/get-user-application, *, *
|
p, *, *, GET, /api/get-user-application, *, *
|
||||||
p, *, *, GET, /api/get-default-providers, *, *
|
|
||||||
p, *, *, GET, /api/get-resources, *, *
|
p, *, *, GET, /api/get-resources, *, *
|
||||||
p, *, *, POST, /api/upload-avatar, *, *
|
p, *, *, GET, /api/get-product, *, *
|
||||||
|
p, *, *, POST, /api/buy-product, *, *
|
||||||
|
p, *, *, GET, /api/get-payment, *, *
|
||||||
|
p, *, *, GET, /api/get-providers, *, *
|
||||||
p, *, *, POST, /api/unlink, *, *
|
p, *, *, POST, /api/unlink, *, *
|
||||||
p, *, *, POST, /api/set-password, *, *
|
p, *, *, POST, /api/set-password, *, *
|
||||||
p, *, *, POST, /api/send-verification-code, *, *
|
p, *, *, POST, /api/send-verification-code, *, *
|
||||||
@ -97,7 +99,7 @@ p, *, *, GET, /api/get-human-check, *, *
|
|||||||
p, *, *, POST, /api/reset-email-or-phone, *, *
|
p, *, *, POST, /api/reset-email-or-phone, *, *
|
||||||
p, *, *, POST, /api/upload-resource, *, *
|
p, *, *, POST, /api/upload-resource, *, *
|
||||||
p, *, *, GET, /.well-known/openid-configuration, *, *
|
p, *, *, GET, /.well-known/openid-configuration, *, *
|
||||||
p, *, *, *, /api/certs, *, *
|
p, *, *, *, /.well-known/jwks, *, *
|
||||||
p, *, *, GET, /api/get-saml-login, *, *
|
p, *, *, GET, /api/get-saml-login, *, *
|
||||||
p, *, *, POST, /api/acs, *, *
|
p, *, *, POST, /api/acs, *, *
|
||||||
`
|
`
|
||||||
|
@ -12,8 +12,8 @@ redisEndpoint =
|
|||||||
defaultStorageProvider =
|
defaultStorageProvider =
|
||||||
isCloudIntranet = false
|
isCloudIntranet = false
|
||||||
authState = "casdoor"
|
authState = "casdoor"
|
||||||
httpProxy = "127.0.0.1:10808"
|
sock5Proxy = "127.0.0.1:10808"
|
||||||
verificationCodeTimeout = 10
|
verificationCodeTimeout = 10
|
||||||
initScore = 2000
|
initScore = 2000
|
||||||
logPostOnly = true
|
logPostOnly = true
|
||||||
origin = "https://door.casbin.com"
|
origin =
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -18,6 +18,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/casdoor/casdoor/object"
|
"github.com/casdoor/casdoor/object"
|
||||||
"github.com/casdoor/casdoor/util"
|
"github.com/casdoor/casdoor/util"
|
||||||
@ -26,6 +27,8 @@ import (
|
|||||||
const (
|
const (
|
||||||
ResponseTypeLogin = "login"
|
ResponseTypeLogin = "login"
|
||||||
ResponseTypeCode = "code"
|
ResponseTypeCode = "code"
|
||||||
|
ResponseTypeToken = "token"
|
||||||
|
ResponseTypeIdToken = "id_token"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RequestForm struct {
|
type RequestForm struct {
|
||||||
@ -35,6 +38,8 @@ type RequestForm struct {
|
|||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
FirstName string `json:"firstName"`
|
||||||
|
LastName string `json:"lastName"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Phone string `json:"phone"`
|
Phone string `json:"phone"`
|
||||||
Affiliation string `json:"affiliation"`
|
Affiliation string `json:"affiliation"`
|
||||||
@ -102,7 +107,7 @@ func (c *ApiController) Signup() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", form.Organization))
|
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", form.Organization))
|
||||||
msg := object.CheckUserSignup(application, organization, form.Username, form.Password, form.Name, form.Email, form.Phone, form.Affiliation)
|
msg := object.CheckUserSignup(application, organization, form.Username, form.Password, form.Name, form.FirstName, form.LastName, form.Email, form.Phone, form.Affiliation)
|
||||||
if msg != "" {
|
if msg != "" {
|
||||||
c.ResponseError(msg)
|
c.ResponseError(msg)
|
||||||
return
|
return
|
||||||
@ -126,12 +131,15 @@ func (c *ApiController) Signup() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
userId := fmt.Sprintf("%s/%s", form.Organization, form.Username)
|
|
||||||
|
|
||||||
id := util.GenerateId()
|
id := util.GenerateId()
|
||||||
if application.GetSignupItemRule("ID") == "Incremental" {
|
if application.GetSignupItemRule("ID") == "Incremental" {
|
||||||
lastUser := object.GetLastUser(form.Organization)
|
lastUser := object.GetLastUser(form.Organization)
|
||||||
lastIdInt := util.ParseInt(lastUser.Id)
|
|
||||||
|
lastIdInt := -1
|
||||||
|
if lastUser != nil {
|
||||||
|
lastIdInt = util.ParseInt(lastUser.Id)
|
||||||
|
}
|
||||||
|
|
||||||
id = strconv.Itoa(lastIdInt + 1)
|
id = strconv.Itoa(lastIdInt + 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,6 +170,22 @@ func (c *ApiController) Signup() {
|
|||||||
IsDeleted: false,
|
IsDeleted: false,
|
||||||
SignupApplication: application.Name,
|
SignupApplication: application.Name,
|
||||||
Properties: map[string]string{},
|
Properties: map[string]string{},
|
||||||
|
Karma: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(organization.Tags) > 0 {
|
||||||
|
tokens := strings.Split(organization.Tags[0], "|")
|
||||||
|
if len(tokens) > 0 {
|
||||||
|
user.Tag = tokens[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if application.GetSignupItemRule("Display name") == "First, last" {
|
||||||
|
if form.FirstName != "" || form.LastName != "" {
|
||||||
|
user.DisplayName = fmt.Sprintf("%s %s", form.FirstName, form.LastName)
|
||||||
|
user.FirstName = form.FirstName
|
||||||
|
user.LastName = form.LastName
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
affected := object.AddUser(user)
|
affected := object.AddUser(user)
|
||||||
@ -180,6 +204,12 @@ func (c *ApiController) Signup() {
|
|||||||
object.DisableVerificationCode(form.Email)
|
object.DisableVerificationCode(form.Email)
|
||||||
object.DisableVerificationCode(checkPhone)
|
object.DisableVerificationCode(checkPhone)
|
||||||
|
|
||||||
|
record := object.NewRecord(c.Ctx)
|
||||||
|
record.Organization = application.Organization
|
||||||
|
record.User = user.Name
|
||||||
|
go object.AddRecord(record)
|
||||||
|
|
||||||
|
userId := fmt.Sprintf("%s/%s", user.Owner, user.Name)
|
||||||
util.LogInfo(c.Ctx, "API: [%s] is signed up as new user", userId)
|
util.LogInfo(c.Ctx, "API: [%s] is signed up as new user", userId)
|
||||||
|
|
||||||
c.ResponseOk(userId)
|
c.ResponseOk(userId)
|
||||||
@ -195,10 +225,15 @@ func (c *ApiController) Logout() {
|
|||||||
user := c.GetSessionUsername()
|
user := c.GetSessionUsername()
|
||||||
util.LogInfo(c.Ctx, "API: [%s] logged out", user)
|
util.LogInfo(c.Ctx, "API: [%s] logged out", user)
|
||||||
|
|
||||||
|
application := c.GetSessionApplication()
|
||||||
c.SetSessionUsername("")
|
c.SetSessionUsername("")
|
||||||
c.SetSessionData(nil)
|
c.SetSessionData(nil)
|
||||||
|
|
||||||
|
if application == nil || application.Name == "app-built-in" || application.HomepageUrl == "" {
|
||||||
c.ResponseOk(user)
|
c.ResponseOk(user)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.ResponseOk(user, application.HomepageUrl)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAccount
|
// GetAccount
|
||||||
@ -231,6 +266,27 @@ func (c *ApiController) GetAccount() {
|
|||||||
c.ServeJSON()
|
c.ServeJSON()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UserInfo
|
||||||
|
// @Title UserInfo
|
||||||
|
// @Tag Account API
|
||||||
|
// @Description return user information according to OIDC standards
|
||||||
|
// @Success 200 {object} object.Userinfo The Response object
|
||||||
|
// @router /userinfo [get]
|
||||||
|
func (c *ApiController) GetUserinfo() {
|
||||||
|
userId, ok := c.RequireSignedIn()
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scope, aud := c.GetSessionOidc()
|
||||||
|
host := c.Ctx.Request.Host
|
||||||
|
resp, err := object.GetUserInfo(userId, scope, aud, host)
|
||||||
|
if err != nil {
|
||||||
|
c.ResponseError(err.Error())
|
||||||
|
}
|
||||||
|
c.Data["json"] = resp
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
// GetHumanCheck ...
|
// GetHumanCheck ...
|
||||||
// @Tag Login API
|
// @Tag Login API
|
||||||
// @Title GetHumancheck
|
// @Title GetHumancheck
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -16,6 +16,7 @@ package controllers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/astaxie/beego/utils/pagination"
|
"github.com/astaxie/beego/utils/pagination"
|
||||||
"github.com/casdoor/casdoor/object"
|
"github.com/casdoor/casdoor/object"
|
||||||
@ -85,7 +86,7 @@ func (c *ApiController) GetUserApplication() {
|
|||||||
id := c.Input().Get("id")
|
id := c.Input().Get("id")
|
||||||
user := object.GetUser(id)
|
user := object.GetUser(id)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ResponseError("No such user.")
|
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", id))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -38,6 +38,14 @@ func codeToResponse(code *object.Code) *Response {
|
|||||||
return &Response{Status: "ok", Msg: "", Data: code.Code}
|
return &Response{Status: "ok", Msg: "", Data: code.Code}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func tokenToResponse(token *object.Token) *Response {
|
||||||
|
if token.AccessToken == "" {
|
||||||
|
return &Response{Status: "error", Msg: "fail to get accessToken", Data: token.AccessToken}
|
||||||
|
}
|
||||||
|
return &Response{Status: "ok", Msg: "", Data: token.AccessToken}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
// HandleLoggedIn ...
|
// HandleLoggedIn ...
|
||||||
func (c *ApiController) HandleLoggedIn(application *object.Application, user *object.User, form *RequestForm) (resp *Response) {
|
func (c *ApiController) HandleLoggedIn(application *object.Application, user *object.User, form *RequestForm) (resp *Response) {
|
||||||
userId := user.GetId()
|
userId := user.GetId()
|
||||||
@ -55,17 +63,26 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob
|
|||||||
challengeMethod := c.Input().Get("code_challenge_method")
|
challengeMethod := c.Input().Get("code_challenge_method")
|
||||||
codeChallenge := c.Input().Get("code_challenge")
|
codeChallenge := c.Input().Get("code_challenge")
|
||||||
|
|
||||||
if challengeMethod != "S256" && challengeMethod != "null" {
|
if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
|
||||||
c.ResponseError("Challenge method should be S256")
|
c.ResponseError("Challenge method should be S256")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
code := object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge)
|
code := object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, c.Ctx.Request.Host)
|
||||||
resp = codeToResponse(code)
|
resp = codeToResponse(code)
|
||||||
|
|
||||||
if application.EnableSigninSession || application.HasPromptPage() {
|
if application.EnableSigninSession || application.HasPromptPage() {
|
||||||
// The prompt page needs the user to be signed in
|
// The prompt page needs the user to be signed in
|
||||||
c.SetSessionUsername(userId)
|
c.SetSessionUsername(userId)
|
||||||
}
|
}
|
||||||
|
} else if form.Type == ResponseTypeToken || form.Type == ResponseTypeIdToken { //implicit flow
|
||||||
|
if !object.IsGrantTypeValid(form.Type, application.GrantTypes) {
|
||||||
|
resp = &Response{Status: "error", Msg: fmt.Sprintf("error: grant_type: %s is not supported in this application", form.Type), Data: ""}
|
||||||
|
} else {
|
||||||
|
scope := c.Input().Get("scope")
|
||||||
|
token, _ := object.GetTokenByUser(application, user, scope, c.Ctx.Request.Host)
|
||||||
|
resp = tokenToResponse(token)
|
||||||
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
resp = &Response{Status: "error", Msg: fmt.Sprintf("Unknown response type: %s", form.Type)}
|
resp = &Response{Status: "error", Msg: fmt.Sprintf("Unknown response type: %s", form.Type)}
|
||||||
}
|
}
|
||||||
@ -101,6 +118,7 @@ func (c *ApiController) GetApplicationLogin() {
|
|||||||
state := c.Input().Get("state")
|
state := c.Input().Get("state")
|
||||||
|
|
||||||
msg, application := object.CheckOAuthLogin(clientId, responseType, redirectUri, scope, state)
|
msg, application := object.CheckOAuthLogin(clientId, responseType, redirectUri, scope, state)
|
||||||
|
application = object.GetMaskedApplication(application, "")
|
||||||
if msg != "" {
|
if msg != "" {
|
||||||
c.ResponseError(msg, application)
|
c.ResponseError(msg, application)
|
||||||
} else {
|
} else {
|
||||||
@ -109,7 +127,7 @@ func (c *ApiController) GetApplicationLogin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func setHttpClient(idProvider idp.IdProvider, providerType string) {
|
func setHttpClient(idProvider idp.IdProvider, providerType string) {
|
||||||
if providerType == "GitHub" || providerType == "Google" || providerType == "Facebook" || providerType == "LinkedIn" {
|
if providerType == "GitHub" || providerType == "Google" || providerType == "Facebook" || providerType == "LinkedIn" || providerType == "Steam" {
|
||||||
idProvider.SetHttpClient(proxy.ProxyHttpClient)
|
idProvider.SetHttpClient(proxy.ProxyHttpClient)
|
||||||
} else {
|
} else {
|
||||||
idProvider.SetHttpClient(proxy.DefaultHttpClient)
|
idProvider.SetHttpClient(proxy.DefaultHttpClient)
|
||||||
@ -149,9 +167,16 @@ func (c *ApiController) Login() {
|
|||||||
var verificationCodeType string
|
var verificationCodeType string
|
||||||
var checkResult string
|
var checkResult string
|
||||||
|
|
||||||
|
if form.Name != "" {
|
||||||
|
user = object.GetUserByFields(form.Organization, form.Name)
|
||||||
|
}
|
||||||
|
|
||||||
// check result through Email or Phone
|
// check result through Email or Phone
|
||||||
if strings.Contains(form.Username, "@") {
|
if strings.Contains(form.Username, "@") {
|
||||||
verificationCodeType = "email"
|
verificationCodeType = "email"
|
||||||
|
if user != nil && util.GetMaskedEmail(user.Email) == form.Username {
|
||||||
|
form.Username = user.Email
|
||||||
|
}
|
||||||
checkResult = object.CheckVerificationCode(form.Username, form.Code)
|
checkResult = object.CheckVerificationCode(form.Username, form.Code)
|
||||||
} else {
|
} else {
|
||||||
verificationCodeType = "phone"
|
verificationCodeType = "phone"
|
||||||
@ -160,6 +185,9 @@ func (c *ApiController) Login() {
|
|||||||
c.ResponseError(responseText)
|
c.ResponseError(responseText)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if user != nil && util.GetMaskedPhone(user.Phone) == form.Username {
|
||||||
|
form.Username = user.Phone
|
||||||
|
}
|
||||||
checkPhone := fmt.Sprintf("+%s%s", form.PhonePrefix, form.Username)
|
checkPhone := fmt.Sprintf("+%s%s", form.PhonePrefix, form.Username)
|
||||||
checkResult = object.CheckVerificationCode(checkPhone, form.Code)
|
checkResult = object.CheckVerificationCode(checkPhone, form.Code)
|
||||||
}
|
}
|
||||||
@ -174,7 +202,7 @@ func (c *ApiController) Login() {
|
|||||||
|
|
||||||
user = object.GetUserByFields(form.Organization, form.Username)
|
user = object.GetUserByFields(form.Organization, form.Username)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ResponseError("No such user.")
|
c.ResponseError(fmt.Sprintf("The user: %s/%s doesn't exist", form.Organization, form.Username))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -186,6 +214,11 @@ func (c *ApiController) Login() {
|
|||||||
resp = &Response{Status: "error", Msg: msg}
|
resp = &Response{Status: "error", Msg: msg}
|
||||||
} else {
|
} else {
|
||||||
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
||||||
|
if application == nil {
|
||||||
|
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
resp = c.HandleLoggedIn(application, user, &form)
|
resp = c.HandleLoggedIn(application, user, &form)
|
||||||
|
|
||||||
record := object.NewRecord(c.Ctx)
|
record := object.NewRecord(c.Ctx)
|
||||||
@ -195,6 +228,11 @@ func (c *ApiController) Login() {
|
|||||||
}
|
}
|
||||||
} else if form.Provider != "" {
|
} else if form.Provider != "" {
|
||||||
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
||||||
|
if application == nil {
|
||||||
|
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", application.Organization))
|
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", application.Organization))
|
||||||
provider := object.GetProvider(fmt.Sprintf("admin/%s", form.Provider))
|
provider := object.GetProvider(fmt.Sprintf("admin/%s", form.Provider))
|
||||||
providerItem := application.GetProviderItem(provider.Name)
|
providerItem := application.GetProviderItem(provider.Name)
|
||||||
@ -221,7 +259,7 @@ func (c *ApiController) Login() {
|
|||||||
clientSecret = provider.ClientSecret2
|
clientSecret = provider.ClientSecret2
|
||||||
}
|
}
|
||||||
|
|
||||||
idProvider := idp.GetIdProvider(provider.Type, clientId, clientSecret, form.RedirectUri)
|
idProvider := idp.GetIdProvider(provider.Type, provider.SubType, clientId, clientSecret, provider.AppId, form.RedirectUri, provider.Domain)
|
||||||
if idProvider == nil {
|
if idProvider == nil {
|
||||||
c.ResponseError(fmt.Sprintf("The provider type: %s is not supported", provider.Type))
|
c.ResponseError(fmt.Sprintf("The provider type: %s is not supported", provider.Type))
|
||||||
return
|
return
|
||||||
@ -365,6 +403,11 @@ func (c *ApiController) Login() {
|
|||||||
if c.GetSessionUsername() != "" {
|
if c.GetSessionUsername() != "" {
|
||||||
// user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in
|
// user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in
|
||||||
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
|
||||||
|
if application == nil {
|
||||||
|
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
user := c.getCurrentUser()
|
user := c.getCurrentUser()
|
||||||
resp = c.HandleLoggedIn(application, user, &form)
|
resp = c.HandleLoggedIn(application, user, &form)
|
||||||
} else {
|
} else {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -72,6 +72,37 @@ func (c *ApiController) GetSessionUsername() string {
|
|||||||
return user.(string)
|
return user.(string)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ApiController) GetSessionApplication() *object.Application {
|
||||||
|
clientId := c.GetSession("aud")
|
||||||
|
if clientId == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
application := object.GetApplicationByClientId(clientId.(string))
|
||||||
|
return application
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ApiController) GetSessionOidc() (string, string) {
|
||||||
|
sessionData := c.GetSessionData()
|
||||||
|
if sessionData != nil &&
|
||||||
|
sessionData.ExpireTime != 0 &&
|
||||||
|
sessionData.ExpireTime < time.Now().Unix() {
|
||||||
|
c.SetSessionUsername("")
|
||||||
|
c.SetSessionData(nil)
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
scopeValue := c.GetSession("scope")
|
||||||
|
audValue := c.GetSession("aud")
|
||||||
|
var scope, aud string
|
||||||
|
var ok bool
|
||||||
|
if scope, ok = scopeValue.(string); !ok {
|
||||||
|
scope = ""
|
||||||
|
}
|
||||||
|
if aud, ok = audValue.(string); !ok {
|
||||||
|
aud = ""
|
||||||
|
}
|
||||||
|
return scope, aud
|
||||||
|
}
|
||||||
|
|
||||||
// SetSessionUsername ...
|
// SetSessionUsername ...
|
||||||
func (c *ApiController) SetSessionUsername(user string) {
|
func (c *ApiController) SetSessionUsername(user string) {
|
||||||
c.SetSession("username", user)
|
c.SetSession("username", user)
|
||||||
@ -110,3 +141,11 @@ func wrapActionResponse(affected bool) *Response {
|
|||||||
return &Response{Status: "ok", Msg: "", Data: "Unaffected"}
|
return &Response{Status: "ok", Msg: "", Data: "Unaffected"}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func wrapErrorResponse(err error) *Response {
|
||||||
|
if err == nil {
|
||||||
|
return &Response{Status: "ok", Msg: ""}
|
||||||
|
} else {
|
||||||
|
return &Response{Status: "error", Msg: err.Error()}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -170,6 +170,7 @@ func (c *ApiController) UpdateLdap() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prevLdap := object.GetLdap(ldap.Id)
|
||||||
affected := object.UpdateLdap(&ldap)
|
affected := object.UpdateLdap(&ldap)
|
||||||
resp := wrapActionResponse(affected)
|
resp := wrapActionResponse(affected)
|
||||||
if affected {
|
if affected {
|
||||||
@ -177,6 +178,8 @@ func (c *ApiController) UpdateLdap() {
|
|||||||
}
|
}
|
||||||
if ldap.AutoSync != 0 {
|
if ldap.AutoSync != 0 {
|
||||||
object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
|
object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
|
||||||
|
} else if ldap.AutoSync == 0 && prevLdap.AutoSync != 0{
|
||||||
|
object.GetLdapAutoSynchronizer().StopAutoSync(ldap.Id)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Data["json"] = resp
|
c.Data["json"] = resp
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -20,14 +20,15 @@ import "github.com/casdoor/casdoor/object"
|
|||||||
// @Tag OIDC API
|
// @Tag OIDC API
|
||||||
// @router /.well-known/openid-configuration [get]
|
// @router /.well-known/openid-configuration [get]
|
||||||
func (c *RootController) GetOidcDiscovery() {
|
func (c *RootController) GetOidcDiscovery() {
|
||||||
c.Data["json"] = object.GetOidcDiscovery()
|
host := c.Ctx.Request.Host
|
||||||
|
c.Data["json"] = object.GetOidcDiscovery(host)
|
||||||
c.ServeJSON()
|
c.ServeJSON()
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Title GetOidcCert
|
// @Title GetJwks
|
||||||
// @Tag OIDC API
|
// @Tag OIDC API
|
||||||
// @router /api/certs [get]
|
// @router /.well-known/jwks [get]
|
||||||
func (c *RootController) GetOidcCert() {
|
func (c *RootController) GetJwks() {
|
||||||
jwks, err := object.GetJsonWebKeySet()
|
jwks, err := object.GetJsonWebKeySet()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.ResponseError(err.Error())
|
c.ResponseError(err.Error())
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
160
controllers/payment.go
Normal file
160
controllers/payment.go
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
// Copyright 2022 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"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/astaxie/beego/utils/pagination"
|
||||||
|
"github.com/casdoor/casdoor/object"
|
||||||
|
"github.com/casdoor/casdoor/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetPayments
|
||||||
|
// @Title GetPayments
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description get payments
|
||||||
|
// @Param owner query string true "The owner of payments"
|
||||||
|
// @Success 200 {array} object.Payment The Response object
|
||||||
|
// @router /get-payments [get]
|
||||||
|
func (c *ApiController) GetPayments() {
|
||||||
|
owner := c.Input().Get("owner")
|
||||||
|
limit := c.Input().Get("pageSize")
|
||||||
|
page := c.Input().Get("p")
|
||||||
|
field := c.Input().Get("field")
|
||||||
|
value := c.Input().Get("value")
|
||||||
|
sortField := c.Input().Get("sortField")
|
||||||
|
sortOrder := c.Input().Get("sortOrder")
|
||||||
|
if limit == "" || page == "" {
|
||||||
|
c.Data["json"] = object.GetPayments(owner)
|
||||||
|
c.ServeJSON()
|
||||||
|
} else {
|
||||||
|
limit := util.ParseInt(limit)
|
||||||
|
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetPaymentCount(owner, field, value)))
|
||||||
|
payments := object.GetPaginationPayments(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
|
||||||
|
c.ResponseOk(payments, paginator.Nums())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUserPayments
|
||||||
|
// @Title GetUserPayments
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description get payments for a user
|
||||||
|
// @Param owner query string true "The owner of payments"
|
||||||
|
// @Param organization query string true "The organization of the user"
|
||||||
|
// @Param user query string true "The username of the user"
|
||||||
|
// @Success 200 {array} object.Payment The Response object
|
||||||
|
// @router /get-user-payments [get]
|
||||||
|
func (c *ApiController) GetUserPayments() {
|
||||||
|
owner := c.Input().Get("owner")
|
||||||
|
organization := c.Input().Get("organization")
|
||||||
|
user := c.Input().Get("user")
|
||||||
|
|
||||||
|
payments := object.GetUserPayments(owner, organization, user)
|
||||||
|
c.ResponseOk(payments)
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title GetPayment
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description get payment
|
||||||
|
// @Param id query string true "The id of the payment"
|
||||||
|
// @Success 200 {object} object.Payment The Response object
|
||||||
|
// @router /get-payment [get]
|
||||||
|
func (c *ApiController) GetPayment() {
|
||||||
|
id := c.Input().Get("id")
|
||||||
|
|
||||||
|
c.Data["json"] = object.GetPayment(id)
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title UpdatePayment
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description update payment
|
||||||
|
// @Param id query string true "The id of the payment"
|
||||||
|
// @Param body body object.Payment true "The details of the payment"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /update-payment [post]
|
||||||
|
func (c *ApiController) UpdatePayment() {
|
||||||
|
id := c.Input().Get("id")
|
||||||
|
|
||||||
|
var payment object.Payment
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.UpdatePayment(id, &payment))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title AddPayment
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description add payment
|
||||||
|
// @Param body body object.Payment true "The details of the payment"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /add-payment [post]
|
||||||
|
func (c *ApiController) AddPayment() {
|
||||||
|
var payment object.Payment
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.AddPayment(&payment))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title DeletePayment
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description delete payment
|
||||||
|
// @Param body body object.Payment true "The details of the payment"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /delete-payment [post]
|
||||||
|
func (c *ApiController) DeletePayment() {
|
||||||
|
var payment object.Payment
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.DeletePayment(&payment))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title NotifyPayment
|
||||||
|
// @Tag Payment API
|
||||||
|
// @Description notify payment
|
||||||
|
// @Param body body object.Payment true "The details of the payment"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /notify-payment [post]
|
||||||
|
func (c *ApiController) NotifyPayment() {
|
||||||
|
owner := c.Ctx.Input.Param(":owner")
|
||||||
|
providerName := c.Ctx.Input.Param(":provider")
|
||||||
|
productName := c.Ctx.Input.Param(":product")
|
||||||
|
paymentName := c.Ctx.Input.Param(":payment")
|
||||||
|
|
||||||
|
body := c.Ctx.Input.RequestBody
|
||||||
|
|
||||||
|
ok := object.NotifyPayment(c.Ctx.Request, body, owner, providerName, productName, paymentName)
|
||||||
|
if ok {
|
||||||
|
_, err := c.Ctx.ResponseWriter.Write([]byte("success"))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic(fmt.Errorf("NotifyPayment() failed: %v", ok))
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
150
controllers/product.go
Normal file
150
controllers/product.go
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
// Copyright 2022 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"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/astaxie/beego/utils/pagination"
|
||||||
|
"github.com/casdoor/casdoor/object"
|
||||||
|
"github.com/casdoor/casdoor/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetProducts
|
||||||
|
// @Title GetProducts
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description get products
|
||||||
|
// @Param owner query string true "The owner of products"
|
||||||
|
// @Success 200 {array} object.Product The Response object
|
||||||
|
// @router /get-products [get]
|
||||||
|
func (c *ApiController) GetProducts() {
|
||||||
|
owner := c.Input().Get("owner")
|
||||||
|
limit := c.Input().Get("pageSize")
|
||||||
|
page := c.Input().Get("p")
|
||||||
|
field := c.Input().Get("field")
|
||||||
|
value := c.Input().Get("value")
|
||||||
|
sortField := c.Input().Get("sortField")
|
||||||
|
sortOrder := c.Input().Get("sortOrder")
|
||||||
|
if limit == "" || page == "" {
|
||||||
|
c.Data["json"] = object.GetProducts(owner)
|
||||||
|
c.ServeJSON()
|
||||||
|
} else {
|
||||||
|
limit := util.ParseInt(limit)
|
||||||
|
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetProductCount(owner, field, value)))
|
||||||
|
products := object.GetPaginationProducts(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
|
||||||
|
c.ResponseOk(products, paginator.Nums())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title GetProduct
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description get product
|
||||||
|
// @Param id query string true "The id of the product"
|
||||||
|
// @Success 200 {object} object.Product The Response object
|
||||||
|
// @router /get-product [get]
|
||||||
|
func (c *ApiController) GetProduct() {
|
||||||
|
id := c.Input().Get("id")
|
||||||
|
|
||||||
|
c.Data["json"] = object.GetProduct(id)
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title UpdateProduct
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description update product
|
||||||
|
// @Param id query string true "The id of the product"
|
||||||
|
// @Param body body object.Product true "The details of the product"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /update-product [post]
|
||||||
|
func (c *ApiController) UpdateProduct() {
|
||||||
|
id := c.Input().Get("id")
|
||||||
|
|
||||||
|
var product object.Product
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.UpdateProduct(id, &product))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title AddProduct
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description add product
|
||||||
|
// @Param body body object.Product true "The details of the product"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /add-product [post]
|
||||||
|
func (c *ApiController) AddProduct() {
|
||||||
|
var product object.Product
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.AddProduct(&product))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title DeleteProduct
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description delete product
|
||||||
|
// @Param body body object.Product true "The details of the product"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /delete-product [post]
|
||||||
|
func (c *ApiController) DeleteProduct() {
|
||||||
|
var product object.Product
|
||||||
|
err := json.Unmarshal(c.Ctx.Input.RequestBody, &product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = wrapActionResponse(object.DeleteProduct(&product))
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Title BuyProduct
|
||||||
|
// @Tag Product API
|
||||||
|
// @Description buy product
|
||||||
|
// @Param id query string true "The id of the product"
|
||||||
|
// @Param providerName query string true "The name of the provider"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /buy-product [post]
|
||||||
|
func (c *ApiController) BuyProduct() {
|
||||||
|
id := c.Input().Get("id")
|
||||||
|
providerName := c.Input().Get("providerName")
|
||||||
|
host := c.Ctx.Request.Host
|
||||||
|
|
||||||
|
userId := c.GetSessionUsername()
|
||||||
|
if userId == "" {
|
||||||
|
c.ResponseError("Please login first")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user := object.GetUser(userId)
|
||||||
|
if user == nil {
|
||||||
|
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", userId))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payUrl, err := object.BuyProduct(id, providerName, user, host)
|
||||||
|
if err != nil {
|
||||||
|
c.ResponseError(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.ResponseOk(payUrl)
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -16,6 +16,7 @@ package controllers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/astaxie/beego/utils/pagination"
|
"github.com/astaxie/beego/utils/pagination"
|
||||||
"github.com/casdoor/casdoor/object"
|
"github.com/casdoor/casdoor/object"
|
||||||
@ -145,12 +146,13 @@ func (c *ApiController) GetOAuthCode() {
|
|||||||
challengeMethod := c.Input().Get("code_challenge_method")
|
challengeMethod := c.Input().Get("code_challenge_method")
|
||||||
codeChallenge := c.Input().Get("code_challenge")
|
codeChallenge := c.Input().Get("code_challenge")
|
||||||
|
|
||||||
if challengeMethod != "S256" && challengeMethod != "null" {
|
if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
|
||||||
c.ResponseError("Challenge method should be S256")
|
c.ResponseError("Challenge method should be S256")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
host := c.Ctx.Request.Host
|
||||||
|
|
||||||
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge)
|
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, host)
|
||||||
c.ServeJSON()
|
c.ServeJSON()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,23 +172,28 @@ func (c *ApiController) GetOAuthToken() {
|
|||||||
clientSecret := c.Input().Get("client_secret")
|
clientSecret := c.Input().Get("client_secret")
|
||||||
code := c.Input().Get("code")
|
code := c.Input().Get("code")
|
||||||
verifier := c.Input().Get("code_verifier")
|
verifier := c.Input().Get("code_verifier")
|
||||||
|
scope := c.Input().Get("scope")
|
||||||
|
username := c.Input().Get("username")
|
||||||
|
password := c.Input().Get("password")
|
||||||
|
|
||||||
if clientId == "" && clientSecret == "" {
|
if clientId == "" && clientSecret == "" {
|
||||||
clientId, clientSecret, _ = c.Ctx.Request.BasicAuth()
|
clientId, clientSecret, _ = c.Ctx.Request.BasicAuth()
|
||||||
}
|
}
|
||||||
|
host := c.Ctx.Request.Host
|
||||||
|
|
||||||
c.Data["json"] = object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier)
|
c.Data["json"] = object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, username, password, host)
|
||||||
c.ServeJSON()
|
c.ServeJSON()
|
||||||
}
|
}
|
||||||
|
|
||||||
// RefreshToken
|
// RefreshToken
|
||||||
// @Title RefreshToken
|
// @Title RefreshToken
|
||||||
|
// @Tag Token API
|
||||||
// @Description refresh OAuth access token
|
// @Description refresh OAuth access token
|
||||||
// @Param grant_type query string true "OAuth grant type"
|
// @Param grant_type query string true "OAuth grant type"
|
||||||
// @Param refresh_token query string true "OAuth refresh token"
|
// @Param refresh_token query string true "OAuth refresh token"
|
||||||
// @Param scope query string true "OAuth scope"
|
// @Param scope query string true "OAuth scope"
|
||||||
// @Param client_id query string true "OAuth client id"
|
// @Param client_id query string true "OAuth client id"
|
||||||
// @Param client_secret query string true "OAuth client secret"
|
// @Param client_secret query string false "OAuth client secret"
|
||||||
// @Success 200 {object} object.TokenWrapper The Response object
|
// @Success 200 {object} object.TokenWrapper The Response object
|
||||||
// @router /login/oauth/refresh_token [post]
|
// @router /login/oauth/refresh_token [post]
|
||||||
func (c *ApiController) RefreshToken() {
|
func (c *ApiController) RefreshToken() {
|
||||||
@ -195,7 +202,92 @@ func (c *ApiController) RefreshToken() {
|
|||||||
scope := c.Input().Get("scope")
|
scope := c.Input().Get("scope")
|
||||||
clientId := c.Input().Get("client_id")
|
clientId := c.Input().Get("client_id")
|
||||||
clientSecret := c.Input().Get("client_secret")
|
clientSecret := c.Input().Get("client_secret")
|
||||||
|
host := c.Ctx.Request.Host
|
||||||
|
|
||||||
c.Data["json"] = object.RefreshToken(grantType, refreshToken, scope, clientId, clientSecret)
|
c.Data["json"] = object.RefreshToken(grantType, refreshToken, scope, clientId, clientSecret, host)
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TokenLogout
|
||||||
|
// @Title TokenLogout
|
||||||
|
// @Tag Token API
|
||||||
|
// @Description delete token by AccessToken
|
||||||
|
// @Param id_token_hint query string true "id_token_hint"
|
||||||
|
// @Param post_logout_redirect_uri query string false "post_logout_redirect_uri"
|
||||||
|
// @Param state query string true "state"
|
||||||
|
// @Success 200 {object} controllers.Response The Response object
|
||||||
|
// @router /login/oauth/logout [get]
|
||||||
|
func (c *ApiController) TokenLogout() {
|
||||||
|
token := c.Input().Get("id_token_hint")
|
||||||
|
flag, application := object.DeleteTokenByAceessToken(token)
|
||||||
|
redirectUri := c.Input().Get("post_logout_redirect_uri")
|
||||||
|
state := c.Input().Get("state")
|
||||||
|
if application != nil && object.CheckRedirectUriValid(application, redirectUri) {
|
||||||
|
c.Ctx.Redirect(http.StatusFound, redirectUri+"?state="+state)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Data["json"] = wrapActionResponse(flag)
|
||||||
|
c.ServeJSON()
|
||||||
|
}
|
||||||
|
|
||||||
|
// IntrospectToken
|
||||||
|
// @Title IntrospectToken
|
||||||
|
// @Description The introspection endpoint is an OAuth 2.0 endpoint that takes a
|
||||||
|
// parameter representing an OAuth 2.0 token and returns a JSON document
|
||||||
|
// representing the meta information surrounding the
|
||||||
|
// token, including whether this token is currently active.
|
||||||
|
// This endpoint only support Basic Authorization.
|
||||||
|
// @Param token formData string true "access_token's value or refresh_token's value"
|
||||||
|
// @Param token_type_hint formData string true "the token type access_token or refresh_token"
|
||||||
|
// @Success 200 {object} object.IntrospectionResponse The Response object
|
||||||
|
// @router /login/oauth/introspect [post]
|
||||||
|
func (c *ApiController) IntrospectToken() {
|
||||||
|
tokenValue := c.Input().Get("token")
|
||||||
|
clientId, clientSecret, ok := c.Ctx.Request.BasicAuth()
|
||||||
|
if !ok {
|
||||||
|
util.LogWarning(c.Ctx, "Basic Authorization parses failed")
|
||||||
|
c.Data["json"] = Response{Status: "error", Msg: "Unauthorized operation"}
|
||||||
|
c.ServeJSON()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
application := object.GetApplicationByClientId(clientId)
|
||||||
|
if application == nil || application.ClientSecret != clientSecret {
|
||||||
|
util.LogWarning(c.Ctx, "Basic Authorization failed")
|
||||||
|
c.Data["json"] = Response{Status: "error", Msg: "Unauthorized operation"}
|
||||||
|
c.ServeJSON()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := object.GetTokenByTokenAndApplication(tokenValue, application.Name)
|
||||||
|
if token == nil {
|
||||||
|
util.LogWarning(c.Ctx, "application: %s can not find token", application.Name)
|
||||||
|
c.Data["json"] = &object.IntrospectionResponse{Active: false}
|
||||||
|
c.ServeJSON()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
jwtToken, err := object.ParseJwtTokenByApplication(tokenValue, application)
|
||||||
|
if err != nil || jwtToken.Valid() != nil {
|
||||||
|
// and token revoked case. but we not implement
|
||||||
|
// TODO: 2022-03-03 add token revoked check, when we implemented the Token Revocation(rfc7009) Specs.
|
||||||
|
// refs: https://tools.ietf.org/html/rfc7009
|
||||||
|
util.LogWarning(c.Ctx, "token invalid")
|
||||||
|
c.Data["json"] = &object.IntrospectionResponse{Active: false}
|
||||||
|
c.ServeJSON()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Data["json"] = &object.IntrospectionResponse{
|
||||||
|
Active: true,
|
||||||
|
Scope: jwtToken.Scope,
|
||||||
|
ClientId: clientId,
|
||||||
|
Username: token.User,
|
||||||
|
TokenType: token.TokenType,
|
||||||
|
Exp: jwtToken.ExpiresAt.Unix(),
|
||||||
|
Iat: jwtToken.IssuedAt.Unix(),
|
||||||
|
Nbf: jwtToken.NotBefore.Unix(),
|
||||||
|
Sub: jwtToken.Subject,
|
||||||
|
Aud: jwtToken.Audience,
|
||||||
|
Iss: jwtToken.Issuer,
|
||||||
|
Jti: jwtToken.Id,
|
||||||
|
}
|
||||||
c.ServeJSON()
|
c.ServeJSON()
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -44,6 +44,7 @@ func (c *ApiController) GetGlobalUsers() {
|
|||||||
limit := util.ParseInt(limit)
|
limit := util.ParseInt(limit)
|
||||||
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetGlobalUserCount(field, value)))
|
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetGlobalUserCount(field, value)))
|
||||||
users := object.GetPaginationGlobalUsers(paginator.Offset(), limit, field, value, sortField, sortOrder)
|
users := object.GetPaginationGlobalUsers(paginator.Offset(), limit, field, value, sortField, sortOrder)
|
||||||
|
users = object.GetMaskedUsers(users)
|
||||||
c.ResponseOk(users, paginator.Nums())
|
c.ResponseOk(users, paginator.Nums())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -70,6 +71,7 @@ func (c *ApiController) GetUsers() {
|
|||||||
limit := util.ParseInt(limit)
|
limit := util.ParseInt(limit)
|
||||||
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetUserCount(owner, field, value)))
|
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetUserCount(owner, field, value)))
|
||||||
users := object.GetPaginationUsers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
|
users := object.GetPaginationUsers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
|
||||||
|
users = object.GetMaskedUsers(users)
|
||||||
c.ResponseOk(users, paginator.Nums())
|
c.ResponseOk(users, paginator.Nums())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -188,19 +190,23 @@ func (c *ApiController) GetEmailAndPhone() {
|
|||||||
|
|
||||||
user := object.GetUserByFields(form.Organization, form.Username)
|
user := object.GetUserByFields(form.Organization, form.Username)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ResponseError("No such user.")
|
c.ResponseError(fmt.Sprintf("The user: %s/%s doesn't exist", form.Organization, form.Username))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
respUser := object.User{Email: user.Email, Phone: user.Phone, Name: user.Name}
|
respUser := object.User{Name: user.Name}
|
||||||
var contentType string
|
var contentType string
|
||||||
switch form.Username {
|
switch form.Username {
|
||||||
case user.Email:
|
case user.Email:
|
||||||
contentType = "email"
|
contentType = "email"
|
||||||
|
respUser.Email = user.Email
|
||||||
case user.Phone:
|
case user.Phone:
|
||||||
contentType = "phone"
|
contentType = "phone"
|
||||||
|
respUser.Phone = user.Phone
|
||||||
case user.Name:
|
case user.Name:
|
||||||
contentType = "username"
|
contentType = "username"
|
||||||
|
respUser.Email = util.GetMaskedEmail(user.Email)
|
||||||
|
respUser.Phone = util.GetMaskedPhone(user.Phone)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.ResponseOk(respUser, contentType)
|
c.ResponseOk(respUser, contentType)
|
||||||
@ -224,7 +230,7 @@ func (c *ApiController) SetPassword() {
|
|||||||
|
|
||||||
requestUserId := c.GetSessionUsername()
|
requestUserId := c.GetSessionUsername()
|
||||||
if requestUserId == "" {
|
if requestUserId == "" {
|
||||||
c.ResponseError("Please login first.")
|
c.ResponseError("Please login first")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -68,15 +68,22 @@ func (c *ApiController) SendVerificationCode() {
|
|||||||
organization := object.GetOrganization(orgId)
|
organization := object.GetOrganization(orgId)
|
||||||
application := object.GetApplicationByOrganizationName(organization.Name)
|
application := object.GetApplicationByOrganizationName(organization.Name)
|
||||||
|
|
||||||
if checkUser == "true" && user == nil &&
|
if checkUser == "true" && user == nil && object.GetUserByFields(organization.Name, dest) == nil {
|
||||||
object.GetUserByFields(organization.Name, dest) == nil {
|
c.ResponseError("Please login first")
|
||||||
c.ResponseError("No such user.")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sendResp := errors.New("Invalid dest type.")
|
sendResp := errors.New("Invalid dest type")
|
||||||
|
|
||||||
|
if user == nil && checkUser != "" && checkUser != "true" {
|
||||||
|
_, name := util.GetOwnerAndNameFromId(orgId)
|
||||||
|
user = object.GetUser(fmt.Sprintf("%s/%s", name, checkUser))
|
||||||
|
}
|
||||||
switch destType {
|
switch destType {
|
||||||
case "email":
|
case "email":
|
||||||
|
if user != nil && util.GetMaskedEmail(user.Email) == dest {
|
||||||
|
dest = user.Email
|
||||||
|
}
|
||||||
if !util.IsEmailValid(dest) {
|
if !util.IsEmailValid(dest) {
|
||||||
c.ResponseError("Invalid Email address")
|
c.ResponseError("Invalid Email address")
|
||||||
return
|
return
|
||||||
@ -85,6 +92,9 @@ func (c *ApiController) SendVerificationCode() {
|
|||||||
provider := application.GetEmailProvider()
|
provider := application.GetEmailProvider()
|
||||||
sendResp = object.SendVerificationCodeToEmail(organization, user, provider, remoteAddr, dest)
|
sendResp = object.SendVerificationCodeToEmail(organization, user, provider, remoteAddr, dest)
|
||||||
case "phone":
|
case "phone":
|
||||||
|
if user != nil && util.GetMaskedPhone(user.Phone) == dest {
|
||||||
|
dest = user.Phone
|
||||||
|
}
|
||||||
if !util.IsPhoneCnValid(dest) {
|
if !util.IsPhoneCnValid(dest) {
|
||||||
c.ResponseError("Invalid phone number")
|
c.ResponseError("Invalid phone number")
|
||||||
return
|
return
|
||||||
@ -121,7 +131,7 @@ func (c *ApiController) ResetEmailOrPhone() {
|
|||||||
|
|
||||||
user := object.GetUser(userId)
|
user := object.GetUser(userId)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ResponseError("No such user.")
|
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", userId))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
version: '3.1'
|
version: '3.1'
|
||||||
services:
|
services:
|
||||||
restart: always
|
|
||||||
casdoor:
|
casdoor:
|
||||||
|
restart: always
|
||||||
build:
|
build:
|
||||||
context: ./
|
context: ./
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
@ -16,6 +16,7 @@ services:
|
|||||||
db:
|
db:
|
||||||
restart: always
|
restart: always
|
||||||
image: mysql:8.0.25
|
image: mysql:8.0.25
|
||||||
|
platform: linux/amd64
|
||||||
ports:
|
ports:
|
||||||
- "3306:3306"
|
- "3306:3306"
|
||||||
environment:
|
environment:
|
||||||
|
8
go.mod
8
go.mod
@ -9,14 +9,16 @@ require (
|
|||||||
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
|
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
|
||||||
github.com/casbin/casbin/v2 v2.30.1
|
github.com/casbin/casbin/v2 v2.30.1
|
||||||
github.com/casbin/xorm-adapter/v2 v2.5.1
|
github.com/casbin/xorm-adapter/v2 v2.5.1
|
||||||
github.com/casdoor/go-sms-sender v0.0.5
|
github.com/casdoor/go-sms-sender v0.2.0
|
||||||
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
|
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
|
||||||
github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df
|
github.com/go-gomail/gomail v0.0.0-20160411212932-81ebce5c23df
|
||||||
github.com/go-ldap/ldap/v3 v3.3.0
|
github.com/go-ldap/ldap/v3 v3.3.0
|
||||||
|
github.com/go-pay/gopay v1.5.72
|
||||||
github.com/go-sql-driver/mysql v1.5.0
|
github.com/go-sql-driver/mysql v1.5.0
|
||||||
github.com/golang-jwt/jwt/v4 v4.1.0
|
github.com/golang-jwt/jwt/v4 v4.1.0
|
||||||
github.com/google/uuid v1.2.0
|
github.com/google/uuid v1.2.0
|
||||||
github.com/jinzhu/configor v1.2.1 // indirect
|
github.com/jinzhu/configor v1.2.1 // indirect
|
||||||
|
github.com/lestrrat-go/jwx v0.9.0
|
||||||
github.com/markbates/goth v1.68.1-0.20211006204042-9dc8905b41c8
|
github.com/markbates/goth v1.68.1-0.20211006204042-9dc8905b41c8
|
||||||
github.com/qiangmzsx/string-adapter/v2 v2.1.0
|
github.com/qiangmzsx/string-adapter/v2 v2.1.0
|
||||||
github.com/qor/oss v0.0.0-20191031055114-aef9ba66bf76
|
github.com/qor/oss v0.0.0-20191031055114-aef9ba66bf76
|
||||||
@ -25,9 +27,10 @@ require (
|
|||||||
github.com/russellhaering/goxmldsig v1.1.1
|
github.com/russellhaering/goxmldsig v1.1.1
|
||||||
github.com/satori/go.uuid v1.2.0 // indirect
|
github.com/satori/go.uuid v1.2.0 // indirect
|
||||||
github.com/smartystreets/goconvey v1.6.4 // indirect
|
github.com/smartystreets/goconvey v1.6.4 // indirect
|
||||||
|
github.com/stretchr/testify v1.7.0
|
||||||
github.com/tealeg/xlsx v1.0.5
|
github.com/tealeg/xlsx v1.0.5
|
||||||
github.com/thanhpk/randstr v1.0.4
|
github.com/thanhpk/randstr v1.0.4
|
||||||
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3
|
golang.org/x/crypto v0.0.0-20220208233918-bba287dce954
|
||||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2
|
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2
|
||||||
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914
|
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914
|
||||||
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
|
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba // indirect
|
||||||
@ -35,6 +38,7 @@ require (
|
|||||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect
|
||||||
gopkg.in/ini.v1 v1.62.0 // indirect
|
gopkg.in/ini.v1 v1.62.0 // indirect
|
||||||
gopkg.in/square/go-jose.v2 v2.6.0
|
gopkg.in/square/go-jose.v2 v2.6.0
|
||||||
|
gopkg.in/yaml.v2 v2.3.0 // indirect
|
||||||
xorm.io/core v0.7.2
|
xorm.io/core v0.7.2
|
||||||
xorm.io/xorm v1.0.3
|
xorm.io/xorm v1.0.3
|
||||||
)
|
)
|
||||||
|
14
go.sum
14
go.sum
@ -81,6 +81,8 @@ github.com/casbin/xorm-adapter/v2 v2.5.1 h1:BkpIxRHKa0s3bSMx173PpuU7oTs+Zw7XmD0B
|
|||||||
github.com/casbin/xorm-adapter/v2 v2.5.1/go.mod h1:AeH4dBKHC9/zYxzdPVHhPDzF8LYLqjDdb767CWJoV54=
|
github.com/casbin/xorm-adapter/v2 v2.5.1/go.mod h1:AeH4dBKHC9/zYxzdPVHhPDzF8LYLqjDdb767CWJoV54=
|
||||||
github.com/casdoor/go-sms-sender v0.0.5 h1:9qhlMM+UoSOvvY7puUULqSHBBA7fbe02Px/tzchQboo=
|
github.com/casdoor/go-sms-sender v0.0.5 h1:9qhlMM+UoSOvvY7puUULqSHBBA7fbe02Px/tzchQboo=
|
||||||
github.com/casdoor/go-sms-sender v0.0.5/go.mod h1:TMM/BsZQAa+7JVDXl2KqgxnzZgCjmHEX5MBN662mM5M=
|
github.com/casdoor/go-sms-sender v0.0.5/go.mod h1:TMM/BsZQAa+7JVDXl2KqgxnzZgCjmHEX5MBN662mM5M=
|
||||||
|
github.com/casdoor/go-sms-sender v0.2.0 h1:52bin4EBOPzOee64s9UK7jxd22FODvT9/+Y/Z+PSHpg=
|
||||||
|
github.com/casdoor/go-sms-sender v0.2.0/go.mod h1:fsZsNnALvFIo+HFcE1U/oCQv4ZT42FdglXKMsEm3WSk=
|
||||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
|
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
|
||||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
@ -124,6 +126,8 @@ github.com/go-ldap/ldap/v3 v3.3.0 h1:lwx+SJpgOHd8tG6SumBQZXCmNX51zM8B1cfxJ5gv4tQ
|
|||||||
github.com/go-ldap/ldap/v3 v3.3.0/go.mod h1:iYS1MdmrmceOJ1QOTnRXrIs7i3kloqtmGQjRvjKpyMg=
|
github.com/go-ldap/ldap/v3 v3.3.0/go.mod h1:iYS1MdmrmceOJ1QOTnRXrIs7i3kloqtmGQjRvjKpyMg=
|
||||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||||
|
github.com/go-pay/gopay v1.5.72 h1:3zm64xMBhJBa8rXbm//q5UiGgOa4WO5XYEnU394N2Zw=
|
||||||
|
github.com/go-pay/gopay v1.5.72/go.mod h1:0qOGIJuFW7PKDOjmecwKyW0mgsVImgwB9yPJj0ilpn8=
|
||||||
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
||||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||||
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||||
@ -343,8 +347,9 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
|
|||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
|
||||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
||||||
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
||||||
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
|
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
|
||||||
@ -378,8 +383,8 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U
|
|||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M=
|
golang.org/x/crypto v0.0.0-20220208233918-bba287dce954 h1:BkypuErRT9A9I/iljuaG3/zdMjd/J6m8tKKJQtGfSdA=
|
||||||
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
golang.org/x/crypto v0.0.0-20220208233918-bba287dce954/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||||
@ -667,8 +672,9 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
|
||||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||||
|
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
136
idp/adfs.go
Normal file
136
idp/adfs.go
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
// Copyright 2022 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 idp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lestrrat-go/jwx/jwa"
|
||||||
|
"github.com/lestrrat-go/jwx/jwk"
|
||||||
|
"github.com/lestrrat-go/jwx/jwt"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AdfsIdProvider struct {
|
||||||
|
Client *http.Client
|
||||||
|
Config *oauth2.Config
|
||||||
|
Host string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAdfsIdProvider(clientId string, clientSecret string, redirectUrl string, hostUrl string) *AdfsIdProvider {
|
||||||
|
idp := &AdfsIdProvider{}
|
||||||
|
|
||||||
|
config := idp.getConfig(hostUrl)
|
||||||
|
config.ClientID = clientId
|
||||||
|
config.ClientSecret = clientSecret
|
||||||
|
config.RedirectURL = redirectUrl
|
||||||
|
idp.Config = config
|
||||||
|
idp.Host = hostUrl
|
||||||
|
return idp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *AdfsIdProvider) SetHttpClient(client *http.Client) {
|
||||||
|
tr := &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
idp.Client = client
|
||||||
|
idp.Client.Transport = tr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *AdfsIdProvider) getConfig(hostUrl string) *oauth2.Config {
|
||||||
|
var endpoint = oauth2.Endpoint{
|
||||||
|
AuthURL: fmt.Sprintf("%s/adfs/oauth2/authorize", hostUrl),
|
||||||
|
TokenURL: fmt.Sprintf("%s/adfs/oauth2/token", hostUrl),
|
||||||
|
}
|
||||||
|
|
||||||
|
var config = &oauth2.Config{
|
||||||
|
Endpoint: endpoint,
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
type AdfsToken struct {
|
||||||
|
IdToken string `json:"id_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
ErrMsg string `json:"error_description"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// get more detail via: https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/overview/ad-fs-openid-connect-oauth-flows-scenarios#request-an-access-token
|
||||||
|
func (idp *AdfsIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
|
payload := url.Values{}
|
||||||
|
payload.Set("code", code)
|
||||||
|
payload.Set("grant_type", "authorization_code")
|
||||||
|
payload.Set("client_id", idp.Config.ClientID)
|
||||||
|
payload.Set("redirect_uri", idp.Config.RedirectURL)
|
||||||
|
resp, err := idp.Client.PostForm(idp.Config.Endpoint.TokenURL, payload)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pToken := &AdfsToken{}
|
||||||
|
err = json.Unmarshal(data, pToken)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fail to unmarshal token response: %s", err.Error())
|
||||||
|
}
|
||||||
|
if pToken.ErrMsg != "" {
|
||||||
|
return nil, fmt.Errorf("pToken.Errmsg = %s", pToken.ErrMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := &oauth2.Token{
|
||||||
|
AccessToken: pToken.IdToken,
|
||||||
|
Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0),
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since the userinfo endpoint of ADFS only returns sub,
|
||||||
|
// the id_token is used to resolve the userinfo
|
||||||
|
func (idp *AdfsIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("%s/adfs/discovery/keys", idp.Host))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
keyset, err := jwk.Parse(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tokenSrc := []byte(token.AccessToken)
|
||||||
|
publicKey, _ := keyset.Keys[0].Materialize()
|
||||||
|
id_token, _ := jwt.Parse(bytes.NewReader(tokenSrc), jwt.WithVerify(jwa.RS256, publicKey))
|
||||||
|
sid, _ := id_token.Get("sid")
|
||||||
|
upn, _ := id_token.Get("upn")
|
||||||
|
name, _ := id_token.Get("unique_name")
|
||||||
|
userinfo := &UserInfo{
|
||||||
|
Id: sid.(string),
|
||||||
|
Username: name.(string),
|
||||||
|
DisplayName: name.(string),
|
||||||
|
Email: upn.(string),
|
||||||
|
}
|
||||||
|
return userinfo, nil
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -109,6 +109,7 @@ func (idp *BaiduIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error)
|
|||||||
userInfo := UserInfo{
|
userInfo := UserInfo{
|
||||||
Id: baiduUser.OpenId,
|
Id: baiduUser.OpenId,
|
||||||
Username: baiduUser.Username,
|
Username: baiduUser.Username,
|
||||||
|
DisplayName: baiduUser.Username,
|
||||||
AvatarUrl: fmt.Sprintf("https://himg.bdimg.com/sys/portrait/item/%s", baiduUser.Portrait),
|
AvatarUrl: fmt.Sprintf("https://himg.bdimg.com/sys/portrait/item/%s", baiduUser.Portrait),
|
||||||
}
|
}
|
||||||
return &userInfo, nil
|
return &userInfo, nil
|
||||||
|
159
idp/casdoor.go
Normal file
159
idp/casdoor.go
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
// Copyright 2022 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 idp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CasdoorIdProvider struct {
|
||||||
|
Client *http.Client
|
||||||
|
Config *oauth2.Config
|
||||||
|
Host string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCasdoorIdProvider(clientId string, clientSecret string, redirectUrl string, hostUrl string) *CasdoorIdProvider {
|
||||||
|
idp := &CasdoorIdProvider{}
|
||||||
|
config := idp.getConfig(hostUrl)
|
||||||
|
config.ClientID = clientId
|
||||||
|
config.ClientSecret = clientSecret
|
||||||
|
config.RedirectURL = redirectUrl
|
||||||
|
idp.Config = config
|
||||||
|
idp.Host = hostUrl
|
||||||
|
return idp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *CasdoorIdProvider) SetHttpClient(client *http.Client) {
|
||||||
|
idp.Client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *CasdoorIdProvider) getConfig(hostUrl string) *oauth2.Config {
|
||||||
|
return &oauth2.Config{
|
||||||
|
Endpoint: oauth2.Endpoint{
|
||||||
|
TokenURL: hostUrl + "/api/login/oauth/access_token",
|
||||||
|
},
|
||||||
|
Scopes: []string{"openid email profile"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CasdoorToken struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *CasdoorIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
|
resp, err := http.PostForm(idp.Config.Endpoint.TokenURL, url.Values{
|
||||||
|
"client_id": {idp.Config.ClientID},
|
||||||
|
"client_secret": {idp.Config.ClientSecret},
|
||||||
|
"code": {code},
|
||||||
|
"grant_type": {"authorization_code"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pToken := &CasdoorToken{}
|
||||||
|
err = json.Unmarshal(body, pToken)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
//check if token is expired
|
||||||
|
if pToken.ExpiresIn <= 0 {
|
||||||
|
return nil, fmt.Errorf("%s", pToken.AccessToken)
|
||||||
|
}
|
||||||
|
token := &oauth2.Token{
|
||||||
|
AccessToken: pToken.AccessToken,
|
||||||
|
Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0),
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
{
|
||||||
|
"sub": "2f80c349-4beb-407f-b1f0-528aac0f1acd",
|
||||||
|
"iss": "https://door.casbin.com",
|
||||||
|
"aud": "7a11****0fa2172",
|
||||||
|
"name": "admin",
|
||||||
|
"preferred_username": "Admin",
|
||||||
|
"email": "admin@example.com",
|
||||||
|
"picture": "https://casbin.org/img/casbin.svg",
|
||||||
|
"address": "Guangdong",
|
||||||
|
"phone": "12345678910"
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
type CasdoorUserInfo struct {
|
||||||
|
Id string `json:"sub"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
DisplayName string `json:"preferred_username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
AvatarUrl string `json:"picture"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Msg string `json:"msg"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *CasdoorIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
|
cdUserinfo := &CasdoorUserInfo{}
|
||||||
|
accessToken := token.AccessToken
|
||||||
|
request, err := http.NewRequest("GET", fmt.Sprintf("%s/api/userinfo", idp.Host), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
//add accesstoken to bearer token
|
||||||
|
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", accessToken))
|
||||||
|
resp, err := idp.Client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(data, cdUserinfo)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if cdUserinfo.Status != "" {
|
||||||
|
return nil, fmt.Errorf("err: %s", cdUserinfo.Msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
userInfo := &UserInfo{
|
||||||
|
Id: cdUserinfo.Id,
|
||||||
|
Username: cdUserinfo.Name,
|
||||||
|
DisplayName: cdUserinfo.DisplayName,
|
||||||
|
Email: cdUserinfo.Email,
|
||||||
|
AvatarUrl: cdUserinfo.AvatarUrl,
|
||||||
|
}
|
||||||
|
return userInfo, nil
|
||||||
|
|
||||||
|
}
|
320
idp/dingtalk.go
320
idp/dingtalk.go
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -15,32 +15,16 @@
|
|||||||
package idp
|
package idp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"crypto/hmac"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A total of three steps are required:
|
|
||||||
//
|
|
||||||
// 1. Construct the link and get the temporary authorization code
|
|
||||||
// tmp_auth_code through the code at the end of the url.
|
|
||||||
//
|
|
||||||
// 2. Use hmac256 to calculate the signature, and then submit it together with timestamp,
|
|
||||||
// tmp_auth_code, accessKey to obtain unionid, userid, accessKey.
|
|
||||||
//
|
|
||||||
// 3. Get detailed information through userid.
|
|
||||||
|
|
||||||
type DingTalkIdProvider struct {
|
type DingTalkIdProvider struct {
|
||||||
Client *http.Client
|
Client *http.Client
|
||||||
Config *oauth2.Config
|
Config *oauth2.Config
|
||||||
@ -64,8 +48,8 @@ func (idp *DingTalkIdProvider) SetHttpClient(client *http.Client) {
|
|||||||
// getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow
|
// getConfig return a point of Config, which describes a typical 3-legged OAuth2 flow
|
||||||
func (idp *DingTalkIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config {
|
func (idp *DingTalkIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config {
|
||||||
var endpoint = oauth2.Endpoint{
|
var endpoint = oauth2.Endpoint{
|
||||||
AuthURL: "https://oapi.dingtalk.com/sns/getuserinfo_bycode",
|
AuthURL: "https://api.dingtalk.com/v1.0/contact/users/me",
|
||||||
TokenURL: "https://oapi.dingtalk.com/gettoken",
|
TokenURL: "https://api.dingtalk.com/v1.0/oauth2/userAccessToken",
|
||||||
}
|
}
|
||||||
|
|
||||||
var config = &oauth2.Config{
|
var config = &oauth2.Config{
|
||||||
@ -83,256 +67,121 @@ func (idp *DingTalkIdProvider) getConfig(clientId string, clientSecret string, r
|
|||||||
}
|
}
|
||||||
|
|
||||||
type DingTalkAccessToken struct {
|
type DingTalkAccessToken struct {
|
||||||
ErrCode int `json:"errcode"`
|
ErrCode int `json:"code"`
|
||||||
ErrMsg string `json:"errmsg"`
|
ErrMsg string `json:"message"`
|
||||||
AccessToken string `json:"access_token"` // Interface call credentials
|
AccessToken string `json:"accessToken"` // Interface call credentials
|
||||||
ExpiresIn int64 `json:"expires_in"` // access_token interface call credential timeout time, unit (seconds)
|
ExpiresIn int64 `json:"expireIn"` // access_token interface call credential timeout time, unit (seconds)
|
||||||
}
|
}
|
||||||
|
|
||||||
type DingTalkIds struct {
|
// GetToken use code get access_token (*operation of getting authCode ought to be done in front)
|
||||||
UserId string `json:"user_id"`
|
// get more detail via: https://open.dingtalk.com/document/orgapp-server/obtain-user-token
|
||||||
UnionId string `json:"union_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type InfoResp struct {
|
|
||||||
Errcode int `json:"errcode"`
|
|
||||||
UserInfo struct {
|
|
||||||
Nick string `json:"nick"`
|
|
||||||
Unionid string `json:"unionid"`
|
|
||||||
Openid string `json:"openid"`
|
|
||||||
MainOrgAuthHighLevel bool `json:"main_org_auth_high_level"`
|
|
||||||
} `json:"user_info"`
|
|
||||||
Errmsg string `json:"errmsg"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetToken use code get access_token (*operation of getting code ought to be done in front)
|
|
||||||
// get more detail via: https://developers.dingtalk.com/document/app/dingtalk-retrieve-user-information?spm=ding_open_doc.document.0.0.51b91a31wWV3tY#doc-api-dingtalk-GetUser
|
|
||||||
func (idp *DingTalkIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
func (idp *DingTalkIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
|
pTokenParams := &struct {
|
||||||
signature := EncodeSHA256(timestamp, idp.Config.ClientSecret)
|
ClientId string `json:"clientId"`
|
||||||
u := fmt.Sprintf(
|
ClientSecret string `json:"clientSecret"`
|
||||||
"%s?accessKey=%s×tamp=%s&signature=%s", idp.Config.Endpoint.AuthURL,
|
Code string `json:"code"`
|
||||||
idp.Config.ClientID, timestamp, signature)
|
GrantType string `json:"grantType"`
|
||||||
|
}{idp.Config.ClientID, idp.Config.ClientSecret, code, "authorization_code"}
|
||||||
|
|
||||||
tmpCode := struct {
|
data, err := idp.postWithBody(pTokenParams, idp.Config.Endpoint.TokenURL)
|
||||||
TmpAuthCode string `json:"tmp_auth_code"`
|
|
||||||
}{code}
|
|
||||||
bs, _ := json.Marshal(tmpCode)
|
|
||||||
r := strings.NewReader(string(bs))
|
|
||||||
resp, err := http.Post(u, "application/json;charset=UTF-8", r)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func(Body io.ReadCloser) {
|
pToken := &DingTalkAccessToken{}
|
||||||
err := Body.Close()
|
err = json.Unmarshal(data, pToken)
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}(resp.Body)
|
|
||||||
|
|
||||||
body, _ := io.ReadAll(resp.Body)
|
|
||||||
info := InfoResp{}
|
|
||||||
_ = json.Unmarshal(body, &info)
|
|
||||||
errCode := info.Errcode
|
|
||||||
if errCode != 0 {
|
|
||||||
return nil, fmt.Errorf("%d: %s", errCode, info.Errmsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
u2 := fmt.Sprintf("%s?appkey=%s&appsecret=%s", idp.Config.Endpoint.TokenURL, idp.Config.ClientID, idp.Config.ClientSecret)
|
|
||||||
resp, _ = http.Get(u2)
|
|
||||||
defer func(Body io.ReadCloser) {
|
|
||||||
err := Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}(resp.Body)
|
|
||||||
body, _ = io.ReadAll(resp.Body)
|
|
||||||
tokenResp := DingTalkAccessToken{}
|
|
||||||
_ = json.Unmarshal(body, &tokenResp)
|
|
||||||
if tokenResp.ErrCode != 0 {
|
|
||||||
return nil, fmt.Errorf("%d: %s", tokenResp.ErrCode, tokenResp.ErrMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
// use unionid to get userid
|
|
||||||
unionid := info.UserInfo.Unionid
|
|
||||||
userid, err := idp.GetUseridByUnionid(tokenResp.AccessToken, unionid)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Since DingTalk does not require scopes, put userid and unionid into
|
if pToken.ErrCode != 0 {
|
||||||
// idp.config.scopes to facilitate GetUserInfo() to obtain these two parameters.
|
return nil, fmt.Errorf("pToken.Errcode = %d, pToken.Errmsg = %s", pToken.ErrCode, pToken.ErrMsg)
|
||||||
idp.Config.Scopes = []string{unionid, userid}
|
}
|
||||||
|
|
||||||
token := &oauth2.Token{
|
token := &oauth2.Token{
|
||||||
AccessToken: tokenResp.AccessToken,
|
AccessToken: pToken.AccessToken,
|
||||||
Expiry: time.Unix(time.Now().Unix()+tokenResp.ExpiresIn, 0),
|
Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0),
|
||||||
}
|
}
|
||||||
|
|
||||||
return token, nil
|
return token, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type UnionIdResponse struct {
|
|
||||||
Errcode int `json:"errcode"`
|
|
||||||
Errmsg string `json:"errmsg"`
|
|
||||||
Result struct {
|
|
||||||
ContactType string `json:"contact_type"`
|
|
||||||
Userid string `json:"userid"`
|
|
||||||
} `json:"result"`
|
|
||||||
RequestId string `json:"request_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUseridByUnionid ...
|
|
||||||
func (idp *DingTalkIdProvider) GetUseridByUnionid(accesstoken, unionid string) (userid string, err error) {
|
|
||||||
u := fmt.Sprintf("https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s&unionid=%s",
|
|
||||||
accesstoken, unionid)
|
|
||||||
useridInfo, err := idp.GetUrlResp(u)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
uresp := UnionIdResponse{}
|
|
||||||
_ = json.Unmarshal([]byte(useridInfo), &uresp)
|
|
||||||
errcode := uresp.Errcode
|
|
||||||
if errcode != 0 {
|
|
||||||
return "", fmt.Errorf("%d: %s", errcode, uresp.Errmsg)
|
|
||||||
}
|
|
||||||
return uresp.Result.Userid, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
{
|
{
|
||||||
"errcode":0,
|
{
|
||||||
"result":{
|
"nick" : "zhangsan",
|
||||||
"boss":false,
|
"avatarUrl" : "https://xxx",
|
||||||
"unionid":"5M6zgZBKQPCxdiPdANeJ6MgiEiE",
|
"mobile" : "150xxxx9144",
|
||||||
"role_list":[
|
"openId" : "123",
|
||||||
{
|
"unionId" : "z21HjQliSzpw0Yxxxx",
|
||||||
"group_name":"默认",
|
"email" : "zhangsan@alibaba-inc.com",
|
||||||
"name":"主管理员",
|
"stateCode" : "86"
|
||||||
"id":2062489174
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"exclusive_account":false,
|
|
||||||
"mobile":"15236176076",
|
|
||||||
"active":true,
|
|
||||||
"admin":true,
|
|
||||||
"avatar":"https://static-legacy.dingtalk.com/media/lALPDeRETW9WAnnNAyDNAyA_800_800.png",
|
|
||||||
"hide_mobile":false,
|
|
||||||
"userid":"manager4713",
|
|
||||||
"senior":false,
|
|
||||||
"dept_order_list":[
|
|
||||||
{
|
|
||||||
"dept_id":1,
|
|
||||||
"order":176294576350761512
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"real_authed":true,
|
|
||||||
"name":"刘继坤",
|
|
||||||
"dept_id_list":[
|
|
||||||
1
|
|
||||||
],
|
|
||||||
"state_code":"86",
|
|
||||||
"email":"",
|
|
||||||
"leader_in_dept":[
|
|
||||||
{
|
|
||||||
"leader":false,
|
|
||||||
"dept_id":1
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"errmsg":"ok",
|
|
||||||
"request_id":"3sug9d2exsla"
|
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
type DingTalkUserResponse struct {
|
type DingTalkUserResponse struct {
|
||||||
Errcode int `json:"errcode"`
|
Nick string `json:"nick"`
|
||||||
Errmsg string `json:"errmsg"`
|
OpenId string `json:"openId"`
|
||||||
Result struct {
|
AvatarUrl string `json:"avatarUrl"`
|
||||||
Extension string `json:"extension"`
|
|
||||||
Unionid string `json:"unionid"`
|
|
||||||
Boss bool `json:"boss"`
|
|
||||||
UnionEmpExt struct {
|
|
||||||
CorpId string `json:"corpId"`
|
|
||||||
Userid string `json:"userid"`
|
|
||||||
UnionEmpMapList []struct {
|
|
||||||
CorpId string `json:"corpId"`
|
|
||||||
Userid string `json:"userid"`
|
|
||||||
} `json:"unionEmpMapList"`
|
|
||||||
} `json:"unionEmpExt"`
|
|
||||||
RoleList []struct {
|
|
||||||
GroupName string `json:"group_name"`
|
|
||||||
Id int `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
} `json:"role_list"`
|
|
||||||
Admin bool `json:"admin"`
|
|
||||||
Remark string `json:"remark"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
HiredDate int64 `json:"hired_date"`
|
|
||||||
Userid string `json:"userid"`
|
|
||||||
WorkPlace string `json:"work_place"`
|
|
||||||
DeptOrderList []struct {
|
|
||||||
DeptId int `json:"dept_id"`
|
|
||||||
Order int64 `json:"order"`
|
|
||||||
} `json:"dept_order_list"`
|
|
||||||
RealAuthed bool `json:"real_authed"`
|
|
||||||
DeptIdList []int `json:"dept_id_list"`
|
|
||||||
JobNumber string `json:"job_number"`
|
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
LeaderInDept []struct {
|
Errmsg string `json:"message"`
|
||||||
DeptId int `json:"dept_id"`
|
Errcode string `json:"code"`
|
||||||
Leader bool `json:"leader"`
|
|
||||||
} `json:"leader_in_dept"`
|
|
||||||
ManagerUserid string `json:"manager_userid"`
|
|
||||||
Mobile string `json:"mobile"`
|
|
||||||
Active bool `json:"active"`
|
|
||||||
Telephone string `json:"telephone"`
|
|
||||||
Avatar string `json:"avatar"`
|
|
||||||
HideMobile bool `json:"hide_mobile"`
|
|
||||||
Senior bool `json:"senior"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
StateCode string `json:"state_code"`
|
|
||||||
} `json:"result"`
|
|
||||||
RequestId string `json:"request_id"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUserInfo Use userid and access_token to get UserInfo
|
// GetUserInfo Use access_token to get UserInfo
|
||||||
// get more detail via: https://developers.dingtalk.com/document/app/query-user-details
|
// get more detail via: https://open.dingtalk.com/document/orgapp-server/dingtalk-retrieve-user-information
|
||||||
func (idp *DingTalkIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
func (idp *DingTalkIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
var dtUserInfo DingTalkUserResponse
|
dtUserInfo := &DingTalkUserResponse{}
|
||||||
accessToken := token.AccessToken
|
accessToken := token.AccessToken
|
||||||
|
|
||||||
u := fmt.Sprintf("https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s&userid=%s",
|
reqest, err := http.NewRequest("GET", idp.Config.Endpoint.AuthURL, nil)
|
||||||
accessToken, idp.Config.Scopes[1])
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
userinfoResp, err := idp.GetUrlResp(u)
|
}
|
||||||
|
reqest.Header.Add("x-acs-dingtalk-access-token", accessToken)
|
||||||
|
resp, err := idp.Client.Do(reqest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = json.Unmarshal([]byte(userinfoResp), &dtUserInfo); err != nil {
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = json.Unmarshal(data, dtUserInfo)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if dtUserInfo.Errmsg != "" {
|
||||||
|
return nil, fmt.Errorf("userIdResp.Errcode = %s, userIdResp.Errmsg = %s", dtUserInfo.Errcode, dtUserInfo.Errmsg)
|
||||||
|
}
|
||||||
|
|
||||||
userInfo := UserInfo{
|
userInfo := UserInfo{
|
||||||
Id: strconv.Itoa(dtUserInfo.Result.RoleList[0].Id),
|
Id: dtUserInfo.OpenId,
|
||||||
Username: dtUserInfo.Result.RoleList[0].Name,
|
Username: dtUserInfo.Nick,
|
||||||
DisplayName: dtUserInfo.Result.Name,
|
DisplayName: dtUserInfo.Nick,
|
||||||
Email: dtUserInfo.Result.Email,
|
Email: dtUserInfo.Email,
|
||||||
AvatarUrl: dtUserInfo.Result.Avatar,
|
AvatarUrl: dtUserInfo.AvatarUrl,
|
||||||
}
|
}
|
||||||
|
|
||||||
return &userInfo, nil
|
return &userInfo, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (idp *DingTalkIdProvider) GetUrlResp(url string) (string, error) {
|
func (idp *DingTalkIdProvider) postWithBody(body interface{}, url string) ([]byte, error) {
|
||||||
resp, err := idp.Client.Get(url)
|
bs, err := json.Marshal(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return nil, err
|
||||||
|
}
|
||||||
|
r := strings.NewReader(string(bs))
|
||||||
|
resp, err := idp.Client.Post(url, "application/json;charset=UTF-8", r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer func(Body io.ReadCloser) {
|
defer func(Body io.ReadCloser) {
|
||||||
err := Body.Close()
|
err := Body.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -340,26 +189,5 @@ func (idp *DingTalkIdProvider) GetUrlResp(url string) (string, error) {
|
|||||||
}
|
}
|
||||||
}(resp.Body)
|
}(resp.Body)
|
||||||
|
|
||||||
buf := new(bytes.Buffer)
|
return data, nil
|
||||||
_, err = buf.ReadFrom(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return buf.String(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncodeSHA256 Use the HmacSHA256 algorithm to sign, the signature data is the current timestamp,
|
|
||||||
// and the key is the appSecret corresponding to the appId. Use this key to calculate the timestamp signature value.
|
|
||||||
// get more detail via: https://developers.dingtalk.com/document/app/signature-calculation-for-logon-free-scenarios-1?spm=ding_open_doc.document.0.0.63262ea7l6iEm1#topic-2021698
|
|
||||||
func EncodeSHA256(message, secret string) string {
|
|
||||||
h := hmac.New(sha256.New, []byte(secret))
|
|
||||||
h.Write([]byte(message))
|
|
||||||
sum := h.Sum(nil)
|
|
||||||
msg1 := base64.StdEncoding.EncodeToString(sum)
|
|
||||||
|
|
||||||
uv := url.Values{}
|
|
||||||
uv.Add("0", msg1)
|
|
||||||
msg2 := uv.Encode()[2:]
|
|
||||||
return msg2
|
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -164,6 +164,7 @@ func (idp *FacebookIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, erro
|
|||||||
|
|
||||||
userInfo := UserInfo{
|
userInfo := UserInfo{
|
||||||
Id: facebookUserInfo.Id,
|
Id: facebookUserInfo.Id,
|
||||||
|
Username: facebookUserInfo.Name,
|
||||||
DisplayName: facebookUserInfo.Name,
|
DisplayName: facebookUserInfo.Name,
|
||||||
Email: facebookUserInfo.Email,
|
Email: facebookUserInfo.Email,
|
||||||
AvatarUrl: facebookUserInfo.Picture.Data.Url,
|
AvatarUrl: facebookUserInfo.Picture.Data.Url,
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
30
idp/goth.go
30
idp/goth.go
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -45,6 +45,7 @@ import (
|
|||||||
"github.com/markbates/goth/providers/salesforce"
|
"github.com/markbates/goth/providers/salesforce"
|
||||||
"github.com/markbates/goth/providers/shopify"
|
"github.com/markbates/goth/providers/shopify"
|
||||||
"github.com/markbates/goth/providers/slack"
|
"github.com/markbates/goth/providers/slack"
|
||||||
|
"github.com/markbates/goth/providers/steam"
|
||||||
"github.com/markbates/goth/providers/tumblr"
|
"github.com/markbates/goth/providers/tumblr"
|
||||||
"github.com/markbates/goth/providers/twitter"
|
"github.com/markbates/goth/providers/twitter"
|
||||||
"github.com/markbates/goth/providers/yahoo"
|
"github.com/markbates/goth/providers/yahoo"
|
||||||
@ -171,6 +172,11 @@ func NewGothIdProvider(providerType string, clientId string, clientSecret string
|
|||||||
Provider: slack.New(clientId, clientSecret, redirectUrl),
|
Provider: slack.New(clientId, clientSecret, redirectUrl),
|
||||||
Session: &slack.Session{},
|
Session: &slack.Session{},
|
||||||
}
|
}
|
||||||
|
case "Steam":
|
||||||
|
idp = GothIdProvider{
|
||||||
|
Provider: steam.New(clientSecret, redirectUrl),
|
||||||
|
Session: &steam.Session{},
|
||||||
|
}
|
||||||
case "Tumblr":
|
case "Tumblr":
|
||||||
idp = GothIdProvider{
|
idp = GothIdProvider{
|
||||||
Provider: tumblr.New(clientId, clientSecret, redirectUrl),
|
Provider: tumblr.New(clientId, clientSecret, redirectUrl),
|
||||||
@ -209,10 +215,21 @@ func (idp *GothIdProvider) SetHttpClient(client *http.Client) {
|
|||||||
|
|
||||||
func (idp *GothIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
func (idp *GothIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
var expireAt time.Time
|
var expireAt time.Time
|
||||||
|
var value url.Values
|
||||||
|
var err error
|
||||||
|
if idp.Provider.Name() == "steam" {
|
||||||
|
value, err = url.ParseQuery(code)
|
||||||
|
returnUrl := reflect.ValueOf(idp.Session).Elem().FieldByName("CallbackURL")
|
||||||
|
returnUrl.Set(reflect.ValueOf(value.Get("openid.return_to")))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
//Need to construct variables supported by goth
|
//Need to construct variables supported by goth
|
||||||
//to call the function to obtain accessToken
|
//to call the function to obtain accessToken
|
||||||
value := url.Values{}
|
value = url.Values{}
|
||||||
value.Add("code", code)
|
value.Add("code", code)
|
||||||
|
}
|
||||||
accessToken, err := idp.Session.Authorize(idp.Provider, value)
|
accessToken, err := idp.Session.Authorize(idp.Provider, value)
|
||||||
//Get ExpiresAt's value
|
//Get ExpiresAt's value
|
||||||
valueOfExpire := reflect.ValueOf(idp.Session).Elem().FieldByName("ExpiresAt")
|
valueOfExpire := reflect.ValueOf(idp.Session).Elem().FieldByName("ExpiresAt")
|
||||||
@ -231,10 +248,10 @@ func (idp *GothIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return getUser(gothUser), nil
|
return getUser(gothUser, idp.Provider.Name()), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUser(gothUser goth.User) *UserInfo {
|
func getUser(gothUser goth.User, provider string) *UserInfo {
|
||||||
user := UserInfo{
|
user := UserInfo{
|
||||||
Id: gothUser.UserID,
|
Id: gothUser.UserID,
|
||||||
Username: gothUser.Name,
|
Username: gothUser.Name,
|
||||||
@ -258,7 +275,10 @@ func getUser(gothUser goth.User) *UserInfo {
|
|||||||
user.DisplayName = user.Username
|
user.DisplayName = user.Username
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if provider == "steam" {
|
||||||
|
user.Username = user.DisplayName
|
||||||
|
user.Email = ""
|
||||||
|
}
|
||||||
return &user
|
return &user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
192
idp/infoflow_internal.go
Normal file
192
idp/infoflow_internal.go
Normal file
@ -0,0 +1,192 @@
|
|||||||
|
// Copyright 2022 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 idp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InfoflowInternalIdProvider struct {
|
||||||
|
Client *http.Client
|
||||||
|
Config *oauth2.Config
|
||||||
|
AgentId string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInfoflowInternalIdProvider(clientId string, clientSecret string, appId string, redirectUrl string) *InfoflowInternalIdProvider {
|
||||||
|
idp := &InfoflowInternalIdProvider{}
|
||||||
|
|
||||||
|
config := idp.getConfig(clientId, clientSecret, redirectUrl)
|
||||||
|
idp.Config = config
|
||||||
|
idp.AgentId = appId
|
||||||
|
return idp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *InfoflowInternalIdProvider) SetHttpClient(client *http.Client) {
|
||||||
|
idp.Client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *InfoflowInternalIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config {
|
||||||
|
var config = &oauth2.Config{
|
||||||
|
ClientID: clientId,
|
||||||
|
ClientSecret: clientSecret,
|
||||||
|
RedirectURL: redirectUrl,
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
type InfoflowInterToken struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// get more detail via: https://qy.baidu.com/doc/index.html#/inner_quickstart/flow?id=%E8%8E%B7%E5%8F%96accesstoken
|
||||||
|
func (idp *InfoflowInternalIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
|
pTokenParams := &struct {
|
||||||
|
CorpId string `json:"corpid"`
|
||||||
|
Corpsecret string `json:"corpsecret"`
|
||||||
|
}{idp.Config.ClientID, idp.Config.ClientSecret}
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("https://qy.im.baidu.com/api/gettoken?corpid=%s&corpsecret=%s", pTokenParams.CorpId, pTokenParams.Corpsecret))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pToken := &InfoflowInterToken{}
|
||||||
|
err = json.Unmarshal(data, pToken)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pToken.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("pToken.Errcode = %d, pToken.Errmsg = %s", pToken.Errcode, pToken.Errmsg)
|
||||||
|
}
|
||||||
|
token := &oauth2.Token{
|
||||||
|
AccessToken: pToken.AccessToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := make(map[string]interface{})
|
||||||
|
raw["code"] = code
|
||||||
|
token = token.WithExtra(raw)
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
{
|
||||||
|
"errcode": 0,
|
||||||
|
"errmsg": "ok",
|
||||||
|
"userid": "lili",
|
||||||
|
"name": "丽丽",
|
||||||
|
"department": [1],
|
||||||
|
"mobile": "13500088888",
|
||||||
|
"email": "lili4@gzdev.com",
|
||||||
|
"imid": 40000318,
|
||||||
|
"hiuname": "lili4",
|
||||||
|
"status": 1,
|
||||||
|
"extattr":
|
||||||
|
{
|
||||||
|
"attrs": [
|
||||||
|
{
|
||||||
|
"name": "爱好",
|
||||||
|
"value": "旅游"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "卡号,
|
||||||
|
"value": "1234567234"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"lm": 14236463257
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
type InfoflowInternalUserResp struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
UserId string `json:"UserId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type InfoflowInternalUserInfo struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
UserId string `json:"userid"`
|
||||||
|
Imid int `json:"imid"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Avatar string `json:"headimg"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// get more detail via: https://qy.baidu.com/doc/index.html#/inner_serverapi/contacts?id=%e8%8e%b7%e5%8f%96%e6%88%90%e5%91%98
|
||||||
|
func (idp *InfoflowInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
|
//Get userid first
|
||||||
|
accessToken := token.AccessToken
|
||||||
|
code := token.Extra("code").(string)
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("https://qy.im.baidu.com/api/user/getuserinfo?access_token=%s&code=%s&agentid=%s", accessToken, code, idp.AgentId))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
userResp := &InfoflowInternalUserResp{}
|
||||||
|
err = json.Unmarshal(data, userResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if userResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userIdResp.Errcode = %d, userIdResp.Errmsg = %s", userResp.Errcode, userResp.Errmsg)
|
||||||
|
}
|
||||||
|
//Use userid and accesstoken to get user information
|
||||||
|
resp, err = idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
infoResp := &InfoflowInternalUserInfo{}
|
||||||
|
err = json.Unmarshal(data, infoResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if infoResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userInfoResp.errcode = %d, userInfoResp.errmsg = %s", infoResp.Errcode, infoResp.Errmsg)
|
||||||
|
}
|
||||||
|
userInfo := UserInfo{
|
||||||
|
Id: infoResp.UserId,
|
||||||
|
Username: infoResp.UserId,
|
||||||
|
DisplayName: infoResp.Name,
|
||||||
|
AvatarUrl: infoResp.Avatar,
|
||||||
|
Email: infoResp.Email,
|
||||||
|
}
|
||||||
|
|
||||||
|
if userInfo.Id == "" {
|
||||||
|
userInfo.Id = userInfo.Username
|
||||||
|
}
|
||||||
|
return &userInfo, nil
|
||||||
|
}
|
211
idp/infoflow_third_party.go
Normal file
211
idp/infoflow_third_party.go
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
// Copyright 2022 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 idp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type InfoflowIdProvider struct {
|
||||||
|
Client *http.Client
|
||||||
|
Config *oauth2.Config
|
||||||
|
AgentId string
|
||||||
|
Ticket string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInfoflowIdProvider(clientId string, clientSecret string, appId string, redirectUrl string) *InfoflowIdProvider {
|
||||||
|
idp := &InfoflowIdProvider{}
|
||||||
|
|
||||||
|
config := idp.getConfig(clientId, clientSecret, redirectUrl)
|
||||||
|
idp.Config = config
|
||||||
|
idp.AgentId = appId
|
||||||
|
return idp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *InfoflowIdProvider) SetHttpClient(client *http.Client) {
|
||||||
|
idp.Client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *InfoflowIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config {
|
||||||
|
var config = &oauth2.Config{
|
||||||
|
ClientID: clientId,
|
||||||
|
ClientSecret: clientSecret,
|
||||||
|
RedirectURL: redirectUrl,
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
type InfoflowToken struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
AccessToken string `json:"suite_access_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// get more detail via: https://qy.baidu.com/doc/index.html#/third_serverapi/authority
|
||||||
|
func (idp *InfoflowIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
|
pTokenParams := &struct {
|
||||||
|
SuiteId string `json:"suite_id"`
|
||||||
|
SuiteSecret string `json:"suite_secret"`
|
||||||
|
SuiteTicket string `json:"suite_ticket"`
|
||||||
|
}{idp.Config.ClientID, idp.Config.ClientSecret, idp.Ticket}
|
||||||
|
data, err := idp.postWithBody(pTokenParams, "https://api.im.baidu.com/api/service/get_suite_token")
|
||||||
|
|
||||||
|
pToken := &InfoflowToken{}
|
||||||
|
err = json.Unmarshal(data, pToken)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pToken.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("pToken.Errcode = %d, pToken.Errmsg = %s", pToken.Errcode, pToken.Errmsg)
|
||||||
|
}
|
||||||
|
token := &oauth2.Token{
|
||||||
|
AccessToken: pToken.AccessToken,
|
||||||
|
Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := make(map[string]interface{})
|
||||||
|
raw["code"] = code
|
||||||
|
token = token.WithExtra(raw)
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
{
|
||||||
|
"errcode": 0,
|
||||||
|
"errmsg": "ok",
|
||||||
|
"userid": "lili",
|
||||||
|
"name": "丽丽",
|
||||||
|
"department": [1],
|
||||||
|
"mobile": "13500088888",
|
||||||
|
"email": "lili4@gzdev.com",
|
||||||
|
"imid": 40000318,
|
||||||
|
"hiuname": "lili4",
|
||||||
|
"status": 1,
|
||||||
|
"extattr": {
|
||||||
|
"attrs": [
|
||||||
|
{
|
||||||
|
"name": "爱好",
|
||||||
|
"value": "旅游"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "卡号",
|
||||||
|
"value": "1234567234"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"lm" : 14236463257
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
type InfoflowUserResp struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
UserId string `json:"UserId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type InfoflowUserInfo struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
Imid string `json:"imid"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// get more detail via: https://qy.baidu.com/doc/index.html#/third_serverapi/contacts?id=%e8%8e%b7%e5%8f%96%e6%88%90%e5%91%98
|
||||||
|
func (idp *InfoflowIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
|
//Get userid first
|
||||||
|
accessToken := token.AccessToken
|
||||||
|
code := token.Extra("code").(string)
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/getuserinfo?access_token=%s&code=%s&agentid=%s", accessToken, code, idp.AgentId))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
userResp := &InfoflowUserResp{}
|
||||||
|
err = json.Unmarshal(data, userResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if userResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userIdResp.Errcode = %d, userIdResp.Errmsg = %s", userResp.Errcode, userResp.Errmsg)
|
||||||
|
}
|
||||||
|
//Use userid and accesstoken to get user information
|
||||||
|
resp, err = idp.Client.Get(fmt.Sprintf("https://api.im.baidu.com/api/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
infoResp := &InfoflowUserInfo{}
|
||||||
|
err = json.Unmarshal(data, infoResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if infoResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userInfoResp.errcode = %d, userInfoResp.errmsg = %s", infoResp.Errcode, infoResp.Errmsg)
|
||||||
|
}
|
||||||
|
userInfo := UserInfo{
|
||||||
|
Id: infoResp.Imid,
|
||||||
|
Username: infoResp.Name,
|
||||||
|
DisplayName: infoResp.Name,
|
||||||
|
Email: infoResp.Email,
|
||||||
|
}
|
||||||
|
|
||||||
|
if userInfo.Id == "" {
|
||||||
|
userInfo.Id = userInfo.Username
|
||||||
|
}
|
||||||
|
return &userInfo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *InfoflowIdProvider) postWithBody(body interface{}, url string) ([]byte, error) {
|
||||||
|
bs, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
r := strings.NewReader(string(bs))
|
||||||
|
resp, err := idp.Client.Post(url, "application/json;charset=UTF-8", r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func(Body io.ReadCloser) {
|
||||||
|
err := Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}(resp.Body)
|
||||||
|
|
||||||
|
return data, nil
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -35,41 +35,59 @@ type IdProvider interface {
|
|||||||
GetUserInfo(token *oauth2.Token) (*UserInfo, error)
|
GetUserInfo(token *oauth2.Token) (*UserInfo, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetIdProvider(providerType string, clientId string, clientSecret string, redirectUrl string) IdProvider {
|
func GetIdProvider(typ string, subType string, clientId string, clientSecret string, appId string, redirectUrl string, hostUrl string) IdProvider {
|
||||||
if providerType == "GitHub" {
|
if typ == "GitHub" {
|
||||||
return NewGithubIdProvider(clientId, clientSecret, redirectUrl)
|
return NewGithubIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Google" {
|
} else if typ == "Google" {
|
||||||
return NewGoogleIdProvider(clientId, clientSecret, redirectUrl)
|
return NewGoogleIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "QQ" {
|
} else if typ == "QQ" {
|
||||||
return NewQqIdProvider(clientId, clientSecret, redirectUrl)
|
return NewQqIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "WeChat" {
|
} else if typ == "WeChat" {
|
||||||
return NewWeChatIdProvider(clientId, clientSecret, redirectUrl)
|
return NewWeChatIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Facebook" {
|
} else if typ == "Facebook" {
|
||||||
return NewFacebookIdProvider(clientId, clientSecret, redirectUrl)
|
return NewFacebookIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "DingTalk" {
|
} else if typ == "DingTalk" {
|
||||||
return NewDingTalkIdProvider(clientId, clientSecret, redirectUrl)
|
return NewDingTalkIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Weibo" {
|
} else if typ == "Weibo" {
|
||||||
return NewWeiBoIdProvider(clientId, clientSecret, redirectUrl)
|
return NewWeiBoIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Gitee" {
|
} else if typ == "Gitee" {
|
||||||
return NewGiteeIdProvider(clientId, clientSecret, redirectUrl)
|
return NewGiteeIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "LinkedIn" {
|
} else if typ == "LinkedIn" {
|
||||||
return NewLinkedInIdProvider(clientId, clientSecret, redirectUrl)
|
return NewLinkedInIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "WeCom" {
|
} else if typ == "WeCom" {
|
||||||
|
if subType == "Internal" {
|
||||||
|
return NewWeComInternalIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
|
} else if subType == "Third-party" {
|
||||||
return NewWeComIdProvider(clientId, clientSecret, redirectUrl)
|
return NewWeComIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Lark" {
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
} else if typ == "Lark" {
|
||||||
return NewLarkIdProvider(clientId, clientSecret, redirectUrl)
|
return NewLarkIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "GitLab" {
|
} else if typ == "GitLab" {
|
||||||
return NewGitlabIdProvider(clientId, clientSecret, redirectUrl)
|
return NewGitlabIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if providerType == "Baidu" {
|
} else if typ == "Adfs" {
|
||||||
|
return NewAdfsIdProvider(clientId, clientSecret, redirectUrl, hostUrl)
|
||||||
|
} else if typ == "Baidu" {
|
||||||
return NewBaiduIdProvider(clientId, clientSecret, redirectUrl)
|
return NewBaiduIdProvider(clientId, clientSecret, redirectUrl)
|
||||||
} else if isGothSupport(providerType) {
|
} else if typ == "Infoflow" {
|
||||||
return NewGothIdProvider(providerType, clientId, clientSecret, redirectUrl)
|
if subType == "Internal" {
|
||||||
|
return NewInfoflowInternalIdProvider(clientId, clientSecret, appId, redirectUrl)
|
||||||
|
} else if subType == "Third-party" {
|
||||||
|
return NewInfoflowIdProvider(clientId, clientSecret, appId, redirectUrl)
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
} else if typ == "Casdoor" {
|
||||||
|
return NewCasdoorIdProvider(clientId, clientSecret, redirectUrl, hostUrl)
|
||||||
|
} else if isGothSupport(typ) {
|
||||||
|
return NewGothIdProvider(typ, clientId, clientSecret, redirectUrl)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var gothList = []string{"Apple", "AzureAd", "Slack"}
|
var gothList = []string{"Apple", "AzureAd", "Slack", "Steam"}
|
||||||
|
|
||||||
func isGothSupport(provider string) bool {
|
func isGothSupport(provider string) bool {
|
||||||
for _, value := range gothList {
|
for _, value := range gothList {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -21,6 +21,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
@ -98,6 +99,11 @@ func (idp *WeChatIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// {"errcode":40163,"errmsg":"code been used, rid: 6206378a-793424c0-2e4091cc"}
|
||||||
|
if strings.Contains(buf.String(), "errcode") {
|
||||||
|
return nil, fmt.Errorf(buf.String())
|
||||||
|
}
|
||||||
|
|
||||||
var wechatAccessToken WechatAccessToken
|
var wechatAccessToken WechatAccessToken
|
||||||
if err = json.Unmarshal(buf.Bytes(), &wechatAccessToken); err != nil {
|
if err = json.Unmarshal(buf.Bytes(), &wechatAccessToken); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
171
idp/wecom_internal.go
Normal file
171
idp/wecom_internal.go
Normal file
@ -0,0 +1,171 @@
|
|||||||
|
// Copyright 2021 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 idp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
//This idp is using wecom internal application api as idp
|
||||||
|
type WeComInternalIdProvider struct {
|
||||||
|
Client *http.Client
|
||||||
|
Config *oauth2.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWeComInternalIdProvider(clientId string, clientSecret string, redirectUrl string) *WeComInternalIdProvider {
|
||||||
|
idp := &WeComInternalIdProvider{}
|
||||||
|
|
||||||
|
config := idp.getConfig(clientId, clientSecret, redirectUrl)
|
||||||
|
idp.Config = config
|
||||||
|
|
||||||
|
return idp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *WeComInternalIdProvider) SetHttpClient(client *http.Client) {
|
||||||
|
idp.Client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *WeComInternalIdProvider) getConfig(clientId string, clientSecret string, redirectUrl string) *oauth2.Config {
|
||||||
|
var config = &oauth2.Config{
|
||||||
|
ClientID: clientId,
|
||||||
|
ClientSecret: clientSecret,
|
||||||
|
RedirectURL: redirectUrl,
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
type WecomInterToken struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetToken use code get access_token (*operation of getting code ought to be done in front)
|
||||||
|
// get more detail via: https://developer.work.weixin.qq.com/document/path/91039
|
||||||
|
func (idp *WeComInternalIdProvider) GetToken(code string) (*oauth2.Token, error) {
|
||||||
|
pTokenParams := &struct {
|
||||||
|
CorpId string `json:"corpid"`
|
||||||
|
Corpsecret string `json:"corpsecret"`
|
||||||
|
}{idp.Config.ClientID, idp.Config.ClientSecret}
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", pTokenParams.CorpId, pTokenParams.Corpsecret))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pToken := &WecomInterToken{}
|
||||||
|
err = json.Unmarshal(data, pToken)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pToken.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("pToken.Errcode = %d, pToken.Errmsg = %s", pToken.Errcode, pToken.Errmsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := &oauth2.Token{
|
||||||
|
AccessToken: pToken.AccessToken,
|
||||||
|
Expiry: time.Unix(time.Now().Unix()+int64(pToken.ExpiresIn), 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := make(map[string]interface{})
|
||||||
|
raw["code"] = code
|
||||||
|
token = token.WithExtra(raw)
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type WecomInternalUserResp struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
UserId string `json:"UserId"`
|
||||||
|
OpenId string `json:"OpenId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type WecomInternalUserInfo struct {
|
||||||
|
Errcode int `json:"errcode"`
|
||||||
|
Errmsg string `json:"errmsg"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Avatar string `json:"avatar"`
|
||||||
|
OpenId string `json:"open_userid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (idp *WeComInternalIdProvider) GetUserInfo(token *oauth2.Token) (*UserInfo, error) {
|
||||||
|
//Get userid first
|
||||||
|
accessToken := token.AccessToken
|
||||||
|
code := token.Extra("code").(string)
|
||||||
|
resp, err := idp.Client.Get(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s", accessToken, code))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
userResp := &WecomInternalUserResp{}
|
||||||
|
err = json.Unmarshal(data, userResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if userResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userIdResp.Errcode = %d, userIdResp.Errmsg = %s", userResp.Errcode, userResp.Errmsg)
|
||||||
|
}
|
||||||
|
if userResp.OpenId != "" {
|
||||||
|
return nil, fmt.Errorf("not an internal user")
|
||||||
|
}
|
||||||
|
//Use userid and accesstoken to get user information
|
||||||
|
resp, err = idp.Client.Get(fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s", accessToken, userResp.UserId))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err = io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
infoResp := &WecomInternalUserInfo{}
|
||||||
|
err = json.Unmarshal(data, infoResp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if infoResp.Errcode != 0 {
|
||||||
|
return nil, fmt.Errorf("userInfoResp.errcode = %d, userInfoResp.errmsg = %s", infoResp.Errcode, infoResp.Errmsg)
|
||||||
|
}
|
||||||
|
userInfo := UserInfo{
|
||||||
|
Id: infoResp.OpenId,
|
||||||
|
Username: infoResp.Name,
|
||||||
|
DisplayName: infoResp.Name,
|
||||||
|
Email: infoResp.Email,
|
||||||
|
AvatarUrl: infoResp.Avatar,
|
||||||
|
}
|
||||||
|
|
||||||
|
if userInfo.Id == "" {
|
||||||
|
userInfo.Id = userInfo.Username
|
||||||
|
}
|
||||||
|
|
||||||
|
return &userInfo, nil
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
56
k8s.yaml
Normal file
56
k8s.yaml
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
# this is only an EXAMPLE of deploying casddor in kubernetes
|
||||||
|
# please modify this file according to your requirements
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
#EDIT IT: if you don't want to run casdoor in default namespace, please modify this field
|
||||||
|
#namespace: casdoor
|
||||||
|
name: casdoor-svc
|
||||||
|
labels:
|
||||||
|
app: casdoor
|
||||||
|
spec:
|
||||||
|
#EDIT IT: if you don't want to run casdoor in default namespace, please modify this filed
|
||||||
|
type: NodePort
|
||||||
|
ports:
|
||||||
|
- port: 8000
|
||||||
|
selector:
|
||||||
|
app: casdoor
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
#EDIT IT: if you don't want to run casdoor in default namespace, please modify this field
|
||||||
|
#namespace: casdoor
|
||||||
|
name: casdoor-deployment
|
||||||
|
labels:
|
||||||
|
app: casdoor
|
||||||
|
spec:
|
||||||
|
#EDIT IT: if you don't use redis, casdoor should not have multiple replicas
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: casdoor
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: casdoor
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: casdoor-container
|
||||||
|
image: casbin/casdoor:latest
|
||||||
|
imagePullPolicy: Always
|
||||||
|
ports:
|
||||||
|
- containerPort: 8000
|
||||||
|
volumeMounts:
|
||||||
|
# the mounted directory path in THE CONTAINER
|
||||||
|
- mountPath: /conf
|
||||||
|
name: conf
|
||||||
|
env:
|
||||||
|
- name: RUNNING_IN_DOCKER
|
||||||
|
value: "true"
|
||||||
|
#if you want to deploy this in real prod env, consider the config map
|
||||||
|
volumes:
|
||||||
|
- name: conf
|
||||||
|
hostPath:
|
||||||
|
#EDIT IT: the mounted directory path in THE HOST
|
||||||
|
path: /conf
|
16
main.go
16
main.go
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -16,10 +16,10 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/astaxie/beego"
|
"github.com/astaxie/beego"
|
||||||
"github.com/astaxie/beego/logs"
|
"github.com/astaxie/beego/logs"
|
||||||
"github.com/astaxie/beego/plugins/cors"
|
|
||||||
_ "github.com/astaxie/beego/session/redis"
|
_ "github.com/astaxie/beego/session/redis"
|
||||||
"github.com/casdoor/casdoor/authz"
|
"github.com/casdoor/casdoor/authz"
|
||||||
"github.com/casdoor/casdoor/object"
|
"github.com/casdoor/casdoor/object"
|
||||||
@ -40,14 +40,6 @@ func main() {
|
|||||||
|
|
||||||
go object.RunSyncUsersJob()
|
go object.RunSyncUsersJob()
|
||||||
|
|
||||||
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
|
|
||||||
AllowOrigins: []string{"*"},
|
|
||||||
AllowMethods: []string{"GET", "PUT", "PATCH"},
|
|
||||||
AllowHeaders: []string{"Origin"},
|
|
||||||
ExposeHeaders: []string{"Content-Length"},
|
|
||||||
AllowCredentials: true,
|
|
||||||
}))
|
|
||||||
|
|
||||||
//beego.DelStaticPath("/static")
|
//beego.DelStaticPath("/static")
|
||||||
beego.SetStaticPath("/static", "web/build/static")
|
beego.SetStaticPath("/static", "web/build/static")
|
||||||
beego.BConfig.WebConfig.DirectoryIndex = true
|
beego.BConfig.WebConfig.DirectoryIndex = true
|
||||||
@ -74,8 +66,8 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
port := beego.AppConfig.DefaultInt("httpport", 8000)
|
||||||
//logs.SetLevel(logs.LevelInformational)
|
//logs.SetLevel(logs.LevelInformational)
|
||||||
logs.SetLogFuncCall(false)
|
logs.SetLogFuncCall(false)
|
||||||
|
beego.Run(fmt.Sprintf(":%v", port))
|
||||||
beego.Run()
|
|
||||||
}
|
}
|
||||||
|
23
manifests/casdoor/.helmignore
Normal file
23
manifests/casdoor/.helmignore
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
# Patterns to ignore when building packages.
|
||||||
|
# This supports shell glob matching, relative path matching, and
|
||||||
|
# negation (prefixed with !). Only one pattern per line.
|
||||||
|
.DS_Store
|
||||||
|
# Common VCS dirs
|
||||||
|
.git/
|
||||||
|
.gitignore
|
||||||
|
.bzr/
|
||||||
|
.bzrignore
|
||||||
|
.hg/
|
||||||
|
.hgignore
|
||||||
|
.svn/
|
||||||
|
# Common backup files
|
||||||
|
*.swp
|
||||||
|
*.bak
|
||||||
|
*.tmp
|
||||||
|
*.orig
|
||||||
|
*~
|
||||||
|
# Various IDEs
|
||||||
|
.project
|
||||||
|
.idea/
|
||||||
|
*.tmproj
|
||||||
|
.vscode/
|
24
manifests/casdoor/Chart.yaml
Normal file
24
manifests/casdoor/Chart.yaml
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
apiVersion: v2
|
||||||
|
name: casdoor
|
||||||
|
description: A Helm chart for Kubernetes
|
||||||
|
|
||||||
|
# A chart can be either an 'application' or a 'library' chart.
|
||||||
|
#
|
||||||
|
# Application charts are a collection of templates that can be packaged into versioned archives
|
||||||
|
# to be deployed.
|
||||||
|
#
|
||||||
|
# Library charts provide useful utilities or functions for the chart developer. They're included as
|
||||||
|
# a dependency of application charts to inject those utilities and functions into the rendering
|
||||||
|
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
|
||||||
|
type: application
|
||||||
|
|
||||||
|
# This is the chart version. This version number should be incremented each time you make changes
|
||||||
|
# to the chart and its templates, including the app version.
|
||||||
|
# Versions are expected to follow Semantic Versioning (https://semver.org/)
|
||||||
|
version: 0.1.0
|
||||||
|
|
||||||
|
# This is the version number of the application being deployed. This version number should be
|
||||||
|
# incremented each time you make changes to the application. Versions are not expected to
|
||||||
|
# follow Semantic Versioning. They should reflect the version the application is using.
|
||||||
|
# It is recommended to use it with quotes.
|
||||||
|
appVersion: "1.16.0"
|
22
manifests/casdoor/templates/NOTES.txt
Normal file
22
manifests/casdoor/templates/NOTES.txt
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
1. Get the application URL by running these commands:
|
||||||
|
{{- if .Values.ingress.enabled }}
|
||||||
|
{{- range $host := .Values.ingress.hosts }}
|
||||||
|
{{- range .paths }}
|
||||||
|
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- else if contains "NodePort" .Values.service.type }}
|
||||||
|
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "casdoor.fullname" . }})
|
||||||
|
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
|
||||||
|
echo http://$NODE_IP:$NODE_PORT
|
||||||
|
{{- else if contains "LoadBalancer" .Values.service.type }}
|
||||||
|
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
|
||||||
|
You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "casdoor.fullname" . }}'
|
||||||
|
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "casdoor.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
|
||||||
|
echo http://$SERVICE_IP:{{ .Values.service.port }}
|
||||||
|
{{- else if contains "ClusterIP" .Values.service.type }}
|
||||||
|
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "casdoor.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
|
||||||
|
export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
|
||||||
|
echo "Visit http://127.0.0.1:8080 to use your application"
|
||||||
|
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
|
||||||
|
{{- end }}
|
62
manifests/casdoor/templates/_helpers.tpl
Normal file
62
manifests/casdoor/templates/_helpers.tpl
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
{{/*
|
||||||
|
Expand the name of the chart.
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.name" -}}
|
||||||
|
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Create a default fully qualified app name.
|
||||||
|
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
|
||||||
|
If release name contains chart name it will be used as a full name.
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.fullname" -}}
|
||||||
|
{{- if .Values.fullnameOverride }}
|
||||||
|
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- else }}
|
||||||
|
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||||
|
{{- if contains $name .Release.Name }}
|
||||||
|
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- else }}
|
||||||
|
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Create chart name and version as used by the chart label.
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.chart" -}}
|
||||||
|
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Common labels
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.labels" -}}
|
||||||
|
helm.sh/chart: {{ include "casdoor.chart" . }}
|
||||||
|
{{ include "casdoor.selectorLabels" . }}
|
||||||
|
{{- if .Chart.AppVersion }}
|
||||||
|
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||||
|
{{- end }}
|
||||||
|
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Selector labels
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.selectorLabels" -}}
|
||||||
|
app.kubernetes.io/name: {{ include "casdoor.name" . }}
|
||||||
|
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{/*
|
||||||
|
Create the name of the service account to use
|
||||||
|
*/}}
|
||||||
|
{{- define "casdoor.serviceAccountName" -}}
|
||||||
|
{{- if .Values.serviceAccount.create }}
|
||||||
|
{{- default (include "casdoor.fullname" .) .Values.serviceAccount.name }}
|
||||||
|
{{- else }}
|
||||||
|
{{- default "default" .Values.serviceAccount.name }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
23
manifests/casdoor/templates/configmap.yaml
Normal file
23
manifests/casdoor/templates/configmap.yaml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: casdoor-config
|
||||||
|
data:
|
||||||
|
app.conf: |
|
||||||
|
appname = casdoor
|
||||||
|
httpport = 80
|
||||||
|
runmode = dev
|
||||||
|
SessionOn = true
|
||||||
|
copyrequestbody = true
|
||||||
|
driverName = mysql
|
||||||
|
dataSourceName = root:123456@tcp(localhost:3306)/
|
||||||
|
dbName = casdoor
|
||||||
|
redisEndpoint =
|
||||||
|
defaultStorageProvider =
|
||||||
|
isCloudIntranet = false
|
||||||
|
authState = "casdoor"
|
||||||
|
sock5Proxy = "127.0.0.1:10808"
|
||||||
|
verificationCodeTimeout = 10
|
||||||
|
initScore = 2000
|
||||||
|
logPostOnly = true
|
||||||
|
origin = "https://door.casbin.com"
|
75
manifests/casdoor/templates/deployment.yaml
Normal file
75
manifests/casdoor/templates/deployment.yaml
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: {{ include "casdoor.fullname" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
{{- if not .Values.autoscaling.enabled }}
|
||||||
|
replicas: {{ .Values.replicaCount }}
|
||||||
|
{{- end }}
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
{{- include "casdoor.selectorLabels" . | nindent 6 }}
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
{{- with .Values.podAnnotations }}
|
||||||
|
annotations:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.selectorLabels" . | nindent 8 }}
|
||||||
|
spec:
|
||||||
|
{{- with .Values.imagePullSecrets }}
|
||||||
|
imagePullSecrets:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
serviceAccountName: {{ include "casdoor.serviceAccountName" . }}
|
||||||
|
securityContext:
|
||||||
|
{{- toYaml .Values.podSecurityContext | nindent 8 }}
|
||||||
|
containers:
|
||||||
|
- name: {{ .Chart.Name }}
|
||||||
|
securityContext:
|
||||||
|
{{- toYaml .Values.securityContext | nindent 12 }}
|
||||||
|
image: "{{ .Values.image.repository }}/{{ .Values.image.name }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
|
||||||
|
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||||
|
# command: ["sleep", "100000000"]
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: 80
|
||||||
|
protocol: TCP
|
||||||
|
# livenessProbe:
|
||||||
|
# httpGet:
|
||||||
|
# path: /
|
||||||
|
# port: http
|
||||||
|
# readinessProbe:
|
||||||
|
# httpGet:
|
||||||
|
# path: /
|
||||||
|
# port: http
|
||||||
|
resources:
|
||||||
|
{{- toYaml .Values.resources | nindent 12 }}
|
||||||
|
volumeMounts:
|
||||||
|
- name: config-volume
|
||||||
|
mountPath: /conf
|
||||||
|
volumes:
|
||||||
|
- name: config-volume
|
||||||
|
projected:
|
||||||
|
defaultMode: 420
|
||||||
|
sources:
|
||||||
|
- configMap:
|
||||||
|
items:
|
||||||
|
- key: app.conf
|
||||||
|
path: app.conf
|
||||||
|
name: casdoor-config
|
||||||
|
{{- with .Values.nodeSelector }}
|
||||||
|
nodeSelector:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.affinity }}
|
||||||
|
affinity:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- with .Values.tolerations }}
|
||||||
|
tolerations:
|
||||||
|
{{- toYaml . | nindent 8 }}
|
||||||
|
{{- end }}
|
28
manifests/casdoor/templates/hpa.yaml
Normal file
28
manifests/casdoor/templates/hpa.yaml
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
{{- if .Values.autoscaling.enabled }}
|
||||||
|
apiVersion: autoscaling/v2beta1
|
||||||
|
kind: HorizontalPodAutoscaler
|
||||||
|
metadata:
|
||||||
|
name: {{ include "casdoor.fullname" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
scaleTargetRef:
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
name: {{ include "casdoor.fullname" . }}
|
||||||
|
minReplicas: {{ .Values.autoscaling.minReplicas }}
|
||||||
|
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
|
||||||
|
metrics:
|
||||||
|
{{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: cpu
|
||||||
|
targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
- type: Resource
|
||||||
|
resource:
|
||||||
|
name: memory
|
||||||
|
targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
61
manifests/casdoor/templates/ingress.yaml
Normal file
61
manifests/casdoor/templates/ingress.yaml
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
{{- if .Values.ingress.enabled -}}
|
||||||
|
{{- $fullName := include "casdoor.fullname" . -}}
|
||||||
|
{{- $svcPort := .Values.service.port -}}
|
||||||
|
{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }}
|
||||||
|
{{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }}
|
||||||
|
{{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}}
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
|
||||||
|
apiVersion: networking.k8s.io/v1beta1
|
||||||
|
{{- else -}}
|
||||||
|
apiVersion: extensions/v1beta1
|
||||||
|
{{- end }}
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: {{ $fullName }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
{{- with .Values.ingress.annotations }}
|
||||||
|
annotations:
|
||||||
|
{{- toYaml . | nindent 4 }}
|
||||||
|
{{- end }}
|
||||||
|
spec:
|
||||||
|
{{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }}
|
||||||
|
ingressClassName: {{ .Values.ingress.className }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.ingress.tls }}
|
||||||
|
tls:
|
||||||
|
{{- range .Values.ingress.tls }}
|
||||||
|
- hosts:
|
||||||
|
{{- range .hosts }}
|
||||||
|
- {{ . | quote }}
|
||||||
|
{{- end }}
|
||||||
|
secretName: {{ .secretName }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
rules:
|
||||||
|
{{- range .Values.ingress.hosts }}
|
||||||
|
- host: {{ .host | quote }}
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
{{- range .paths }}
|
||||||
|
- path: {{ .path }}
|
||||||
|
{{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }}
|
||||||
|
pathType: {{ .pathType }}
|
||||||
|
{{- end }}
|
||||||
|
backend:
|
||||||
|
{{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }}
|
||||||
|
service:
|
||||||
|
name: {{ $fullName }}
|
||||||
|
port:
|
||||||
|
number: {{ $svcPort }}
|
||||||
|
{{- else }}
|
||||||
|
serviceName: {{ $fullName }}
|
||||||
|
servicePort: {{ $svcPort }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
15
manifests/casdoor/templates/service.yaml
Normal file
15
manifests/casdoor/templates/service.yaml
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: {{ include "casdoor.fullname" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
spec:
|
||||||
|
type: {{ .Values.service.type }}
|
||||||
|
ports:
|
||||||
|
- port: {{ .Values.service.port }}
|
||||||
|
targetPort: http
|
||||||
|
protocol: TCP
|
||||||
|
name: http
|
||||||
|
selector:
|
||||||
|
{{- include "casdoor.selectorLabels" . | nindent 4 }}
|
12
manifests/casdoor/templates/serviceaccount.yaml
Normal file
12
manifests/casdoor/templates/serviceaccount.yaml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
{{- if .Values.serviceAccount.create -}}
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
|
metadata:
|
||||||
|
name: {{ include "casdoor.serviceAccountName" . }}
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
{{- with .Values.serviceAccount.annotations }}
|
||||||
|
annotations:
|
||||||
|
{{- toYaml . | nindent 4 }}
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
15
manifests/casdoor/templates/tests/test-connection.yaml
Normal file
15
manifests/casdoor/templates/tests/test-connection.yaml
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Pod
|
||||||
|
metadata:
|
||||||
|
name: "{{ include "casdoor.fullname" . }}-test-connection"
|
||||||
|
labels:
|
||||||
|
{{- include "casdoor.labels" . | nindent 4 }}
|
||||||
|
annotations:
|
||||||
|
"helm.sh/hook": test
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: wget
|
||||||
|
image: busybox
|
||||||
|
command: ['wget']
|
||||||
|
args: ['{{ include "casdoor.fullname" . }}:{{ .Values.service.port }}']
|
||||||
|
restartPolicy: Never
|
83
manifests/casdoor/values.yaml
Normal file
83
manifests/casdoor/values.yaml
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
# Default values for casdoor.
|
||||||
|
# This is a YAML-formatted file.
|
||||||
|
# Declare variables to be passed into your templates.
|
||||||
|
|
||||||
|
replicaCount: 1
|
||||||
|
|
||||||
|
image:
|
||||||
|
repository: casbin
|
||||||
|
name: casdoor-all-in-one
|
||||||
|
pullPolicy: IfNotPresent
|
||||||
|
# Overrides the image tag whose default is the chart appVersion.
|
||||||
|
tag: ""
|
||||||
|
|
||||||
|
imagePullSecrets: []
|
||||||
|
nameOverride: ""
|
||||||
|
fullnameOverride: ""
|
||||||
|
|
||||||
|
serviceAccount:
|
||||||
|
# Specifies whether a service account should be created
|
||||||
|
create: true
|
||||||
|
# Annotations to add to the service account
|
||||||
|
annotations: {}
|
||||||
|
# The name of the service account to use.
|
||||||
|
# If not set and create is true, a name is generated using the fullname template
|
||||||
|
name: ""
|
||||||
|
|
||||||
|
podAnnotations: {}
|
||||||
|
|
||||||
|
podSecurityContext: {}
|
||||||
|
# fsGroup: 2000
|
||||||
|
|
||||||
|
securityContext: {}
|
||||||
|
# capabilities:
|
||||||
|
# drop:
|
||||||
|
# - ALL
|
||||||
|
# readOnlyRootFilesystem: true
|
||||||
|
# runAsNonRoot: true
|
||||||
|
# runAsUser: 1000
|
||||||
|
|
||||||
|
service:
|
||||||
|
type: ClusterIP
|
||||||
|
port: 80
|
||||||
|
|
||||||
|
ingress:
|
||||||
|
enabled: false
|
||||||
|
className: ""
|
||||||
|
annotations: {}
|
||||||
|
# kubernetes.io/ingress.class: nginx
|
||||||
|
# kubernetes.io/tls-acme: "true"
|
||||||
|
hosts:
|
||||||
|
- host: chart-example.local
|
||||||
|
paths:
|
||||||
|
- path: /
|
||||||
|
pathType: ImplementationSpecific
|
||||||
|
tls: []
|
||||||
|
# - secretName: chart-example-tls
|
||||||
|
# hosts:
|
||||||
|
# - chart-example.local
|
||||||
|
|
||||||
|
resources: {}
|
||||||
|
# We usually recommend not to specify default resources and to leave this as a conscious
|
||||||
|
# choice for the user. This also increases chances charts run on environments with little
|
||||||
|
# resources, such as Minikube. If you do want to specify resources, uncomment the following
|
||||||
|
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
|
||||||
|
# limits:
|
||||||
|
# cpu: 100m
|
||||||
|
# memory: 128Mi
|
||||||
|
# requests:
|
||||||
|
# cpu: 100m
|
||||||
|
# memory: 128Mi
|
||||||
|
|
||||||
|
autoscaling:
|
||||||
|
enabled: false
|
||||||
|
minReplicas: 1
|
||||||
|
maxReplicas: 100
|
||||||
|
targetCPUUtilizationPercentage: 80
|
||||||
|
# targetMemoryUtilizationPercentage: 80
|
||||||
|
|
||||||
|
nodeSelector: {}
|
||||||
|
|
||||||
|
tolerations: []
|
||||||
|
|
||||||
|
affinity: {}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -17,7 +17,6 @@ package object
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"runtime"
|
"runtime"
|
||||||
"xorm.io/core"
|
|
||||||
|
|
||||||
"github.com/astaxie/beego"
|
"github.com/astaxie/beego"
|
||||||
"github.com/casdoor/casdoor/conf"
|
"github.com/casdoor/casdoor/conf"
|
||||||
@ -25,6 +24,7 @@ import (
|
|||||||
//_ "github.com/denisenkom/go-mssqldb" // db = mssql
|
//_ "github.com/denisenkom/go-mssqldb" // db = mssql
|
||||||
_ "github.com/go-sql-driver/mysql" // db = mysql
|
_ "github.com/go-sql-driver/mysql" // db = mysql
|
||||||
//_ "github.com/lib/pq" // db = postgres
|
//_ "github.com/lib/pq" // db = postgres
|
||||||
|
"xorm.io/core"
|
||||||
"xorm.io/xorm"
|
"xorm.io/xorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -87,7 +87,7 @@ func (a *Adapter) CreateDatabase() error {
|
|||||||
}
|
}
|
||||||
defer engine.Close()
|
defer engine.Close()
|
||||||
|
|
||||||
_, err = engine.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8 COLLATE utf8_general_ci", a.dbName))
|
_, err = engine.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8mb4 COLLATE utf8mb4_general_ci", a.dbName))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -183,6 +183,16 @@ func (a *Adapter) createTable() {
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err = a.Engine.Sync2(new(Product))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = a.Engine.Sync2(new(Payment))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
err = a.Engine.Sync2(new(Ldap))
|
err = a.Engine.Sync2(new(Ldap))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
@ -190,13 +200,18 @@ func (a *Adapter) createTable() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetSession(owner string, offset, limit int, field, value, sortField, sortOrder string) *xorm.Session {
|
func GetSession(owner string, offset, limit int, field, value, sortField, sortOrder string) *xorm.Session {
|
||||||
session := adapter.Engine.Limit(limit, offset).Where("1=1")
|
session := adapter.Engine.Prepare()
|
||||||
|
if offset != -1 && limit != -1 {
|
||||||
|
session.Limit(limit, offset)
|
||||||
|
}
|
||||||
if owner != "" {
|
if owner != "" {
|
||||||
session = session.And("owner=?", owner)
|
session = session.And("owner=?", owner)
|
||||||
}
|
}
|
||||||
if field != "" && value != "" {
|
if field != "" && value != "" {
|
||||||
|
if filterField(field) {
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if sortField == "" || sortOrder == "" {
|
if sortField == "" || sortOrder == "" {
|
||||||
sortField = "created_time"
|
sortField = "created_time"
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -16,6 +16,7 @@ package object
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/casdoor/casdoor/util"
|
"github.com/casdoor/casdoor/util"
|
||||||
"xorm.io/core"
|
"xorm.io/core"
|
||||||
@ -38,6 +39,7 @@ type Application struct {
|
|||||||
EnableCodeSignin bool `json:"enableCodeSignin"`
|
EnableCodeSignin bool `json:"enableCodeSignin"`
|
||||||
Providers []*ProviderItem `xorm:"mediumtext" json:"providers"`
|
Providers []*ProviderItem `xorm:"mediumtext" json:"providers"`
|
||||||
SignupItems []*SignupItem `xorm:"varchar(1000)" json:"signupItems"`
|
SignupItems []*SignupItem `xorm:"varchar(1000)" json:"signupItems"`
|
||||||
|
GrantTypes []string `xorm:"varchar(1000)" json:"grantTypes"`
|
||||||
OrganizationObj *Organization `xorm:"-" json:"organizationObj"`
|
OrganizationObj *Organization `xorm:"-" json:"organizationObj"`
|
||||||
|
|
||||||
ClientId string `xorm:"varchar(100)" json:"clientId"`
|
ClientId string `xorm:"varchar(100)" json:"clientId"`
|
||||||
@ -56,10 +58,7 @@ type Application struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetApplicationCount(owner, field, value string) int {
|
func GetApplicationCount(owner, field, value string) int {
|
||||||
session := adapter.Engine.Where("owner=?", owner)
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Application{})
|
count, err := session.Count(&Application{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
@ -218,6 +217,18 @@ func GetMaskedApplication(application *Application, userId string) *Application
|
|||||||
if application.ClientSecret != "" {
|
if application.ClientSecret != "" {
|
||||||
application.ClientSecret = "***"
|
application.ClientSecret = "***"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if application.OrganizationObj != nil {
|
||||||
|
if application.OrganizationObj.MasterPassword != "" {
|
||||||
|
application.OrganizationObj.MasterPassword = "***"
|
||||||
|
}
|
||||||
|
if application.OrganizationObj.PasswordType != "" {
|
||||||
|
application.OrganizationObj.PasswordType = "***"
|
||||||
|
}
|
||||||
|
if application.OrganizationObj.PasswordSalt != "" {
|
||||||
|
application.OrganizationObj.PasswordSalt = "***"
|
||||||
|
}
|
||||||
|
}
|
||||||
return application
|
return application
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -285,3 +296,15 @@ func DeleteApplication(application *Application) bool {
|
|||||||
func (application *Application) GetId() string {
|
func (application *Application) GetId() string {
|
||||||
return fmt.Sprintf("%s/%s", application.Owner, application.Name)
|
return fmt.Sprintf("%s/%s", application.Owner, application.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func CheckRedirectUriValid(application *Application, redirectUri string) bool {
|
||||||
|
var validUri = false
|
||||||
|
for _, tmpUri := range application.RedirectUris {
|
||||||
|
fmt.Println(tmpUri, redirectUri)
|
||||||
|
if strings.Contains(redirectUri, tmpUri) {
|
||||||
|
validUri = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return validUri
|
||||||
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -35,6 +35,8 @@ type Cert struct {
|
|||||||
|
|
||||||
PublicKey string `xorm:"mediumtext" json:"publicKey"`
|
PublicKey string `xorm:"mediumtext" json:"publicKey"`
|
||||||
PrivateKey string `xorm:"mediumtext" json:"privateKey"`
|
PrivateKey string `xorm:"mediumtext" json:"privateKey"`
|
||||||
|
AuthorityPublicKey string `xorm:"mediumtext" json:"authorityPublicKey"`
|
||||||
|
AuthorityRootPublicKey string `xorm:"mediumtext" json:"authorityRootPublicKey"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetMaskedCert(cert *Cert) *Cert {
|
func GetMaskedCert(cert *Cert) *Cert {
|
||||||
@ -53,10 +55,7 @@ func GetMaskedCerts(certs []*Cert) []*Cert {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetCertCount(owner, field, value string) int {
|
func GetCertCount(owner, field, value string) int {
|
||||||
session := adapter.Engine.Where("owner=?", owner)
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Cert{})
|
count, err := session.Count(&Cert{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -23,13 +23,17 @@ import (
|
|||||||
goldap "github.com/go-ldap/ldap/v3"
|
goldap "github.com/go-ldap/ldap/v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
var reWhiteSpace *regexp.Regexp
|
var (
|
||||||
|
reWhiteSpace *regexp.Regexp
|
||||||
|
reFieldWhiteList *regexp.Regexp
|
||||||
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
reWhiteSpace, _ = regexp.Compile(`\s`)
|
reWhiteSpace, _ = regexp.Compile(`\s`)
|
||||||
|
reFieldWhiteList, _ = regexp.Compile(`^[A-Za-z0-9]+$`)
|
||||||
}
|
}
|
||||||
|
|
||||||
func CheckUserSignup(application *Application, organization *Organization, username string, password string, displayName string, email string, phone string, affiliation string) string {
|
func CheckUserSignup(application *Application, organization *Organization, username string, password string, displayName string, firstName string, lastName string, email string, phone string, affiliation string) string {
|
||||||
if organization == nil {
|
if organization == nil {
|
||||||
return "organization does not exist"
|
return "organization does not exist"
|
||||||
}
|
}
|
||||||
@ -81,11 +85,19 @@ func CheckUserSignup(application *Application, organization *Organization, usern
|
|||||||
}
|
}
|
||||||
|
|
||||||
if application.IsSignupItemVisible("Display name") {
|
if application.IsSignupItemVisible("Display name") {
|
||||||
|
if application.GetSignupItemRule("Display name") == "First, last" && (firstName != "" || lastName != "") {
|
||||||
|
if firstName == "" {
|
||||||
|
return "firstName cannot be blank"
|
||||||
|
} else if lastName == "" {
|
||||||
|
return "lastName cannot be blank"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if displayName == "" {
|
if displayName == "" {
|
||||||
return "displayName cannot be blank"
|
return "displayName cannot be blank"
|
||||||
} else if application.GetSignupItemRule("Display name") == "Personal" {
|
} else if application.GetSignupItemRule("Display name") == "Real name" {
|
||||||
if !isValidPersonalName(displayName) {
|
if !isValidRealName(displayName) {
|
||||||
return "displayName is not valid personal name"
|
return "displayName is not valid real name"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -167,15 +179,20 @@ func CheckUserPassword(organization string, username string, password string) (*
|
|||||||
if user.IsForbidden {
|
if user.IsForbidden {
|
||||||
return nil, "the user is forbidden to sign in, please contact the administrator"
|
return nil, "the user is forbidden to sign in, please contact the administrator"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
msg := CheckPassword(user, password)
|
||||||
|
if msg != "" {
|
||||||
//for ldap users
|
//for ldap users
|
||||||
if user.Ldap != "" {
|
if user.Ldap != "" {
|
||||||
return checkLdapUserPassword(user, password)
|
return checkLdapUserPassword(user, password)
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := CheckPassword(user, password)
|
|
||||||
if msg != "" {
|
|
||||||
return nil, msg
|
return nil, msg
|
||||||
}
|
}
|
||||||
|
|
||||||
return user, ""
|
return user, ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func filterField(field string) bool {
|
||||||
|
return reFieldWhiteList.MatchString(field)
|
||||||
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -16,16 +16,16 @@ package object
|
|||||||
|
|
||||||
import "regexp"
|
import "regexp"
|
||||||
|
|
||||||
var rePersonalName *regexp.Regexp
|
var reRealName *regexp.Regexp
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
var err error
|
var err error
|
||||||
rePersonalName, err = regexp.Compile("^[\u4E00-\u9FA5]{2,3}(?:·[\u4E00-\u9FA5]{2,3})*$")
|
reRealName, err = regexp.Compile("^[\u4E00-\u9FA5]{2,3}(?:·[\u4E00-\u9FA5]{2,3})*$")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isValidPersonalName(s string) bool {
|
func isValidRealName(s string) bool {
|
||||||
return rePersonalName.MatchString(s)
|
return reRealName.MatchString(s)
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -47,9 +47,10 @@ func initBuiltInOrganization() {
|
|||||||
DisplayName: "Built-in Organization",
|
DisplayName: "Built-in Organization",
|
||||||
WebsiteUrl: "https://example.com",
|
WebsiteUrl: "https://example.com",
|
||||||
Favicon: "https://cdn.casbin.com/static/favicon.ico",
|
Favicon: "https://cdn.casbin.com/static/favicon.ico",
|
||||||
|
PasswordType: "plain",
|
||||||
PhonePrefix: "86",
|
PhonePrefix: "86",
|
||||||
DefaultAvatar: "https://casbin.org/img/casbin.svg",
|
DefaultAvatar: "https://casbin.org/img/casbin.svg",
|
||||||
PasswordType: "plain",
|
Tags: []string{},
|
||||||
}
|
}
|
||||||
AddOrganization(organization)
|
AddOrganization(organization)
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -162,7 +162,7 @@ func (l *ldapConn) GetLdapUsers(baseDn string) ([]ldapUser, error) {
|
|||||||
searchReq := goldap.NewSearchRequest(baseDn,
|
searchReq := goldap.NewSearchRequest(baseDn,
|
||||||
goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false,
|
goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false,
|
||||||
SearchFilter, SearchAttributes, nil)
|
SearchFilter, SearchAttributes, nil)
|
||||||
searchResult, err := l.Conn.Search(searchReq)
|
searchResult, err := l.Conn.SearchWithPaging(searchReq, 100)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -65,6 +65,13 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) {
|
|||||||
ticker := time.NewTicker(time.Duration(ldap.AutoSync) * time.Minute)
|
ticker := time.NewTicker(time.Duration(ldap.AutoSync) * time.Minute)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
for {
|
for {
|
||||||
|
select {
|
||||||
|
case <-stopChan:
|
||||||
|
logs.Info(fmt.Sprintf("autoSync goroutine for %s stopped", ldap.Id))
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
|
||||||
UpdateLdapSyncTime(ldap.Id)
|
UpdateLdapSyncTime(ldap.Id)
|
||||||
//fetch all users
|
//fetch all users
|
||||||
conn, err := GetLdapConn(ldap.Host, ldap.Port, ldap.Admin, ldap.Passwd)
|
conn, err := GetLdapConn(ldap.Host, ldap.Port, ldap.Admin, ldap.Passwd)
|
||||||
@ -84,12 +91,6 @@ func (l *LdapAutoSynchronizer) syncRoutine(ldap *Ldap, stopChan chan struct{}) {
|
|||||||
} else {
|
} else {
|
||||||
logs.Info(fmt.Sprintf("ldap autosync success, %d new users, %d existing users", len(users)-len(*existed), len(*existed)))
|
logs.Info(fmt.Sprintf("ldap autosync success, %d new users, %d existing users", len(users)-len(*existed), len(*existed)))
|
||||||
}
|
}
|
||||||
select {
|
|
||||||
case <-stopChan:
|
|
||||||
logs.Info(fmt.Sprintf("autoSync goroutine for %s stopped", ldap.Id))
|
|
||||||
return
|
|
||||||
case <-ticker.C:
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -18,6 +18,7 @@ import (
|
|||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/astaxie/beego"
|
"github.com/astaxie/beego"
|
||||||
"gopkg.in/square/go-jose.v2"
|
"gopkg.in/square/go-jose.v2"
|
||||||
@ -29,6 +30,7 @@ type OidcDiscovery struct {
|
|||||||
TokenEndpoint string `json:"token_endpoint"`
|
TokenEndpoint string `json:"token_endpoint"`
|
||||||
UserinfoEndpoint string `json:"userinfo_endpoint"`
|
UserinfoEndpoint string `json:"userinfo_endpoint"`
|
||||||
JwksUri string `json:"jwks_uri"`
|
JwksUri string `json:"jwks_uri"`
|
||||||
|
IntrospectionEndpoint string `json:"introspection_endpoint"`
|
||||||
ResponseTypesSupported []string `json:"response_types_supported"`
|
ResponseTypesSupported []string `json:"response_types_supported"`
|
||||||
ResponseModesSupported []string `json:"response_modes_supported"`
|
ResponseModesSupported []string `json:"response_modes_supported"`
|
||||||
GrantTypesSupported []string `json:"grant_types_supported"`
|
GrantTypesSupported []string `json:"grant_types_supported"`
|
||||||
@ -40,22 +42,40 @@ type OidcDiscovery struct {
|
|||||||
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
|
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var oidcDiscovery OidcDiscovery
|
func getOriginFromHost(host string) (string, string) {
|
||||||
|
protocol := "https://"
|
||||||
|
if strings.HasPrefix(host, "localhost") {
|
||||||
|
protocol = "http://"
|
||||||
|
}
|
||||||
|
|
||||||
|
if host == "localhost:8000" {
|
||||||
|
return fmt.Sprintf("%s%s", protocol, "localhost:7001"), fmt.Sprintf("%s%s", protocol, "localhost:8000")
|
||||||
|
} else {
|
||||||
|
return fmt.Sprintf("%s%s", protocol, host), fmt.Sprintf("%s%s", protocol, host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetOidcDiscovery(host string) OidcDiscovery {
|
||||||
|
originFrontend, originBackend := getOriginFromHost(host)
|
||||||
|
|
||||||
func init() {
|
|
||||||
origin := beego.AppConfig.String("origin")
|
origin := beego.AppConfig.String("origin")
|
||||||
|
if origin != "" {
|
||||||
|
originFrontend = origin
|
||||||
|
originBackend = origin
|
||||||
|
}
|
||||||
|
|
||||||
// Examples:
|
// Examples:
|
||||||
// https://login.okta.com/.well-known/openid-configuration
|
// https://login.okta.com/.well-known/openid-configuration
|
||||||
// https://auth0.auth0.com/.well-known/openid-configuration
|
// https://auth0.auth0.com/.well-known/openid-configuration
|
||||||
// https://accounts.google.com/.well-known/openid-configuration
|
// https://accounts.google.com/.well-known/openid-configuration
|
||||||
// https://access.line.me/.well-known/openid-configuration
|
// https://access.line.me/.well-known/openid-configuration
|
||||||
oidcDiscovery = OidcDiscovery{
|
oidcDiscovery := OidcDiscovery{
|
||||||
Issuer: origin,
|
Issuer: originBackend,
|
||||||
AuthorizationEndpoint: fmt.Sprintf("%s/login/oauth/authorize", origin),
|
AuthorizationEndpoint: fmt.Sprintf("%s/login/oauth/authorize", originFrontend),
|
||||||
TokenEndpoint: fmt.Sprintf("%s/api/login/oauth/access_token", origin),
|
TokenEndpoint: fmt.Sprintf("%s/api/login/oauth/access_token", originBackend),
|
||||||
UserinfoEndpoint: fmt.Sprintf("%s/api/get-account", origin),
|
UserinfoEndpoint: fmt.Sprintf("%s/api/userinfo", originBackend),
|
||||||
JwksUri: fmt.Sprintf("%s/api/certs", origin),
|
JwksUri: fmt.Sprintf("%s/.well-known/jwks", originBackend),
|
||||||
|
IntrospectionEndpoint: fmt.Sprintf("%s/api/login/oauth/introspect", originBackend),
|
||||||
ResponseTypesSupported: []string{"id_token"},
|
ResponseTypesSupported: []string{"id_token"},
|
||||||
ResponseModesSupported: []string{"login", "code", "link"},
|
ResponseModesSupported: []string{"login", "code", "link"},
|
||||||
GrantTypesSupported: []string{"password", "authorization_code"},
|
GrantTypesSupported: []string{"password", "authorization_code"},
|
||||||
@ -66,18 +86,17 @@ func init() {
|
|||||||
RequestParameterSupported: true,
|
RequestParameterSupported: true,
|
||||||
RequestObjectSigningAlgValuesSupported: []string{"HS256", "HS384", "HS512"},
|
RequestObjectSigningAlgValuesSupported: []string{"HS256", "HS384", "HS512"},
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
func GetOidcDiscovery() OidcDiscovery {
|
|
||||||
return oidcDiscovery
|
return oidcDiscovery
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetJsonWebKeySet() (jose.JSONWebKeySet, error) {
|
func GetJsonWebKeySet() (jose.JSONWebKeySet, error) {
|
||||||
cert := GetDefaultCert()
|
certs := GetCerts("admin")
|
||||||
|
jwks := jose.JSONWebKeySet{}
|
||||||
//follows the protocol rfc 7517(draft)
|
//follows the protocol rfc 7517(draft)
|
||||||
//link here: https://self-issued.info/docs/draft-ietf-jose-json-web-key.html
|
//link here: https://self-issued.info/docs/draft-ietf-jose-json-web-key.html
|
||||||
//or https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key
|
//or https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key
|
||||||
|
for _, cert := range certs {
|
||||||
certPemBlock := []byte(cert.PublicKey)
|
certPemBlock := []byte(cert.PublicKey)
|
||||||
certDerBlock, _ := pem.Decode(certPemBlock)
|
certDerBlock, _ := pem.Decode(certPemBlock)
|
||||||
x509Cert, _ := x509.ParseCertificate(certDerBlock.Bytes)
|
x509Cert, _ := x509.ParseCertificate(certDerBlock.Bytes)
|
||||||
@ -86,8 +105,8 @@ func GetJsonWebKeySet() (jose.JSONWebKeySet, error) {
|
|||||||
jwk.Key = x509Cert.PublicKey
|
jwk.Key = x509Cert.PublicKey
|
||||||
jwk.Certificates = []*x509.Certificate{x509Cert}
|
jwk.Certificates = []*x509.Certificate{x509Cert}
|
||||||
jwk.KeyID = cert.Name
|
jwk.KeyID = cert.Name
|
||||||
|
jwks.Keys = append(jwks.Keys, jwk)
|
||||||
|
}
|
||||||
|
|
||||||
var jwks jose.JSONWebKeySet
|
|
||||||
jwks.Keys = []jose.JSONWebKey{jwk}
|
|
||||||
return jwks, nil
|
return jwks, nil
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -15,8 +15,6 @@
|
|||||||
package object
|
package object
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/casdoor/casdoor/cred"
|
"github.com/casdoor/casdoor/cred"
|
||||||
"github.com/casdoor/casdoor/util"
|
"github.com/casdoor/casdoor/util"
|
||||||
"xorm.io/core"
|
"xorm.io/core"
|
||||||
@ -34,15 +32,13 @@ type Organization struct {
|
|||||||
PasswordSalt string `xorm:"varchar(100)" json:"passwordSalt"`
|
PasswordSalt string `xorm:"varchar(100)" json:"passwordSalt"`
|
||||||
PhonePrefix string `xorm:"varchar(10)" json:"phonePrefix"`
|
PhonePrefix string `xorm:"varchar(10)" json:"phonePrefix"`
|
||||||
DefaultAvatar string `xorm:"varchar(100)" json:"defaultAvatar"`
|
DefaultAvatar string `xorm:"varchar(100)" json:"defaultAvatar"`
|
||||||
|
Tags []string `xorm:"mediumtext" json:"tags"`
|
||||||
MasterPassword string `xorm:"varchar(100)" json:"masterPassword"`
|
MasterPassword string `xorm:"varchar(100)" json:"masterPassword"`
|
||||||
EnableSoftDeletion bool `json:"enableSoftDeletion"`
|
EnableSoftDeletion bool `json:"enableSoftDeletion"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetOrganizationCount(owner, field, value string) int {
|
func GetOrganizationCount(owner, field, value string) int {
|
||||||
session := adapter.Engine.Where("owner=?", owner)
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Organization{})
|
count, err := session.Count(&Organization{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
|
202
object/payment.go
Normal file
202
object/payment.go
Normal file
@ -0,0 +1,202 @@
|
|||||||
|
// Copyright 2022 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"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/casdoor/casdoor/util"
|
||||||
|
"xorm.io/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Payment 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"`
|
||||||
|
DisplayName string `xorm:"varchar(100)" json:"displayName"`
|
||||||
|
|
||||||
|
Provider string `xorm:"varchar(100)" json:"provider"`
|
||||||
|
Type string `xorm:"varchar(100)" json:"type"`
|
||||||
|
Organization string `xorm:"varchar(100)" json:"organization"`
|
||||||
|
User string `xorm:"varchar(100)" json:"user"`
|
||||||
|
ProductName string `xorm:"varchar(100)" json:"productName"`
|
||||||
|
ProductDisplayName string `xorm:"varchar(100)" json:"productDisplayName"`
|
||||||
|
|
||||||
|
Detail string `xorm:"varchar(100)" json:"detail"`
|
||||||
|
Tag string `xorm:"varchar(100)" json:"tag"`
|
||||||
|
Currency string `xorm:"varchar(100)" json:"currency"`
|
||||||
|
Price float64 `json:"price"`
|
||||||
|
|
||||||
|
PayUrl string `xorm:"varchar(2000)" json:"payUrl"`
|
||||||
|
ReturnUrl string `xorm:"varchar(1000)" json:"returnUrl"`
|
||||||
|
State string `xorm:"varchar(100)" json:"state"`
|
||||||
|
Message string `xorm:"varchar(1000)" json:"message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPaymentCount(owner, field, value string) int {
|
||||||
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
|
count, err := session.Count(&Payment{})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return int(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPayments(owner string) []*Payment {
|
||||||
|
payments := []*Payment{}
|
||||||
|
err := adapter.Engine.Desc("created_time").Find(&payments, &Payment{Owner: owner})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return payments
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetUserPayments(owner string, organization string, user string) []*Payment {
|
||||||
|
payments := []*Payment{}
|
||||||
|
err := adapter.Engine.Desc("created_time").Find(&payments, &Payment{Owner: owner, Organization: organization, User: user})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return payments
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPaginationPayments(owner string, offset, limit int, field, value, sortField, sortOrder string) []*Payment {
|
||||||
|
payments := []*Payment{}
|
||||||
|
session := GetSession(owner, offset, limit, field, value, sortField, sortOrder)
|
||||||
|
err := session.Find(&payments)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return payments
|
||||||
|
}
|
||||||
|
|
||||||
|
func getPayment(owner string, name string) *Payment {
|
||||||
|
if owner == "" || name == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
payment := Payment{Owner: owner, Name: name}
|
||||||
|
existed, err := adapter.Engine.Get(&payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if existed {
|
||||||
|
return &payment
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPayment(id string) *Payment {
|
||||||
|
owner, name := util.GetOwnerAndNameFromId(id)
|
||||||
|
return getPayment(owner, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdatePayment(id string, payment *Payment) bool {
|
||||||
|
owner, name := util.GetOwnerAndNameFromId(id)
|
||||||
|
if getPayment(owner, name) == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
affected, err := adapter.Engine.ID(core.PK{owner, name}).AllCols().Update(payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddPayment(payment *Payment) bool {
|
||||||
|
affected, err := adapter.Engine.Insert(payment)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeletePayment(payment *Payment) bool {
|
||||||
|
affected, err := adapter.Engine.ID(core.PK{payment.Owner, payment.Name}).Delete(&Payment{})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyPayment(request *http.Request, body []byte, owner string, providerName string, productName string, paymentName string) (*Payment, error) {
|
||||||
|
payment := getPayment(owner, paymentName)
|
||||||
|
if payment == nil {
|
||||||
|
return nil, fmt.Errorf("the payment: %s does not exist", paymentName)
|
||||||
|
}
|
||||||
|
|
||||||
|
product := getProduct(owner, productName)
|
||||||
|
if product == nil {
|
||||||
|
return nil, fmt.Errorf("the product: %s does not exist", productName)
|
||||||
|
}
|
||||||
|
|
||||||
|
provider, err := product.getProvider(providerName)
|
||||||
|
if err != nil {
|
||||||
|
return payment, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pProvider, cert, err := provider.getPaymentProvider()
|
||||||
|
if err != nil {
|
||||||
|
return payment, err
|
||||||
|
}
|
||||||
|
|
||||||
|
productDisplayName, paymentName, price, productName, providerName, err := pProvider.Notify(request, body, cert.AuthorityPublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return payment, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if productDisplayName != "" && productDisplayName != product.DisplayName {
|
||||||
|
return nil, fmt.Errorf("the payment's product name: %s doesn't equal to the expected product name: %s", productDisplayName, product.DisplayName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if price != product.Price {
|
||||||
|
return nil, fmt.Errorf("the payment's price: %f doesn't equal to the expected price: %f", price, product.Price)
|
||||||
|
}
|
||||||
|
|
||||||
|
return payment, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NotifyPayment(request *http.Request, body []byte, owner string, providerName string, productName string, paymentName string) bool {
|
||||||
|
payment, err := notifyPayment(request, body, owner, providerName, productName, paymentName)
|
||||||
|
|
||||||
|
if payment != nil {
|
||||||
|
if err != nil {
|
||||||
|
payment.State = "Error"
|
||||||
|
payment.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
payment.State = "Paid"
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdatePayment(payment.GetId(), payment)
|
||||||
|
}
|
||||||
|
|
||||||
|
ok := err == nil
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (payment *Payment) GetId() string {
|
||||||
|
return fmt.Sprintf("%s/%s", payment.Owner, payment.Name)
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -39,10 +39,7 @@ type Permission struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetPermissionCount(owner, field, value string) int {
|
func GetPermissionCount(owner, field, value string) int {
|
||||||
session := adapter.Engine.Where("owner=?", owner)
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Permission{})
|
count, err := session.Count(&Permission{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
|
210
object/product.go
Normal file
210
object/product.go
Normal file
@ -0,0 +1,210 @@
|
|||||||
|
// Copyright 2022 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"
|
||||||
|
"xorm.io/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Product 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"`
|
||||||
|
DisplayName string `xorm:"varchar(100)" json:"displayName"`
|
||||||
|
|
||||||
|
Image string `xorm:"varchar(100)" json:"image"`
|
||||||
|
Detail string `xorm:"varchar(100)" json:"detail"`
|
||||||
|
Tag string `xorm:"varchar(100)" json:"tag"`
|
||||||
|
Currency string `xorm:"varchar(100)" json:"currency"`
|
||||||
|
Price float64 `json:"price"`
|
||||||
|
Quantity int `json:"quantity"`
|
||||||
|
Sold int `json:"sold"`
|
||||||
|
Providers []string `xorm:"varchar(100)" json:"providers"`
|
||||||
|
ReturnUrl string `xorm:"varchar(1000)" json:"returnUrl"`
|
||||||
|
|
||||||
|
State string `xorm:"varchar(100)" json:"state"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetProductCount(owner, field, value string) int {
|
||||||
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
|
count, err := session.Count(&Product{})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return int(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetProducts(owner string) []*Product {
|
||||||
|
products := []*Product{}
|
||||||
|
err := adapter.Engine.Desc("created_time").Find(&products, &Product{Owner: owner})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return products
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetPaginationProducts(owner string, offset, limit int, field, value, sortField, sortOrder string) []*Product {
|
||||||
|
products := []*Product{}
|
||||||
|
session := GetSession(owner, offset, limit, field, value, sortField, sortOrder)
|
||||||
|
err := session.Find(&products)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return products
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProduct(owner string, name string) *Product {
|
||||||
|
if owner == "" || name == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
product := Product{Owner: owner, Name: name}
|
||||||
|
existed, err := adapter.Engine.Get(&product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if existed {
|
||||||
|
return &product
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetProduct(id string) *Product {
|
||||||
|
owner, name := util.GetOwnerAndNameFromId(id)
|
||||||
|
return getProduct(owner, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateProduct(id string, product *Product) bool {
|
||||||
|
owner, name := util.GetOwnerAndNameFromId(id)
|
||||||
|
if getProduct(owner, name) == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
affected, err := adapter.Engine.ID(core.PK{owner, name}).AllCols().Update(product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func AddProduct(product *Product) bool {
|
||||||
|
affected, err := adapter.Engine.Insert(product)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeleteProduct(product *Product) bool {
|
||||||
|
affected, err := adapter.Engine.ID(core.PK{product.Owner, product.Name}).Delete(&Product{})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return affected != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (product *Product) GetId() string {
|
||||||
|
return fmt.Sprintf("%s/%s", product.Owner, product.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (product *Product) isValidProvider(provider *Provider) bool {
|
||||||
|
for _, providerName := range product.Providers {
|
||||||
|
if providerName == provider.Name {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (product *Product) getProvider(providerId string) (*Provider, error) {
|
||||||
|
provider := getProvider(product.Owner, providerId)
|
||||||
|
if provider == nil {
|
||||||
|
return nil, fmt.Errorf("the payment provider: %s does not exist", providerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !product.isValidProvider(provider) {
|
||||||
|
return nil, fmt.Errorf("the payment provider: %s is not valid for the product: %s", providerId, product.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
return provider, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func BuyProduct(id string, providerName string, user *User, host string) (string, error) {
|
||||||
|
product := GetProduct(id)
|
||||||
|
if product == nil {
|
||||||
|
return "", fmt.Errorf("the product: %s does not exist", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
provider, err := product.getProvider(providerName)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
pProvider, _, err := provider.getPaymentProvider()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
owner := product.Owner
|
||||||
|
productName := product.Name
|
||||||
|
paymentName := util.GenerateTimeId()
|
||||||
|
productDisplayName := product.DisplayName
|
||||||
|
|
||||||
|
originFrontend, originBackend := getOriginFromHost(host)
|
||||||
|
returnUrl := fmt.Sprintf("%s/payments/%s/result", originFrontend, paymentName)
|
||||||
|
notifyUrl := fmt.Sprintf("%s/api/notify-payment/%s/%s/%s/%s", originBackend, owner, providerName, productName, paymentName)
|
||||||
|
|
||||||
|
payUrl, err := pProvider.Pay(providerName, productName, paymentName, productDisplayName, product.Price, returnUrl, notifyUrl)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
payment := Payment{
|
||||||
|
Owner: product.Owner,
|
||||||
|
Name: paymentName,
|
||||||
|
CreatedTime: util.GetCurrentTime(),
|
||||||
|
DisplayName: paymentName,
|
||||||
|
Provider: provider.Name,
|
||||||
|
Type: provider.Type,
|
||||||
|
Organization: user.Owner,
|
||||||
|
User: user.Name,
|
||||||
|
ProductName: productName,
|
||||||
|
ProductDisplayName: productDisplayName,
|
||||||
|
Detail: product.Detail,
|
||||||
|
Tag: product.Tag,
|
||||||
|
Currency: product.Currency,
|
||||||
|
Price: product.Price,
|
||||||
|
PayUrl: payUrl,
|
||||||
|
ReturnUrl: product.ReturnUrl,
|
||||||
|
State: "Created",
|
||||||
|
}
|
||||||
|
affected := AddPayment(&payment)
|
||||||
|
if !affected {
|
||||||
|
return "", fmt.Errorf("failed to add payment: %s", util.StructToJson(payment))
|
||||||
|
}
|
||||||
|
|
||||||
|
return payUrl, err
|
||||||
|
}
|
44
object/product_test.go
Normal file
44
object/product_test.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
// Copyright 2022 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.
|
||||||
|
|
||||||
|
//go:build !skipCi
|
||||||
|
// +build !skipCi
|
||||||
|
|
||||||
|
package object
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/casdoor/casdoor/pp"
|
||||||
|
"github.com/casdoor/casdoor/util"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProduct(t *testing.T) {
|
||||||
|
InitConfig()
|
||||||
|
|
||||||
|
product := GetProduct("admin/product_123")
|
||||||
|
provider := getProvider(product.Owner, "provider_pay_alipay")
|
||||||
|
cert := getCert(product.Owner, "cert-pay-alipay")
|
||||||
|
pProvider := pp.GetPaymentProvider(provider.Type, provider.ClientId, provider.ClientSecret, provider.Host, cert.PublicKey, cert.PrivateKey, cert.AuthorityPublicKey, cert.AuthorityRootPublicKey)
|
||||||
|
|
||||||
|
paymentId := util.GenerateTimeId()
|
||||||
|
returnUrl := ""
|
||||||
|
notifyUrl := ""
|
||||||
|
payUrl, err := pProvider.Pay(product.DisplayName, product.Name, provider.Name, paymentId, product.Price, returnUrl, notifyUrl)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
println(payUrl)
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -17,6 +17,7 @@ package object
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/casdoor/casdoor/pp"
|
||||||
"github.com/casdoor/casdoor/util"
|
"github.com/casdoor/casdoor/util"
|
||||||
"xorm.io/core"
|
"xorm.io/core"
|
||||||
)
|
)
|
||||||
@ -29,11 +30,13 @@ type Provider struct {
|
|||||||
DisplayName string `xorm:"varchar(100)" json:"displayName"`
|
DisplayName string `xorm:"varchar(100)" json:"displayName"`
|
||||||
Category string `xorm:"varchar(100)" json:"category"`
|
Category string `xorm:"varchar(100)" json:"category"`
|
||||||
Type string `xorm:"varchar(100)" json:"type"`
|
Type string `xorm:"varchar(100)" json:"type"`
|
||||||
|
SubType string `xorm:"varchar(100)" json:"subType"`
|
||||||
Method string `xorm:"varchar(100)" json:"method"`
|
Method string `xorm:"varchar(100)" json:"method"`
|
||||||
ClientId string `xorm:"varchar(100)" json:"clientId"`
|
ClientId string `xorm:"varchar(100)" json:"clientId"`
|
||||||
ClientSecret string `xorm:"varchar(100)" json:"clientSecret"`
|
ClientSecret string `xorm:"varchar(100)" json:"clientSecret"`
|
||||||
ClientId2 string `xorm:"varchar(100)" json:"clientId2"`
|
ClientId2 string `xorm:"varchar(100)" json:"clientId2"`
|
||||||
ClientSecret2 string `xorm:"varchar(100)" json:"clientSecret2"`
|
ClientSecret2 string `xorm:"varchar(100)" json:"clientSecret2"`
|
||||||
|
Cert string `xorm:"varchar(100)" json:"cert"`
|
||||||
|
|
||||||
Host string `xorm:"varchar(100)" json:"host"`
|
Host string `xorm:"varchar(100)" json:"host"`
|
||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
@ -81,10 +84,7 @@ func GetMaskedProviders(providers []*Provider) []*Provider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetProviderCount(owner, field, value string) int {
|
func GetProviderCount(owner, field, value string) int {
|
||||||
session := adapter.Engine.Where("owner=?", owner)
|
session := GetSession(owner, -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Provider{})
|
count, err := session.Count(&Provider{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
@ -183,6 +183,23 @@ func DeleteProvider(provider *Provider) bool {
|
|||||||
return affected != 0
|
return affected != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (p *Provider) getPaymentProvider() (pp.PaymentProvider, *Cert, error) {
|
||||||
|
cert := &Cert{}
|
||||||
|
if p.Cert != "" {
|
||||||
|
cert = getCert(p.Owner, p.Cert)
|
||||||
|
if cert == nil {
|
||||||
|
return nil, nil, fmt.Errorf("the cert: %s does not exist", p.Cert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pProvider := pp.GetPaymentProvider(p.Type, p.ClientId, p.ClientSecret, p.Host, cert.PublicKey, cert.PrivateKey, cert.AuthorityPublicKey, cert.AuthorityRootPublicKey)
|
||||||
|
if pProvider == nil {
|
||||||
|
return nil, cert, fmt.Errorf("the payment provider type: %s is not supported", p.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pProvider, cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (p *Provider) GetId() string {
|
func (p *Provider) GetId() string {
|
||||||
return fmt.Sprintf("%s/%s", p.Owner, p.Name)
|
return fmt.Sprintf("%s/%s", p.Owner, p.Name)
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2021 The casbin Authors. All Rights Reserved.
|
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
|
||||||
//
|
//
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
// you may not use this file except in compliance with the License.
|
// you may not use this file except in compliance with the License.
|
||||||
@ -102,10 +102,7 @@ func AddRecord(record *Record) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetRecordCount(field, value string) int {
|
func GetRecordCount(field, value string) int {
|
||||||
session := adapter.Engine.Where("1=1")
|
session := GetSession("", -1, -1, field, value, "", "")
|
||||||
if field != "" && value != "" {
|
|
||||||
session = session.And(fmt.Sprintf("%s like ?", util.SnakeString(field)), fmt.Sprintf("%%%s%%", value))
|
|
||||||
}
|
|
||||||
count, err := session.Count(&Record{})
|
count, err := session.Count(&Record{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user