From e9868f44302e66c5f6bc0ed73a34d41e63c2cc75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Sat, 24 Aug 2024 07:14:58 +0000 Subject: [PATCH] feature/template (#1) Co-authored-by: daniel.w Reviewed-on: https://code.30cm.net/digimon/app-cloudep-permission-server/pulls/1 --- .gitignore | 6 + .golangci.yaml | 140 ++++++++++++++ Makefile | 74 ++++++++ build/Dockerfile | 47 +++++ chart/readme.md | 1 + ...816014305_create_permission_table.down.sql | 1 + ...40816014305_create_permission_table.up.sql | 15 ++ ...20240819013052_create_roles_table.down.sql | 1 + .../20240819013052_create_roles_table.up.sql | 12 ++ ...0819022436_create_user_role_table.down.sql | 1 + ...240819022436_create_user_role_table.up.sql | 12 ++ ...0248_create_role_permission_table.down.sql | 1 + ...090248_create_role_permission_table.up.sql | 10 + .../20240824000000_create_schema.down.sql | 1 + .../20240824000000_create_schema.up.sql | 0 generate/database/readme.md | 39 ++++ .../seeders/20230620025708_init_role.down.sql | 1 + .../seeders/20230620025708_init_role.up.sql | 3 + .../20240816014305_init_permission.up.sql | 15 ++ generate/protobuf/service.proto | 154 +++++++++++++++ go.mod | 88 +++++++++ internal/config/config.go | 7 + .../cancel_one_time_token_logic.go | 31 +++ .../cancel_token_by_device_id_logic.go | 31 +++ .../logic/tokenservice/cancel_token_logic.go | 31 +++ .../logic/tokenservice/cancel_tokens_logic.go | 31 +++ .../get_user_tokens_by_device_id_logic.go | 31 +++ .../get_user_tokens_by_uid_logic.go | 31 +++ .../tokenservice/new_one_time_token_logic.go | 31 +++ .../logic/tokenservice/new_token_logic.go | 31 +++ .../logic/tokenservice/refresh_token_logic.go | 31 +++ .../tokenservice/validation_token_logic.go | 31 +++ internal/mock/model/permission_model.go | 115 +++++++++++ internal/mock/model/permission_model_gen.go | 115 +++++++++++ internal/mock/model/role_model.go | 130 +++++++++++++ internal/mock/model/role_model_gen.go | 130 +++++++++++++ internal/mock/model/role_permission_model.go | 100 ++++++++++ .../mock/model/role_permission_model_gen.go | 100 ++++++++++ internal/mock/model/user_role_model.go | 115 +++++++++++ internal/mock/model/user_role_model_gen.go | 115 +++++++++++ internal/model/permission_model.go | 27 +++ internal/model/permission_model_gen.go | 157 +++++++++++++++ internal/model/role_model.go | 27 +++ internal/model/role_model_gen.go | 179 ++++++++++++++++++ internal/model/role_permission_model.go | 27 +++ internal/model/role_permission_model_gen.go | 118 ++++++++++++ internal/model/user_role_model.go | 27 +++ internal/model/user_role_model_gen.go | 155 +++++++++++++++ internal/model/vars.go | 5 + .../tokenservice/token_service_server.go | 83 ++++++++ internal/svc/service_context.go | 13 ++ service.go | 39 ++++ 52 files changed, 2716 insertions(+) create mode 100644 .gitignore create mode 100644 .golangci.yaml create mode 100644 Makefile create mode 100644 build/Dockerfile create mode 100644 chart/readme.md create mode 100644 generate/database/mysql/20240816014305_create_permission_table.down.sql create mode 100644 generate/database/mysql/20240816014305_create_permission_table.up.sql create mode 100644 generate/database/mysql/20240819013052_create_roles_table.down.sql create mode 100644 generate/database/mysql/20240819013052_create_roles_table.up.sql create mode 100644 generate/database/mysql/20240819022436_create_user_role_table.down.sql create mode 100644 generate/database/mysql/20240819022436_create_user_role_table.up.sql create mode 100644 generate/database/mysql/20240819090248_create_role_permission_table.down.sql create mode 100644 generate/database/mysql/20240819090248_create_role_permission_table.up.sql create mode 100644 generate/database/mysql/create/20240824000000_create_schema.down.sql create mode 100644 generate/database/mysql/create/20240824000000_create_schema.up.sql create mode 100644 generate/database/readme.md create mode 100644 generate/database/seeders/20230620025708_init_role.down.sql create mode 100644 generate/database/seeders/20230620025708_init_role.up.sql create mode 100644 generate/database/seeders/20240816014305_init_permission.up.sql create mode 100644 generate/protobuf/service.proto create mode 100644 go.mod create mode 100755 internal/config/config.go create mode 100644 internal/logic/tokenservice/cancel_one_time_token_logic.go create mode 100644 internal/logic/tokenservice/cancel_token_by_device_id_logic.go create mode 100644 internal/logic/tokenservice/cancel_token_logic.go create mode 100644 internal/logic/tokenservice/cancel_tokens_logic.go create mode 100644 internal/logic/tokenservice/get_user_tokens_by_device_id_logic.go create mode 100644 internal/logic/tokenservice/get_user_tokens_by_uid_logic.go create mode 100644 internal/logic/tokenservice/new_one_time_token_logic.go create mode 100644 internal/logic/tokenservice/new_token_logic.go create mode 100644 internal/logic/tokenservice/refresh_token_logic.go create mode 100644 internal/logic/tokenservice/validation_token_logic.go create mode 100644 internal/mock/model/permission_model.go create mode 100644 internal/mock/model/permission_model_gen.go create mode 100644 internal/mock/model/role_model.go create mode 100644 internal/mock/model/role_model_gen.go create mode 100644 internal/mock/model/role_permission_model.go create mode 100644 internal/mock/model/role_permission_model_gen.go create mode 100644 internal/mock/model/user_role_model.go create mode 100644 internal/mock/model/user_role_model_gen.go create mode 100755 internal/model/permission_model.go create mode 100755 internal/model/permission_model_gen.go create mode 100755 internal/model/role_model.go create mode 100755 internal/model/role_model_gen.go create mode 100755 internal/model/role_permission_model.go create mode 100755 internal/model/role_permission_model_gen.go create mode 100755 internal/model/user_role_model.go create mode 100755 internal/model/user_role_model_gen.go create mode 100644 internal/model/vars.go create mode 100644 internal/server/tokenservice/token_service_server.go create mode 100644 internal/svc/service_context.go create mode 100644 service.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a56a16 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.idea/ +go.sum +account/ +gen_result/ +etc/service.yaml +client/ \ No newline at end of file diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000..5518484 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,140 @@ +run: + timeout: 3m + # Exit code when at least one issue was found. + # Default: 1 + issues-exit-code: 2 + # Include test files or not. + # Default: true + tests: false + +# Reference URL: https://golangci-lint.run/usage/linters/ +linters: + # Disable everything by default so upgrades to not include new - default + # enabled- linters. + disable-all: true + # Specifically enable linters we want to use. + enable: + # - depguard + - errcheck + # - godot + - gofmt + - goimports + - gosimple + - govet + - ineffassign + - misspell + - revive + # - staticcheck + - typecheck + - unused + # - wsl + - asasalint + - asciicheck + - bidichk + - bodyclose + # - containedctx + - contextcheck + # - cyclop + # - varnamelen + # - gci + - wastedassign + - whitespace + # - wrapcheck + - thelper + - tparallel + - unconvert + - unparam + - usestdlibvars + - tenv + - testableexamples + - stylecheck + - sqlclosecheck + - nosprintfhostport + - paralleltest + - prealloc + - predeclared + - promlinter + - reassign + - rowserrcheck + - nakedret + - nestif + - nilerr + - nilnil + - nlreturn + - noctx + - nolintlint + - nonamedreturns + - decorder + - dogsled + # - dupl + - dupword + - durationcheck + - errchkjson + - errname + - errorlint + # - execinquery + - exhaustive + - exportloopref + - forbidigo + - forcetypeassert + # - gochecknoglobals + - gochecknoinits + - gocognit + - goconst + - gocritic + - gocyclo + # - godox + # - goerr113 + # - gofumpt + - goheader + - gomoddirectives + # - gomodguard always failed + - goprintffuncname + - gosec + - grouper + - importas + - interfacebloat + # - ireturn + - lll + - loggercheck + - maintidx + - makezero + +issues: + exclude-rules: + - path: _test\.go + linters: + - funlen + - goconst + - interfacer + - dupl + - lll + - goerr113 + - errcheck + - gocritic + - cyclop + - wrapcheck + - gocognit + - contextcheck + +linters-settings: + gci: + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + gocognit: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 40 + nestif: + # Minimal complexity of if statements to report. + # Default: 5 + min-complexity: 10 + lll: + # Max line length, lines longer will be reported. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option. + # Default: 120. + line-length: 200 + # Tab width in spaces. + # Default: 1 + tab-width: 1 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f3eff17 --- /dev/null +++ b/Makefile @@ -0,0 +1,74 @@ +# go-zero 生成風格 +GO_ZERO_STYLE=go_zero + +GO ?= go +GOFMT ?= gofmt "-s" +GOFILES := $(shell find . -name "*.go") +LDFLAGS := -s -w +VERSION="v1.0.1" +DOCKER_REPO="igs170911/permission" + +.PHONY: test +test: # 進行測試 + go test -v --cover ./... + +.PHONY: fmt +fmt: # 格式優化 + $(GOFMT) -w $(GOFILES) + goimports -w ./ + +.PHONY: gen-rpc +gen-rpc: # 建立 rpc code + goctl rpc protoc ./generate/protobuf/service.proto -m --style=$(GO_ZERO_STYLE) --go_out=./gen_result/pb --go-grpc_out=./gen_result/pb --zrpc_out=. + go mod tidy + @echo "Generate core-api files successfully" + +.PHONY: gen-clean +gen-clean: # 建立 rpc code + rm -rf ./client + rm -rf ./etc + rm -rf ./gen_result + rm -rf ./internal + rm -rf go.mod + rm -rf go.sum + rm -rf service.go + @echo "Generate core-api files successfully" + +.PHONY: run-docker +run-docker: # 建立 rpc code + docker run --platform=linux/arm64/v8 -p 8080:8080 $(DOCKER_REPO):$(VERSION) + +.PHONY: build-docker +build-docker: + cp ./build/Dockerfile Dockerfile + docker buildx build -t $(DOCKER_REPO):$(VERSION) --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/ed_25519)" . + rm -rf Dockerfile + @echo "Generate core-api files successfully" + +.PHONY: gen-my-sql-model-up +gen-my-sql-model: # 建立 rpc 資料庫 + goctl model mysql ddl -c no -s ./generate/database/mysql/20240816014305_create_permission_table.up.sql --style $(GO_ZERO_STYLE) -d ./internal/model -i '' + goctl model mysql ddl -c no -s ./generate/database/mysql/20240819013052_create_roles_table.up.sql --style $(GO_ZERO_STYLE) -d ./internal/model -i '' + goctl model mysql ddl -c no -s ./generate/database/mysql/20240819022436_create_user_role_table.up.sql --style $(GO_ZERO_STYLE) -d ./internal/model -i '' + goctl model mysql ddl -c no -s ./generate/database/mysql/20240819090248_create_role_permission_table.up.sql --style $(GO_ZERO_STYLE) -d ./internal/model -i '' + @echo "Generate mysql model files successfully" + +.PHONY: mock-gen +mock-gen: # 建立 mock 資料 + mockgen -source=./internal/model/permission_model.go -destination=./internal/mock/model/permission_model.go -package=mock + mockgen -source=./internal/model/permission_model_gen.go -destination=./internal/mock/model/permission_model_gen.go -package=mock + mockgen -source=./internal/model/role_model.go -destination=./internal/mock/model/role_model.go -package=mock + mockgen -source=./internal/model/role_model_gen.go -destination=./internal/mock/model/role_model_gen.go -package=mock + mockgen -source=./internal/model/role_permission_model.go -destination=./internal/mock/model/role_permission_model.go -package=mock + mockgen -source=./internal/model/role_permission_model_gen.go -destination=./internal/mock/model/role_permission_model_gen.go -package=mock + mockgen -source=./internal/model/user_role_model.go -destination=./internal/mock/model/user_role_model.go -package=mock + mockgen -source=./internal/model/user_role_model_gen.go -destination=./internal/mock/model/user_role_model_gen.go -package=mock + + + + @echo "Generate mock files successfully" + +.PHONY: migrate-database +migrate-database: + migrate -source file://generate/database/mysql -database 'mysql://root:yytt@tcp(127.0.0.1:3306)/digimon_member' up + migrate -source file://generate/database/seeders -database 'mysql://root:yytt@tcp(127.0.0.1:3306)/digimon_member' up diff --git a/build/Dockerfile b/build/Dockerfile new file mode 100644 index 0000000..78cd457 --- /dev/null +++ b/build/Dockerfile @@ -0,0 +1,47 @@ +########### +# BUILDER # +########### + +FROM golang:1.22.3 as builder + +ARG VERSION +ARG BUILT +ARG GIT_COMMIT +ARG SSH_PRV_KEY + +# private go packages +ENV GOPRIVATE=code.30cm.net +ENV FLAG="-s -w -X main.Version=${VERSION} -X main.Built=${BUILT} -X main.GitCommit=${GIT_COMMIT}" +WORKDIR /app +COPY . . + + +RUN apt-get update && \ + apt-get install git + +# Make the root foler for our ssh +RUN mkdir -p /root/.ssh && \ + chmod 0700 /root/.ssh && \ + ssh-keyscan git.30cm.net > /root/.ssh/known_hosts && \ + echo "$SSH_PRV_KEY" > /root/.ssh/id_rsa && \ + chmod 600 /root/.ssh/id_rsa + + + +RUN --mount=type=ssh go mod download + +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ + -ldflags "$FLAG" \ + -o service + +########## +## FINAL # +########## +# +FROM gcr.io/distroless/static-debian11 +WORKDIR /app + +COPY --from=builder /app/service /app/service +COPY --from=builder /app/etc/service.yaml /app/etc/service.yaml +EXPOSE 8080 +CMD ["/app/service"] \ No newline at end of file diff --git a/chart/readme.md b/chart/readme.md new file mode 100644 index 0000000..33c4f67 --- /dev/null +++ b/chart/readme.md @@ -0,0 +1 @@ +// TODO 未來要放 helm 的地方 \ No newline at end of file diff --git a/generate/database/mysql/20240816014305_create_permission_table.down.sql b/generate/database/mysql/20240816014305_create_permission_table.down.sql new file mode 100644 index 0000000..6dc8750 --- /dev/null +++ b/generate/database/mysql/20240816014305_create_permission_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS `permission`; diff --git a/generate/database/mysql/20240816014305_create_permission_table.up.sql b/generate/database/mysql/20240816014305_create_permission_table.up.sql new file mode 100644 index 0000000..cbe4d31 --- /dev/null +++ b/generate/database/mysql/20240816014305_create_permission_table.up.sql @@ -0,0 +1,15 @@ +-- 通常會把整個表都放到記憶體當中,不常搜尋,不需要加其他搜尋的 index +CREATE TABLE `permission` +( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK', + `parent` bigint unsigned DEFAULT NULL, + `name` varchar(255) NOT NULL, + `http_method` varchar(255) NOT NULL, + `http_path` text NOT NULL, + `status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 啟用, 2: 關閉', + `type` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 後台, 2: 前台', + `create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間', + `update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間', + PRIMARY KEY (`id`), + UNIQUE KEY `name_unique_key` (`name`) +) ENGINE = InnoDB COMMENT ='權限表'; \ No newline at end of file diff --git a/generate/database/mysql/20240819013052_create_roles_table.down.sql b/generate/database/mysql/20240819013052_create_roles_table.down.sql new file mode 100644 index 0000000..37e4134 --- /dev/null +++ b/generate/database/mysql/20240819013052_create_roles_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS `role`; diff --git a/generate/database/mysql/20240819013052_create_roles_table.up.sql b/generate/database/mysql/20240819013052_create_roles_table.up.sql new file mode 100644 index 0000000..b4b6229 --- /dev/null +++ b/generate/database/mysql/20240819013052_create_roles_table.up.sql @@ -0,0 +1,12 @@ +CREATE TABLE `role` +( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK', + `role_id` varchar(50) NOT NULL, + `display_name` varchar(255) NOT NULL COMMENT '名稱', + `status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 啟用, 2: 禁用', + `create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間', + `update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間', + PRIMARY KEY (`id`), + UNIQUE KEY `uid_unique_key` (`role_id`), + UNIQUE KEY `name_unique_key` (`display_name`) +) ENGINE = InnoDB COMMENT ='角色'; \ No newline at end of file diff --git a/generate/database/mysql/20240819022436_create_user_role_table.down.sql b/generate/database/mysql/20240819022436_create_user_role_table.down.sql new file mode 100644 index 0000000..c27c315 --- /dev/null +++ b/generate/database/mysql/20240819022436_create_user_role_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS `user_role`; diff --git a/generate/database/mysql/20240819022436_create_user_role_table.up.sql b/generate/database/mysql/20240819022436_create_user_role_table.up.sql new file mode 100644 index 0000000..040fd6c --- /dev/null +++ b/generate/database/mysql/20240819022436_create_user_role_table.up.sql @@ -0,0 +1,12 @@ +CREATE TABLE `user_role` +( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK', + `brand` varchar(50) DEFAULT '' NOT NULL COMMENT '', + `uid` varchar(50) NOT NULL, + `role_id` varchar(50) NOT NULL, + `status` tinyint NOT NULL DEFAULT '1' COMMENT '狀態 1: 啟用, 2: 禁用', + `create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間', + `update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間', + PRIMARY KEY (`id`), + UNIQUE KEY `uid_unique_key` (`uid`) +) ENGINE = InnoDB COMMENT ='會員角色'; \ No newline at end of file diff --git a/generate/database/mysql/20240819090248_create_role_permission_table.down.sql b/generate/database/mysql/20240819090248_create_role_permission_table.down.sql new file mode 100644 index 0000000..26a43a9 --- /dev/null +++ b/generate/database/mysql/20240819090248_create_role_permission_table.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS `role_permission`; diff --git a/generate/database/mysql/20240819090248_create_role_permission_table.up.sql b/generate/database/mysql/20240819090248_create_role_permission_table.up.sql new file mode 100644 index 0000000..8ab08c7 --- /dev/null +++ b/generate/database/mysql/20240819090248_create_role_permission_table.up.sql @@ -0,0 +1,10 @@ +CREATE TABLE `role_permission` +( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK', + `role_id` bigint unsigned DEFAULT NULL COMMENT 'role.id', + `permission_id` bigint unsigned DEFAULT NULL COMMENT 'permission.id', + `create_time` bigint DEFAULT 0 NOT NULL COMMENT '創建時間', + `update_time` bigint DEFAULT 0 NOT NULL COMMENT '更新時間', + PRIMARY KEY (`id`), + KEY `category_id_permission_id_index` (`role_id`, `permission_id`) +) ENGINE = InnoDB COMMENT ='角色權限'; \ No newline at end of file diff --git a/generate/database/mysql/create/20240824000000_create_schema.down.sql b/generate/database/mysql/create/20240824000000_create_schema.down.sql new file mode 100644 index 0000000..9c7ec94 --- /dev/null +++ b/generate/database/mysql/create/20240824000000_create_schema.down.sql @@ -0,0 +1 @@ +DROP DATABASE IF EXISTS `digimon_permission`; \ No newline at end of file diff --git a/generate/database/mysql/create/20240824000000_create_schema.up.sql b/generate/database/mysql/create/20240824000000_create_schema.up.sql new file mode 100644 index 0000000..e69de29 diff --git a/generate/database/readme.md b/generate/database/readme.md new file mode 100644 index 0000000..4db6e02 --- /dev/null +++ b/generate/database/readme.md @@ -0,0 +1,39 @@ +# migrate +數據庫遷移工具 + +[golang-migrate](https://github.com/golang-migrate/migrate) + +## 安裝 make +```shell +brew install Makefile +``` + +## 安裝 golang-migrate +```shell +brew install golang-migrate +``` + +## 執行刪除 mysql schema + +```shell +migrate -source file://database/migrations/mysql -database 'mysql://account:password@tcp(127.0.0.1:3306)/esc_c2c' down +``` + +## 執行安裝 mysql schema + +```shell +migrate -source file://database/migrations/mysql -database 'mysql://account:password@tcp(127.0.0.1:3306)/esc_c2c' up +``` + +## 執行刪除 mongo schema + +```shell +migrate -source file://database/migrations/mongodb -database 'mongodb://127.0.0.1:27017/esc_c2c' down +``` + +## 執行安裝 mongo schema + +```shell +migrate -source file://database/migrations/mongodb -database 'mongodb://127.0.0.1:27017/esc_c2c' up +``` + diff --git a/generate/database/seeders/20230620025708_init_role.down.sql b/generate/database/seeders/20230620025708_init_role.down.sql new file mode 100644 index 0000000..36a1962 --- /dev/null +++ b/generate/database/seeders/20230620025708_init_role.down.sql @@ -0,0 +1 @@ +DELETE FROM `role` WHERE (`role_id` = 'AM000000'); diff --git a/generate/database/seeders/20230620025708_init_role.up.sql b/generate/database/seeders/20230620025708_init_role.up.sql new file mode 100644 index 0000000..d4c158e --- /dev/null +++ b/generate/database/seeders/20230620025708_init_role.up.sql @@ -0,0 +1,3 @@ +INSERT INTO `role` (`role_id`, `display_name`, `status`, `create_time`, `update_time`) +VALUES ('AM000000', 'admin', 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()), + ('AM000001', 'visitor', 1, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()); \ No newline at end of file diff --git a/generate/database/seeders/20240816014305_init_permission.up.sql b/generate/database/seeders/20240816014305_init_permission.up.sql new file mode 100644 index 0000000..1293885 --- /dev/null +++ b/generate/database/seeders/20240816014305_init_permission.up.sql @@ -0,0 +1,15 @@ +-- 一級分類 +INSERT INTO `permission` (`parent`, `name`, `http_method`, `http_path`, `create_time`, `update_time`) +VALUES (0, 'user.info.management', '', '', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()); -- 用戶資訊管理 + +# -- 二級分類 用戶資訊管理 +SET @id := (SELECT id FROM `permission` where name = 'user.info.management'); +INSERT INTO `permission` (`parent`, `name`, `http_method`, `http_path`, `create_time`, `update_time`) +VALUES (@id, 'user.basic.info', '', '', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()); -- 用戶基礎資訊查詢 + + +# -- 三級分類 用戶基礎資訊管理-基礎資訊查詢表 +SET @id := (SELECT id FROM `permission` where name = 'user.basic.info'); +INSERT INTO `permission` (`parent`, `name`, `http_method`, `http_path`, `create_time`, `update_time`) +VALUES (@id, 'user.info.select', 'GET', '/v1/user', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()), -- 查詢 + (@id, 'user.info.select.plain_code', 'GET', '/v1/user', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()); -- 明碼查詢 diff --git a/generate/protobuf/service.proto b/generate/protobuf/service.proto new file mode 100644 index 0000000..62f547e --- /dev/null +++ b/generate/protobuf/service.proto @@ -0,0 +1,154 @@ +syntax = "proto3"; + +package permission; + +option go_package="./permission"; + +// OKResp +message OKResp {} +// NoneReq +message NoneReq {} + +// AuthorizationReq 定義授權請求的結構 +message AuthorizationReq { + // grant_type 表示授權類型 + string grant_type = 1; + // device_id 表示設備 ID + string device_id = 2; + // scope 表示授權範圍 + string scope = 3; + // data 是一個通用的 key-value 結構,用於存儲額外數據 + map data = 4; + // expires 表示過期時間 + int32 expires = 5; + // is_refresh_token 表示是否為刷新令牌 + bool is_refresh_token = 6; +} + +// TokenResp 定義訪問令牌響應的結構 +message TokenResp { + // access_token 表示訪問令牌 + string access_token = 1; + // token_type 表示令牌類型 + string token_type = 2; + // expires_in 表示令牌過期時間 + int32 expires_in = 3; + // refresh_token 表示刷新令牌 + string refresh_token = 4; +} + +// CreateOneTimeTokenReq 建立一次性使用的 token, +// 要帶比較長久的 token 來,驗證後才可以 +message CreateOneTimeTokenReq { + string token = 1; +} + +message CreateOneTimeTokenResp { + string one_time_token = 1; +} + +// RefreshTokenReq 更新 Token +message RefreshTokenReq { + string token = 1; + string scope = 2; + int64 expires = 3; + string device_id = 4; +} + +// https://datatracker.ietf.org/doc/html/rfc6749#section-4.3.3 +message RefreshTokenResp { + string token =1; + string one_time_token = 2; + int64 expires_in = 3; + string token_type = 4; +} + +// CancelTokenReq 註銷這個 Token +message CancelTokenReq { + string token = 1; +} + +// CancelTokenReq 註銷這個 Token +message DoTokenByUIDReq { + repeated string ids = 1; + string uid = 2; +} + +// QueryTokenByUIDReq 拿這個UID 找 Token +message QueryTokenByUIDReq { + string uid = 1; +} + +// ValidationTokenReq 驗證這個 Token +message ValidationTokenReq { + string token = 1; +} + +// ValidationTokenResp 驗證以及取得 Token 詳情 +message ValidationTokenResp { + Token token = 1; + map data = 2; +} + +// Token 定義令牌的結構 +message Token { + // ID 表示令牌的唯一標識符 + string id = 1; + // client_id 表示客戶端 ID + int32 client_id = 2; + // uid 表示用戶 ID + string uid = 3; + // device_id 表示設備 ID + string device_id = 4; + // access_token 表示訪問令牌 + string access_token = 5; + // expires_in 表示訪問令牌的過期時間(秒) + int32 expires_in = 6; + // access_create_at 表示訪問令牌的創建時間 + int64 access_create_at = 7; + // refresh_token 表示刷新令牌 + string refresh_token = 8; + // refresh_expires_in 表示刷新令牌的過期時間(秒) + int32 refresh_expires_in = 9; + // refresh_create_at 表示刷新令牌的創建時間 + int64 refresh_create_at = 10; +} + +// DoTokenByDeviceIDReq 用DeviceID 來做事的 +message DoTokenByDeviceIDReq { + string device_id = 1; +} + +message Tokens{ + repeated TokenResp token = 1; +} + +message CancelOneTimeTokenReq { + repeated string token = 1; +} + +// 跟 Token 相關的大小事,這次只回應錯誤,以及結果,不統一規範 +// 錯誤碼應該在 Biz GW 在做回應,另外我這邊取名字比較通用, +// access_token -> token , refresh_token -> one_time_token +service TokenService { + // NewToken 建立一個新的 Token,例如:AccessToken + rpc NewToken(AuthorizationReq) returns(TokenResp); + // RefreshToken 更新目前的token 以及裡面包含的一次性 Token + rpc RefreshToken(RefreshTokenReq) returns(RefreshTokenResp); + // CancelToken 取消 Token,也包含他裡面的 One Time Toke + rpc CancelToken(CancelTokenReq) returns(OKResp); + // ValidationToken 驗證這個 Token 有沒有效 + rpc ValidationToken(ValidationTokenReq) returns(ValidationTokenResp); + // CancelTokens 取消 Token 從UID 視角,以及 token id 視角出發, UID 登出,底下所有 Device ID 也要登出, Token ID 登出, 所有 UID + Device 都要登出 + rpc CancelTokens(DoTokenByUIDReq) returns(OKResp); + // CancelTokenByDeviceId 取消 Token, 從 Device 視角出發,可以選,登出這個Device 下所有 token ,登出這個Device 下指定token + rpc CancelTokenByDeviceId(DoTokenByDeviceIDReq) returns(OKResp); + // GetUserTokensByDeviceId 取得目前所對應的 DeviceID 所存在的 Tokens + rpc GetUserTokensByDeviceId(DoTokenByDeviceIDReq) returns(Tokens); + // GetUserTokensByUid 取得目前所對應的 UID 所存在的 Tokens + rpc GetUserTokensByUid(QueryTokenByUIDReq) returns(Tokens); + // NewOneTimeToken 建立一次性使用,例如:RefreshToken + rpc NewOneTimeToken(CreateOneTimeTokenReq) returns(CreateOneTimeTokenResp); + // CancelOneTimeToken 取消一次性使用 + rpc CancelOneTimeToken(CancelOneTimeTokenReq) returns(OKResp); +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e63a795 --- /dev/null +++ b/go.mod @@ -0,0 +1,88 @@ +module app-cloudep-permission-server + +go 1.22.3 + +require ( + github.com/zeromicro/go-zero v1.7.0 + google.golang.org/grpc v1.65.0 + google.golang.org/protobuf v1.34.2 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/coreos/go-semver v0.3.1 // indirect + github.com/coreos/go-systemd/v22 v22.5.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/fatih/color v1.17.0 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.2 // indirect + github.com/go-openapi/swag v0.22.4 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/mock v1.6.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/gnostic-models v0.6.8 // indirect + github.com/google/go-cmp v0.6.0 // indirect + github.com/google/gofuzz v1.2.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.20.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/openzipkin/zipkin-go v0.4.3 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/prometheus/client_golang v1.19.1 // indirect + github.com/prometheus/client_model v0.5.0 // indirect + github.com/prometheus/common v0.48.0 // indirect + github.com/prometheus/procfs v0.12.0 // indirect + github.com/redis/go-redis/v9 v9.6.1 // indirect + github.com/spaolacci/murmur3 v1.1.0 // indirect + go.etcd.io/etcd/api/v3 v3.5.15 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.5.15 // indirect + go.etcd.io/etcd/client/v3 v3.5.15 // indirect + go.opentelemetry.io/otel v1.24.0 // indirect + go.opentelemetry.io/otel/exporters/jaeger v1.17.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.24.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.24.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.24.0 // indirect + go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.24.0 // indirect + go.opentelemetry.io/otel/exporters/zipkin v1.24.0 // indirect + go.opentelemetry.io/otel/metric v1.24.0 // indirect + go.opentelemetry.io/otel/sdk v1.24.0 // indirect + go.opentelemetry.io/otel/trace v1.24.0 // indirect + go.opentelemetry.io/proto/otlp v1.3.1 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/automaxprocs v1.5.3 // indirect + go.uber.org/multierr v1.9.0 // indirect + go.uber.org/zap v1.24.0 // indirect + golang.org/x/net v0.27.0 // indirect + golang.org/x/oauth2 v0.20.0 // indirect + golang.org/x/sys v0.22.0 // indirect + golang.org/x/term v0.22.0 // indirect + golang.org/x/text v0.16.0 // indirect + golang.org/x/time v0.5.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20240711142825-46eb208f015d // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/api v0.29.3 // indirect + k8s.io/apimachinery v0.29.4 // indirect + k8s.io/client-go v0.29.3 // indirect + k8s.io/klog/v2 v2.110.1 // indirect + k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect + k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect + sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect +) diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100755 index 0000000..c1f85b9 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,7 @@ +package config + +import "github.com/zeromicro/go-zero/zrpc" + +type Config struct { + zrpc.RpcServerConf +} diff --git a/internal/logic/tokenservice/cancel_one_time_token_logic.go b/internal/logic/tokenservice/cancel_one_time_token_logic.go new file mode 100644 index 0000000..70f109a --- /dev/null +++ b/internal/logic/tokenservice/cancel_one_time_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CancelOneTimeTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewCancelOneTimeTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelOneTimeTokenLogic { + return &CancelOneTimeTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// CancelOneTimeToken 取消一次性使用 +func (l *CancelOneTimeTokenLogic) CancelOneTimeToken(in *permission.CancelOneTimeTokenReq) (*permission.OKResp, error) { + // todo: add your logic here and delete this line + + return &permission.OKResp{}, nil +} diff --git a/internal/logic/tokenservice/cancel_token_by_device_id_logic.go b/internal/logic/tokenservice/cancel_token_by_device_id_logic.go new file mode 100644 index 0000000..e1623fe --- /dev/null +++ b/internal/logic/tokenservice/cancel_token_by_device_id_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CancelTokenByDeviceIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewCancelTokenByDeviceIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelTokenByDeviceIdLogic { + return &CancelTokenByDeviceIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// CancelTokenByDeviceId 取消 Token, 從 Device 視角出發,可以選,登出這個Device 下所有 token ,登出這個Device 下指定token +func (l *CancelTokenByDeviceIdLogic) CancelTokenByDeviceId(in *permission.DoTokenByDeviceIDReq) (*permission.OKResp, error) { + // todo: add your logic here and delete this line + + return &permission.OKResp{}, nil +} diff --git a/internal/logic/tokenservice/cancel_token_logic.go b/internal/logic/tokenservice/cancel_token_logic.go new file mode 100644 index 0000000..7e1808b --- /dev/null +++ b/internal/logic/tokenservice/cancel_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CancelTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewCancelTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelTokenLogic { + return &CancelTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// CancelToken 取消 Token,也包含他裡面的 One Time Toke +func (l *CancelTokenLogic) CancelToken(in *permission.CancelTokenReq) (*permission.OKResp, error) { + // todo: add your logic here and delete this line + + return &permission.OKResp{}, nil +} diff --git a/internal/logic/tokenservice/cancel_tokens_logic.go b/internal/logic/tokenservice/cancel_tokens_logic.go new file mode 100644 index 0000000..3df4d22 --- /dev/null +++ b/internal/logic/tokenservice/cancel_tokens_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type CancelTokensLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewCancelTokensLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelTokensLogic { + return &CancelTokensLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// CancelTokens 取消 Token 從UID 視角,以及 token id 視角出發, UID 登出,底下所有 Device ID 也要登出, Token ID 登出, 所有 UID + Device 都要登出 +func (l *CancelTokensLogic) CancelTokens(in *permission.DoTokenByUIDReq) (*permission.OKResp, error) { + // todo: add your logic here and delete this line + + return &permission.OKResp{}, nil +} diff --git a/internal/logic/tokenservice/get_user_tokens_by_device_id_logic.go b/internal/logic/tokenservice/get_user_tokens_by_device_id_logic.go new file mode 100644 index 0000000..b289f0b --- /dev/null +++ b/internal/logic/tokenservice/get_user_tokens_by_device_id_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetUserTokensByDeviceIdLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetUserTokensByDeviceIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserTokensByDeviceIdLogic { + return &GetUserTokensByDeviceIdLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// GetUserTokensByDeviceId 取得目前所對應的 DeviceID 所存在的 Tokens +func (l *GetUserTokensByDeviceIdLogic) GetUserTokensByDeviceId(in *permission.DoTokenByDeviceIDReq) (*permission.Tokens, error) { + // todo: add your logic here and delete this line + + return &permission.Tokens{}, nil +} diff --git a/internal/logic/tokenservice/get_user_tokens_by_uid_logic.go b/internal/logic/tokenservice/get_user_tokens_by_uid_logic.go new file mode 100644 index 0000000..9f6c69f --- /dev/null +++ b/internal/logic/tokenservice/get_user_tokens_by_uid_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type GetUserTokensByUidLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewGetUserTokensByUidLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserTokensByUidLogic { + return &GetUserTokensByUidLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// GetUserTokensByUid 取得目前所對應的 UID 所存在的 Tokens +func (l *GetUserTokensByUidLogic) GetUserTokensByUid(in *permission.QueryTokenByUIDReq) (*permission.Tokens, error) { + // todo: add your logic here and delete this line + + return &permission.Tokens{}, nil +} diff --git a/internal/logic/tokenservice/new_one_time_token_logic.go b/internal/logic/tokenservice/new_one_time_token_logic.go new file mode 100644 index 0000000..082ea3b --- /dev/null +++ b/internal/logic/tokenservice/new_one_time_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type NewOneTimeTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewNewOneTimeTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewOneTimeTokenLogic { + return &NewOneTimeTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// NewOneTimeToken 建立一次性使用,例如:RefreshToken +func (l *NewOneTimeTokenLogic) NewOneTimeToken(in *permission.CreateOneTimeTokenReq) (*permission.CreateOneTimeTokenResp, error) { + // todo: add your logic here and delete this line + + return &permission.CreateOneTimeTokenResp{}, nil +} diff --git a/internal/logic/tokenservice/new_token_logic.go b/internal/logic/tokenservice/new_token_logic.go new file mode 100644 index 0000000..e7e750c --- /dev/null +++ b/internal/logic/tokenservice/new_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type NewTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewNewTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewTokenLogic { + return &NewTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// NewToken 建立一個新的 Token,例如:AccessToken +func (l *NewTokenLogic) NewToken(in *permission.AuthorizationReq) (*permission.TokenResp, error) { + // todo: add your logic here and delete this line + + return &permission.TokenResp{}, nil +} diff --git a/internal/logic/tokenservice/refresh_token_logic.go b/internal/logic/tokenservice/refresh_token_logic.go new file mode 100644 index 0000000..dd64bcb --- /dev/null +++ b/internal/logic/tokenservice/refresh_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type RefreshTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewRefreshTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefreshTokenLogic { + return &RefreshTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// RefreshToken 更新目前的token 以及裡面包含的一次性 Token +func (l *RefreshTokenLogic) RefreshToken(in *permission.RefreshTokenReq) (*permission.RefreshTokenResp, error) { + // todo: add your logic here and delete this line + + return &permission.RefreshTokenResp{}, nil +} diff --git a/internal/logic/tokenservice/validation_token_logic.go b/internal/logic/tokenservice/validation_token_logic.go new file mode 100644 index 0000000..0fe447a --- /dev/null +++ b/internal/logic/tokenservice/validation_token_logic.go @@ -0,0 +1,31 @@ +package tokenservicelogic + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +type ValidationTokenLogic struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func NewValidationTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ValidationTokenLogic { + return &ValidationTokenLogic{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} + +// ValidationToken 驗證這個 Token 有沒有效 +func (l *ValidationTokenLogic) ValidationToken(in *permission.ValidationTokenReq) (*permission.ValidationTokenResp, error) { + // todo: add your logic here and delete this line + + return &permission.ValidationTokenResp{}, nil +} diff --git a/internal/mock/model/permission_model.go b/internal/mock/model/permission_model.go new file mode 100644 index 0000000..47a7c11 --- /dev/null +++ b/internal/mock/model/permission_model.go @@ -0,0 +1,115 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/permission_model.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/permission_model.go -destination=./internal/mock/model/permission_model.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockPermissionModel is a mock of PermissionModel interface. +type MockPermissionModel struct { + ctrl *gomock.Controller + recorder *MockPermissionModelMockRecorder +} + +// MockPermissionModelMockRecorder is the mock recorder for MockPermissionModel. +type MockPermissionModelMockRecorder struct { + mock *MockPermissionModel +} + +// NewMockPermissionModel creates a new mock instance. +func NewMockPermissionModel(ctrl *gomock.Controller) *MockPermissionModel { + mock := &MockPermissionModel{ctrl: ctrl} + mock.recorder = &MockPermissionModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPermissionModel) EXPECT() *MockPermissionModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockPermissionModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockPermissionModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockPermissionModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockPermissionModel) FindOne(ctx context.Context, id int64) (*model.Permission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.Permission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockPermissionModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockPermissionModel)(nil).FindOne), ctx, id) +} + +// FindOneByName mocks base method. +func (m *MockPermissionModel) FindOneByName(ctx context.Context, name string) (*model.Permission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByName", ctx, name) + ret0, _ := ret[0].(*model.Permission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByName indicates an expected call of FindOneByName. +func (mr *MockPermissionModelMockRecorder) FindOneByName(ctx, name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByName", reflect.TypeOf((*MockPermissionModel)(nil).FindOneByName), ctx, name) +} + +// Insert mocks base method. +func (m *MockPermissionModel) Insert(ctx context.Context, data *model.Permission) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockPermissionModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockPermissionModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockPermissionModel) Update(ctx context.Context, data *model.Permission) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockPermissionModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockPermissionModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/permission_model_gen.go b/internal/mock/model/permission_model_gen.go new file mode 100644 index 0000000..fcb4d57 --- /dev/null +++ b/internal/mock/model/permission_model_gen.go @@ -0,0 +1,115 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/permission_model_gen.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/permission_model_gen.go -destination=./internal/mock/model/permission_model_gen.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockpermissionModel is a mock of permissionModel interface. +type MockpermissionModel struct { + ctrl *gomock.Controller + recorder *MockpermissionModelMockRecorder +} + +// MockpermissionModelMockRecorder is the mock recorder for MockpermissionModel. +type MockpermissionModelMockRecorder struct { + mock *MockpermissionModel +} + +// NewMockpermissionModel creates a new mock instance. +func NewMockpermissionModel(ctrl *gomock.Controller) *MockpermissionModel { + mock := &MockpermissionModel{ctrl: ctrl} + mock.recorder = &MockpermissionModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockpermissionModel) EXPECT() *MockpermissionModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockpermissionModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockpermissionModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockpermissionModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockpermissionModel) FindOne(ctx context.Context, id int64) (*model.Permission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.Permission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockpermissionModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockpermissionModel)(nil).FindOne), ctx, id) +} + +// FindOneByName mocks base method. +func (m *MockpermissionModel) FindOneByName(ctx context.Context, name string) (*model.Permission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByName", ctx, name) + ret0, _ := ret[0].(*model.Permission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByName indicates an expected call of FindOneByName. +func (mr *MockpermissionModelMockRecorder) FindOneByName(ctx, name any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByName", reflect.TypeOf((*MockpermissionModel)(nil).FindOneByName), ctx, name) +} + +// Insert mocks base method. +func (m *MockpermissionModel) Insert(ctx context.Context, data *model.Permission) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockpermissionModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockpermissionModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockpermissionModel) Update(ctx context.Context, data *model.Permission) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockpermissionModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockpermissionModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/role_model.go b/internal/mock/model/role_model.go new file mode 100644 index 0000000..aeb86cd --- /dev/null +++ b/internal/mock/model/role_model.go @@ -0,0 +1,130 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/role_model.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/role_model.go -destination=./internal/mock/model/role_model.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockRoleModel is a mock of RoleModel interface. +type MockRoleModel struct { + ctrl *gomock.Controller + recorder *MockRoleModelMockRecorder +} + +// MockRoleModelMockRecorder is the mock recorder for MockRoleModel. +type MockRoleModelMockRecorder struct { + mock *MockRoleModel +} + +// NewMockRoleModel creates a new mock instance. +func NewMockRoleModel(ctrl *gomock.Controller) *MockRoleModel { + mock := &MockRoleModel{ctrl: ctrl} + mock.recorder = &MockRoleModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRoleModel) EXPECT() *MockRoleModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockRoleModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockRoleModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRoleModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockRoleModel) FindOne(ctx context.Context, id int64) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockRoleModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockRoleModel)(nil).FindOne), ctx, id) +} + +// FindOneByDisplayName mocks base method. +func (m *MockRoleModel) FindOneByDisplayName(ctx context.Context, displayName string) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByDisplayName", ctx, displayName) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByDisplayName indicates an expected call of FindOneByDisplayName. +func (mr *MockRoleModelMockRecorder) FindOneByDisplayName(ctx, displayName any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByDisplayName", reflect.TypeOf((*MockRoleModel)(nil).FindOneByDisplayName), ctx, displayName) +} + +// FindOneByRoleId mocks base method. +func (m *MockRoleModel) FindOneByRoleId(ctx context.Context, roleId string) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByRoleId", ctx, roleId) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByRoleId indicates an expected call of FindOneByRoleId. +func (mr *MockRoleModelMockRecorder) FindOneByRoleId(ctx, roleId any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByRoleId", reflect.TypeOf((*MockRoleModel)(nil).FindOneByRoleId), ctx, roleId) +} + +// Insert mocks base method. +func (m *MockRoleModel) Insert(ctx context.Context, data *model.Role) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockRoleModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockRoleModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockRoleModel) Update(ctx context.Context, data *model.Role) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockRoleModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRoleModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/role_model_gen.go b/internal/mock/model/role_model_gen.go new file mode 100644 index 0000000..75f34a2 --- /dev/null +++ b/internal/mock/model/role_model_gen.go @@ -0,0 +1,130 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/role_model_gen.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/role_model_gen.go -destination=./internal/mock/model/role_model_gen.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockroleModel is a mock of roleModel interface. +type MockroleModel struct { + ctrl *gomock.Controller + recorder *MockroleModelMockRecorder +} + +// MockroleModelMockRecorder is the mock recorder for MockroleModel. +type MockroleModelMockRecorder struct { + mock *MockroleModel +} + +// NewMockroleModel creates a new mock instance. +func NewMockroleModel(ctrl *gomock.Controller) *MockroleModel { + mock := &MockroleModel{ctrl: ctrl} + mock.recorder = &MockroleModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockroleModel) EXPECT() *MockroleModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockroleModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockroleModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockroleModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockroleModel) FindOne(ctx context.Context, id int64) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockroleModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockroleModel)(nil).FindOne), ctx, id) +} + +// FindOneByDisplayName mocks base method. +func (m *MockroleModel) FindOneByDisplayName(ctx context.Context, displayName string) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByDisplayName", ctx, displayName) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByDisplayName indicates an expected call of FindOneByDisplayName. +func (mr *MockroleModelMockRecorder) FindOneByDisplayName(ctx, displayName any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByDisplayName", reflect.TypeOf((*MockroleModel)(nil).FindOneByDisplayName), ctx, displayName) +} + +// FindOneByRoleId mocks base method. +func (m *MockroleModel) FindOneByRoleId(ctx context.Context, roleId string) (*model.Role, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByRoleId", ctx, roleId) + ret0, _ := ret[0].(*model.Role) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByRoleId indicates an expected call of FindOneByRoleId. +func (mr *MockroleModelMockRecorder) FindOneByRoleId(ctx, roleId any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByRoleId", reflect.TypeOf((*MockroleModel)(nil).FindOneByRoleId), ctx, roleId) +} + +// Insert mocks base method. +func (m *MockroleModel) Insert(ctx context.Context, data *model.Role) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockroleModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockroleModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockroleModel) Update(ctx context.Context, data *model.Role) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockroleModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockroleModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/role_permission_model.go b/internal/mock/model/role_permission_model.go new file mode 100644 index 0000000..b5301c8 --- /dev/null +++ b/internal/mock/model/role_permission_model.go @@ -0,0 +1,100 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/role_permission_model.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/role_permission_model.go -destination=./internal/mock/model/role_permission_model.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockRolePermissionModel is a mock of RolePermissionModel interface. +type MockRolePermissionModel struct { + ctrl *gomock.Controller + recorder *MockRolePermissionModelMockRecorder +} + +// MockRolePermissionModelMockRecorder is the mock recorder for MockRolePermissionModel. +type MockRolePermissionModelMockRecorder struct { + mock *MockRolePermissionModel +} + +// NewMockRolePermissionModel creates a new mock instance. +func NewMockRolePermissionModel(ctrl *gomock.Controller) *MockRolePermissionModel { + mock := &MockRolePermissionModel{ctrl: ctrl} + mock.recorder = &MockRolePermissionModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRolePermissionModel) EXPECT() *MockRolePermissionModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockRolePermissionModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockRolePermissionModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockRolePermissionModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockRolePermissionModel) FindOne(ctx context.Context, id int64) (*model.RolePermission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.RolePermission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockRolePermissionModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockRolePermissionModel)(nil).FindOne), ctx, id) +} + +// Insert mocks base method. +func (m *MockRolePermissionModel) Insert(ctx context.Context, data *model.RolePermission) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockRolePermissionModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockRolePermissionModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockRolePermissionModel) Update(ctx context.Context, data *model.RolePermission) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockRolePermissionModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockRolePermissionModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/role_permission_model_gen.go b/internal/mock/model/role_permission_model_gen.go new file mode 100644 index 0000000..2c620fd --- /dev/null +++ b/internal/mock/model/role_permission_model_gen.go @@ -0,0 +1,100 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/role_permission_model_gen.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/role_permission_model_gen.go -destination=./internal/mock/model/role_permission_model_gen.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockrolePermissionModel is a mock of rolePermissionModel interface. +type MockrolePermissionModel struct { + ctrl *gomock.Controller + recorder *MockrolePermissionModelMockRecorder +} + +// MockrolePermissionModelMockRecorder is the mock recorder for MockrolePermissionModel. +type MockrolePermissionModelMockRecorder struct { + mock *MockrolePermissionModel +} + +// NewMockrolePermissionModel creates a new mock instance. +func NewMockrolePermissionModel(ctrl *gomock.Controller) *MockrolePermissionModel { + mock := &MockrolePermissionModel{ctrl: ctrl} + mock.recorder = &MockrolePermissionModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockrolePermissionModel) EXPECT() *MockrolePermissionModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockrolePermissionModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockrolePermissionModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockrolePermissionModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockrolePermissionModel) FindOne(ctx context.Context, id int64) (*model.RolePermission, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.RolePermission) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockrolePermissionModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockrolePermissionModel)(nil).FindOne), ctx, id) +} + +// Insert mocks base method. +func (m *MockrolePermissionModel) Insert(ctx context.Context, data *model.RolePermission) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockrolePermissionModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockrolePermissionModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockrolePermissionModel) Update(ctx context.Context, data *model.RolePermission) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockrolePermissionModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockrolePermissionModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/user_role_model.go b/internal/mock/model/user_role_model.go new file mode 100644 index 0000000..194927e --- /dev/null +++ b/internal/mock/model/user_role_model.go @@ -0,0 +1,115 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/user_role_model.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/user_role_model.go -destination=./internal/mock/model/user_role_model.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockUserRoleModel is a mock of UserRoleModel interface. +type MockUserRoleModel struct { + ctrl *gomock.Controller + recorder *MockUserRoleModelMockRecorder +} + +// MockUserRoleModelMockRecorder is the mock recorder for MockUserRoleModel. +type MockUserRoleModelMockRecorder struct { + mock *MockUserRoleModel +} + +// NewMockUserRoleModel creates a new mock instance. +func NewMockUserRoleModel(ctrl *gomock.Controller) *MockUserRoleModel { + mock := &MockUserRoleModel{ctrl: ctrl} + mock.recorder = &MockUserRoleModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockUserRoleModel) EXPECT() *MockUserRoleModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockUserRoleModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockUserRoleModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockUserRoleModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockUserRoleModel) FindOne(ctx context.Context, id int64) (*model.UserRole, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.UserRole) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockUserRoleModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockUserRoleModel)(nil).FindOne), ctx, id) +} + +// FindOneByUid mocks base method. +func (m *MockUserRoleModel) FindOneByUid(ctx context.Context, uid string) (*model.UserRole, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByUid", ctx, uid) + ret0, _ := ret[0].(*model.UserRole) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByUid indicates an expected call of FindOneByUid. +func (mr *MockUserRoleModelMockRecorder) FindOneByUid(ctx, uid any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByUid", reflect.TypeOf((*MockUserRoleModel)(nil).FindOneByUid), ctx, uid) +} + +// Insert mocks base method. +func (m *MockUserRoleModel) Insert(ctx context.Context, data *model.UserRole) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockUserRoleModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockUserRoleModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockUserRoleModel) Update(ctx context.Context, data *model.UserRole) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockUserRoleModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockUserRoleModel)(nil).Update), ctx, data) +} diff --git a/internal/mock/model/user_role_model_gen.go b/internal/mock/model/user_role_model_gen.go new file mode 100644 index 0000000..456c290 --- /dev/null +++ b/internal/mock/model/user_role_model_gen.go @@ -0,0 +1,115 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: ./internal/model/user_role_model_gen.go +// +// Generated by this command: +// +// mockgen -source=./internal/model/user_role_model_gen.go -destination=./internal/mock/model/user_role_model_gen.go -package=mock +// + +// Package mock is a generated GoMock package. +package mock + +import ( + model "app-cloudep-permission-server/internal/model" + context "context" + sql "database/sql" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockuserRoleModel is a mock of userRoleModel interface. +type MockuserRoleModel struct { + ctrl *gomock.Controller + recorder *MockuserRoleModelMockRecorder +} + +// MockuserRoleModelMockRecorder is the mock recorder for MockuserRoleModel. +type MockuserRoleModelMockRecorder struct { + mock *MockuserRoleModel +} + +// NewMockuserRoleModel creates a new mock instance. +func NewMockuserRoleModel(ctrl *gomock.Controller) *MockuserRoleModel { + mock := &MockuserRoleModel{ctrl: ctrl} + mock.recorder = &MockuserRoleModelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockuserRoleModel) EXPECT() *MockuserRoleModelMockRecorder { + return m.recorder +} + +// Delete mocks base method. +func (m *MockuserRoleModel) Delete(ctx context.Context, id int64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", ctx, id) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockuserRoleModelMockRecorder) Delete(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockuserRoleModel)(nil).Delete), ctx, id) +} + +// FindOne mocks base method. +func (m *MockuserRoleModel) FindOne(ctx context.Context, id int64) (*model.UserRole, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOne", ctx, id) + ret0, _ := ret[0].(*model.UserRole) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOne indicates an expected call of FindOne. +func (mr *MockuserRoleModelMockRecorder) FindOne(ctx, id any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOne", reflect.TypeOf((*MockuserRoleModel)(nil).FindOne), ctx, id) +} + +// FindOneByUid mocks base method. +func (m *MockuserRoleModel) FindOneByUid(ctx context.Context, uid string) (*model.UserRole, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindOneByUid", ctx, uid) + ret0, _ := ret[0].(*model.UserRole) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindOneByUid indicates an expected call of FindOneByUid. +func (mr *MockuserRoleModelMockRecorder) FindOneByUid(ctx, uid any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindOneByUid", reflect.TypeOf((*MockuserRoleModel)(nil).FindOneByUid), ctx, uid) +} + +// Insert mocks base method. +func (m *MockuserRoleModel) Insert(ctx context.Context, data *model.UserRole) (sql.Result, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Insert", ctx, data) + ret0, _ := ret[0].(sql.Result) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Insert indicates an expected call of Insert. +func (mr *MockuserRoleModelMockRecorder) Insert(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Insert", reflect.TypeOf((*MockuserRoleModel)(nil).Insert), ctx, data) +} + +// Update mocks base method. +func (m *MockuserRoleModel) Update(ctx context.Context, data *model.UserRole) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// Update indicates an expected call of Update. +func (mr *MockuserRoleModelMockRecorder) Update(ctx, data any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockuserRoleModel)(nil).Update), ctx, data) +} diff --git a/internal/model/permission_model.go b/internal/model/permission_model.go new file mode 100755 index 0000000..719486a --- /dev/null +++ b/internal/model/permission_model.go @@ -0,0 +1,27 @@ +package model + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlx" +) + +var _ PermissionModel = (*customPermissionModel)(nil) + +type ( + // PermissionModel is an interface to be customized, add more methods here, + // and implement the added methods in customPermissionModel. + PermissionModel interface { + permissionModel + } + + customPermissionModel struct { + *defaultPermissionModel + } +) + +// NewPermissionModel returns a model for the database table. +func NewPermissionModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) PermissionModel { + return &customPermissionModel{ + defaultPermissionModel: newPermissionModel(conn, c, opts...), + } +} diff --git a/internal/model/permission_model_gen.go b/internal/model/permission_model_gen.go new file mode 100755 index 0000000..74bd248 --- /dev/null +++ b/internal/model/permission_model_gen.go @@ -0,0 +1,157 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + permissionFieldNames = builder.RawFieldNames(&Permission{}) + permissionRows = strings.Join(permissionFieldNames, ",") + permissionRowsExpectAutoSet = strings.Join(stringx.Remove(permissionFieldNames, "`id`"), ",") + permissionRowsWithPlaceHolder = strings.Join(stringx.Remove(permissionFieldNames, "`id`"), "=?,") + "=?" + + cachePermissionIdPrefix = "cache:permission:id:" + cachePermissionNamePrefix = "cache:permission:name:" +) + +type ( + permissionModel interface { + Insert(ctx context.Context, data *Permission) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*Permission, error) + FindOneByName(ctx context.Context, name string) (*Permission, error) + Update(ctx context.Context, data *Permission) error + Delete(ctx context.Context, id int64) error + } + + defaultPermissionModel struct { + sqlc.CachedConn + table string + } + + Permission struct { + Id int64 `db:"id"` // PK + Parent sql.NullInt64 `db:"parent"` + Name string `db:"name"` + HttpMethod string `db:"http_method"` + HttpPath string `db:"http_path"` + Status int64 `db:"status"` // 狀態 1: 啟用, 2: 關閉 + Type int64 `db:"type"` // 狀態 1: 後台, 2: 前台 + CreateTime int64 `db:"create_time"` // 創建時間 + UpdateTime int64 `db:"update_time"` // 更新時間 + } +) + +func newPermissionModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultPermissionModel { + return &defaultPermissionModel{ + CachedConn: sqlc.NewConn(conn, c, opts...), + table: "`permission`", + } +} + +func (m *defaultPermissionModel) withSession(session sqlx.Session) *defaultPermissionModel { + return &defaultPermissionModel{ + CachedConn: m.CachedConn.WithSession(session), + table: "`permission`", + } +} + +func (m *defaultPermissionModel) Delete(ctx context.Context, id int64) error { + data, err := m.FindOne(ctx, id) + if err != nil { + return err + } + + permissionIdKey := fmt.Sprintf("%s%v", cachePermissionIdPrefix, id) + permissionNameKey := fmt.Sprintf("%s%v", cachePermissionNamePrefix, data.Name) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + return conn.ExecCtx(ctx, query, id) + }, permissionIdKey, permissionNameKey) + return err +} + +func (m *defaultPermissionModel) FindOne(ctx context.Context, id int64) (*Permission, error) { + permissionIdKey := fmt.Sprintf("%s%v", cachePermissionIdPrefix, id) + var resp Permission + err := m.QueryRowCtx(ctx, &resp, permissionIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", permissionRows, m.table) + return conn.QueryRowCtx(ctx, v, query, id) + }) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultPermissionModel) FindOneByName(ctx context.Context, name string) (*Permission, error) { + permissionNameKey := fmt.Sprintf("%s%v", cachePermissionNamePrefix, name) + var resp Permission + err := m.QueryRowIndexCtx(ctx, &resp, permissionNameKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) { + query := fmt.Sprintf("select %s from %s where `name` = ? limit 1", permissionRows, m.table) + if err := conn.QueryRowCtx(ctx, &resp, query, name); err != nil { + return nil, err + } + return resp.Id, nil + }, m.queryPrimary) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultPermissionModel) Insert(ctx context.Context, data *Permission) (sql.Result, error) { + permissionIdKey := fmt.Sprintf("%s%v", cachePermissionIdPrefix, data.Id) + permissionNameKey := fmt.Sprintf("%s%v", cachePermissionNamePrefix, data.Name) + ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?, ?, ?)", m.table, permissionRowsExpectAutoSet) + return conn.ExecCtx(ctx, query, data.Parent, data.Name, data.HttpMethod, data.HttpPath, data.Status, data.Type, data.CreateTime, data.UpdateTime) + }, permissionIdKey, permissionNameKey) + return ret, err +} + +func (m *defaultPermissionModel) Update(ctx context.Context, newData *Permission) error { + data, err := m.FindOne(ctx, newData.Id) + if err != nil { + return err + } + + permissionIdKey := fmt.Sprintf("%s%v", cachePermissionIdPrefix, data.Id) + permissionNameKey := fmt.Sprintf("%s%v", cachePermissionNamePrefix, data.Name) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, permissionRowsWithPlaceHolder) + return conn.ExecCtx(ctx, query, newData.Parent, newData.Name, newData.HttpMethod, newData.HttpPath, newData.Status, newData.Type, newData.CreateTime, newData.UpdateTime, newData.Id) + }, permissionIdKey, permissionNameKey) + return err +} + +func (m *defaultPermissionModel) formatPrimary(primary any) string { + return fmt.Sprintf("%s%v", cachePermissionIdPrefix, primary) +} + +func (m *defaultPermissionModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", permissionRows, m.table) + return conn.QueryRowCtx(ctx, v, query, primary) +} + +func (m *defaultPermissionModel) tableName() string { + return m.table +} diff --git a/internal/model/role_model.go b/internal/model/role_model.go new file mode 100755 index 0000000..7c4c733 --- /dev/null +++ b/internal/model/role_model.go @@ -0,0 +1,27 @@ +package model + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlx" +) + +var _ RoleModel = (*customRoleModel)(nil) + +type ( + // RoleModel is an interface to be customized, add more methods here, + // and implement the added methods in customRoleModel. + RoleModel interface { + roleModel + } + + customRoleModel struct { + *defaultRoleModel + } +) + +// NewRoleModel returns a model for the database table. +func NewRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) RoleModel { + return &customRoleModel{ + defaultRoleModel: newRoleModel(conn, c, opts...), + } +} diff --git a/internal/model/role_model_gen.go b/internal/model/role_model_gen.go new file mode 100755 index 0000000..681eb15 --- /dev/null +++ b/internal/model/role_model_gen.go @@ -0,0 +1,179 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + roleFieldNames = builder.RawFieldNames(&Role{}) + roleRows = strings.Join(roleFieldNames, ",") + roleRowsExpectAutoSet = strings.Join(stringx.Remove(roleFieldNames, "`id`"), ",") + roleRowsWithPlaceHolder = strings.Join(stringx.Remove(roleFieldNames, "`id`"), "=?,") + "=?" + + cacheRoleIdPrefix = "cache:role:id:" + cacheRoleDisplayNamePrefix = "cache:role:displayName:" + cacheRoleRoleIdPrefix = "cache:role:roleId:" +) + +type ( + roleModel interface { + Insert(ctx context.Context, data *Role) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*Role, error) + FindOneByDisplayName(ctx context.Context, displayName string) (*Role, error) + FindOneByRoleId(ctx context.Context, roleId string) (*Role, error) + Update(ctx context.Context, data *Role) error + Delete(ctx context.Context, id int64) error + } + + defaultRoleModel struct { + sqlc.CachedConn + table string + } + + Role struct { + Id int64 `db:"id"` // PK + RoleId string `db:"role_id"` + DisplayName string `db:"display_name"` // 名稱 + Status int64 `db:"status"` // 狀態 1: 啟用, 2: 禁用 + CreateTime int64 `db:"create_time"` // 創建時間 + UpdateTime int64 `db:"update_time"` // 更新時間 + } +) + +func newRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultRoleModel { + return &defaultRoleModel{ + CachedConn: sqlc.NewConn(conn, c, opts...), + table: "`role`", + } +} + +func (m *defaultRoleModel) withSession(session sqlx.Session) *defaultRoleModel { + return &defaultRoleModel{ + CachedConn: m.CachedConn.WithSession(session), + table: "`role`", + } +} + +func (m *defaultRoleModel) Delete(ctx context.Context, id int64) error { + data, err := m.FindOne(ctx, id) + if err != nil { + return err + } + + roleDisplayNameKey := fmt.Sprintf("%s%v", cacheRoleDisplayNamePrefix, data.DisplayName) + roleIdKey := fmt.Sprintf("%s%v", cacheRoleIdPrefix, id) + roleRoleIdKey := fmt.Sprintf("%s%v", cacheRoleRoleIdPrefix, data.RoleId) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + return conn.ExecCtx(ctx, query, id) + }, roleDisplayNameKey, roleIdKey, roleRoleIdKey) + return err +} + +func (m *defaultRoleModel) FindOne(ctx context.Context, id int64) (*Role, error) { + roleIdKey := fmt.Sprintf("%s%v", cacheRoleIdPrefix, id) + var resp Role + err := m.QueryRowCtx(ctx, &resp, roleIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table) + return conn.QueryRowCtx(ctx, v, query, id) + }) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultRoleModel) FindOneByDisplayName(ctx context.Context, displayName string) (*Role, error) { + roleDisplayNameKey := fmt.Sprintf("%s%v", cacheRoleDisplayNamePrefix, displayName) + var resp Role + err := m.QueryRowIndexCtx(ctx, &resp, roleDisplayNameKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) { + query := fmt.Sprintf("select %s from %s where `display_name` = ? limit 1", roleRows, m.table) + if err := conn.QueryRowCtx(ctx, &resp, query, displayName); err != nil { + return nil, err + } + return resp.Id, nil + }, m.queryPrimary) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultRoleModel) FindOneByRoleId(ctx context.Context, roleId string) (*Role, error) { + roleRoleIdKey := fmt.Sprintf("%s%v", cacheRoleRoleIdPrefix, roleId) + var resp Role + err := m.QueryRowIndexCtx(ctx, &resp, roleRoleIdKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) { + query := fmt.Sprintf("select %s from %s where `role_id` = ? limit 1", roleRows, m.table) + if err := conn.QueryRowCtx(ctx, &resp, query, roleId); err != nil { + return nil, err + } + return resp.Id, nil + }, m.queryPrimary) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultRoleModel) Insert(ctx context.Context, data *Role) (sql.Result, error) { + roleDisplayNameKey := fmt.Sprintf("%s%v", cacheRoleDisplayNamePrefix, data.DisplayName) + roleIdKey := fmt.Sprintf("%s%v", cacheRoleIdPrefix, data.Id) + roleRoleIdKey := fmt.Sprintf("%s%v", cacheRoleRoleIdPrefix, data.RoleId) + ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, roleRowsExpectAutoSet) + return conn.ExecCtx(ctx, query, data.RoleId, data.DisplayName, data.Status, data.CreateTime, data.UpdateTime) + }, roleDisplayNameKey, roleIdKey, roleRoleIdKey) + return ret, err +} + +func (m *defaultRoleModel) Update(ctx context.Context, newData *Role) error { + data, err := m.FindOne(ctx, newData.Id) + if err != nil { + return err + } + + roleDisplayNameKey := fmt.Sprintf("%s%v", cacheRoleDisplayNamePrefix, data.DisplayName) + roleIdKey := fmt.Sprintf("%s%v", cacheRoleIdPrefix, data.Id) + roleRoleIdKey := fmt.Sprintf("%s%v", cacheRoleRoleIdPrefix, data.RoleId) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, roleRowsWithPlaceHolder) + return conn.ExecCtx(ctx, query, newData.RoleId, newData.DisplayName, newData.Status, newData.CreateTime, newData.UpdateTime, newData.Id) + }, roleDisplayNameKey, roleIdKey, roleRoleIdKey) + return err +} + +func (m *defaultRoleModel) formatPrimary(primary any) string { + return fmt.Sprintf("%s%v", cacheRoleIdPrefix, primary) +} + +func (m *defaultRoleModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", roleRows, m.table) + return conn.QueryRowCtx(ctx, v, query, primary) +} + +func (m *defaultRoleModel) tableName() string { + return m.table +} diff --git a/internal/model/role_permission_model.go b/internal/model/role_permission_model.go new file mode 100755 index 0000000..d1d8e30 --- /dev/null +++ b/internal/model/role_permission_model.go @@ -0,0 +1,27 @@ +package model + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlx" +) + +var _ RolePermissionModel = (*customRolePermissionModel)(nil) + +type ( + // RolePermissionModel is an interface to be customized, add more methods here, + // and implement the added methods in customRolePermissionModel. + RolePermissionModel interface { + rolePermissionModel + } + + customRolePermissionModel struct { + *defaultRolePermissionModel + } +) + +// NewRolePermissionModel returns a model for the database table. +func NewRolePermissionModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) RolePermissionModel { + return &customRolePermissionModel{ + defaultRolePermissionModel: newRolePermissionModel(conn, c, opts...), + } +} diff --git a/internal/model/role_permission_model_gen.go b/internal/model/role_permission_model_gen.go new file mode 100755 index 0000000..1a0dabe --- /dev/null +++ b/internal/model/role_permission_model_gen.go @@ -0,0 +1,118 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + rolePermissionFieldNames = builder.RawFieldNames(&RolePermission{}) + rolePermissionRows = strings.Join(rolePermissionFieldNames, ",") + rolePermissionRowsExpectAutoSet = strings.Join(stringx.Remove(rolePermissionFieldNames, "`id`"), ",") + rolePermissionRowsWithPlaceHolder = strings.Join(stringx.Remove(rolePermissionFieldNames, "`id`"), "=?,") + "=?" + + cacheRolePermissionIdPrefix = "cache:rolePermission:id:" +) + +type ( + rolePermissionModel interface { + Insert(ctx context.Context, data *RolePermission) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*RolePermission, error) + Update(ctx context.Context, data *RolePermission) error + Delete(ctx context.Context, id int64) error + } + + defaultRolePermissionModel struct { + sqlc.CachedConn + table string + } + + RolePermission struct { + Id int64 `db:"id"` // PK + RoleId sql.NullInt64 `db:"role_id"` // role.id + PermissionId sql.NullInt64 `db:"permission_id"` // permission.id + CreateTime int64 `db:"create_time"` // 創建時間 + UpdateTime int64 `db:"update_time"` // 更新時間 + } +) + +func newRolePermissionModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultRolePermissionModel { + return &defaultRolePermissionModel{ + CachedConn: sqlc.NewConn(conn, c, opts...), + table: "`role_permission`", + } +} + +func (m *defaultRolePermissionModel) withSession(session sqlx.Session) *defaultRolePermissionModel { + return &defaultRolePermissionModel{ + CachedConn: m.CachedConn.WithSession(session), + table: "`role_permission`", + } +} + +func (m *defaultRolePermissionModel) Delete(ctx context.Context, id int64) error { + rolePermissionIdKey := fmt.Sprintf("%s%v", cacheRolePermissionIdPrefix, id) + _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + return conn.ExecCtx(ctx, query, id) + }, rolePermissionIdKey) + return err +} + +func (m *defaultRolePermissionModel) FindOne(ctx context.Context, id int64) (*RolePermission, error) { + rolePermissionIdKey := fmt.Sprintf("%s%v", cacheRolePermissionIdPrefix, id) + var resp RolePermission + err := m.QueryRowCtx(ctx, &resp, rolePermissionIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", rolePermissionRows, m.table) + return conn.QueryRowCtx(ctx, v, query, id) + }) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultRolePermissionModel) Insert(ctx context.Context, data *RolePermission) (sql.Result, error) { + rolePermissionIdKey := fmt.Sprintf("%s%v", cacheRolePermissionIdPrefix, data.Id) + ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?)", m.table, rolePermissionRowsExpectAutoSet) + return conn.ExecCtx(ctx, query, data.RoleId, data.PermissionId, data.CreateTime, data.UpdateTime) + }, rolePermissionIdKey) + return ret, err +} + +func (m *defaultRolePermissionModel) Update(ctx context.Context, data *RolePermission) error { + rolePermissionIdKey := fmt.Sprintf("%s%v", cacheRolePermissionIdPrefix, data.Id) + _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, rolePermissionRowsWithPlaceHolder) + return conn.ExecCtx(ctx, query, data.RoleId, data.PermissionId, data.CreateTime, data.UpdateTime, data.Id) + }, rolePermissionIdKey) + return err +} + +func (m *defaultRolePermissionModel) formatPrimary(primary any) string { + return fmt.Sprintf("%s%v", cacheRolePermissionIdPrefix, primary) +} + +func (m *defaultRolePermissionModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", rolePermissionRows, m.table) + return conn.QueryRowCtx(ctx, v, query, primary) +} + +func (m *defaultRolePermissionModel) tableName() string { + return m.table +} diff --git a/internal/model/user_role_model.go b/internal/model/user_role_model.go new file mode 100755 index 0000000..4f2427f --- /dev/null +++ b/internal/model/user_role_model.go @@ -0,0 +1,27 @@ +package model + +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlx" +) + +var _ UserRoleModel = (*customUserRoleModel)(nil) + +type ( + // UserRoleModel is an interface to be customized, add more methods here, + // and implement the added methods in customUserRoleModel. + UserRoleModel interface { + userRoleModel + } + + customUserRoleModel struct { + *defaultUserRoleModel + } +) + +// NewUserRoleModel returns a model for the database table. +func NewUserRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserRoleModel { + return &customUserRoleModel{ + defaultUserRoleModel: newUserRoleModel(conn, c, opts...), + } +} diff --git a/internal/model/user_role_model_gen.go b/internal/model/user_role_model_gen.go new file mode 100755 index 0000000..1a4698d --- /dev/null +++ b/internal/model/user_role_model_gen.go @@ -0,0 +1,155 @@ +// Code generated by goctl. DO NOT EDIT. + +package model + +import ( + "context" + "database/sql" + "fmt" + "strings" + + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) + +var ( + userRoleFieldNames = builder.RawFieldNames(&UserRole{}) + userRoleRows = strings.Join(userRoleFieldNames, ",") + userRoleRowsExpectAutoSet = strings.Join(stringx.Remove(userRoleFieldNames, "`id`"), ",") + userRoleRowsWithPlaceHolder = strings.Join(stringx.Remove(userRoleFieldNames, "`id`"), "=?,") + "=?" + + cacheUserRoleIdPrefix = "cache:userRole:id:" + cacheUserRoleUidPrefix = "cache:userRole:uid:" +) + +type ( + userRoleModel interface { + Insert(ctx context.Context, data *UserRole) (sql.Result, error) + FindOne(ctx context.Context, id int64) (*UserRole, error) + FindOneByUid(ctx context.Context, uid string) (*UserRole, error) + Update(ctx context.Context, data *UserRole) error + Delete(ctx context.Context, id int64) error + } + + defaultUserRoleModel struct { + sqlc.CachedConn + table string + } + + UserRole struct { + Id int64 `db:"id"` // PK + Brand string `db:"brand"` + Uid string `db:"uid"` + RoleId string `db:"role_id"` + Status int64 `db:"status"` // 狀態 1: 啟用, 2: 禁用 + CreateTime int64 `db:"create_time"` // 創建時間 + UpdateTime int64 `db:"update_time"` // 更新時間 + } +) + +func newUserRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultUserRoleModel { + return &defaultUserRoleModel{ + CachedConn: sqlc.NewConn(conn, c, opts...), + table: "`user_role`", + } +} + +func (m *defaultUserRoleModel) withSession(session sqlx.Session) *defaultUserRoleModel { + return &defaultUserRoleModel{ + CachedConn: m.CachedConn.WithSession(session), + table: "`user_role`", + } +} + +func (m *defaultUserRoleModel) Delete(ctx context.Context, id int64) error { + data, err := m.FindOne(ctx, id) + if err != nil { + return err + } + + userRoleIdKey := fmt.Sprintf("%s%v", cacheUserRoleIdPrefix, id) + userRoleUidKey := fmt.Sprintf("%s%v", cacheUserRoleUidPrefix, data.Uid) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("delete from %s where `id` = ?", m.table) + return conn.ExecCtx(ctx, query, id) + }, userRoleIdKey, userRoleUidKey) + return err +} + +func (m *defaultUserRoleModel) FindOne(ctx context.Context, id int64) (*UserRole, error) { + userRoleIdKey := fmt.Sprintf("%s%v", cacheUserRoleIdPrefix, id) + var resp UserRole + err := m.QueryRowCtx(ctx, &resp, userRoleIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table) + return conn.QueryRowCtx(ctx, v, query, id) + }) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultUserRoleModel) FindOneByUid(ctx context.Context, uid string) (*UserRole, error) { + userRoleUidKey := fmt.Sprintf("%s%v", cacheUserRoleUidPrefix, uid) + var resp UserRole + err := m.QueryRowIndexCtx(ctx, &resp, userRoleUidKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) { + query := fmt.Sprintf("select %s from %s where `uid` = ? limit 1", userRoleRows, m.table) + if err := conn.QueryRowCtx(ctx, &resp, query, uid); err != nil { + return nil, err + } + return resp.Id, nil + }, m.queryPrimary) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *defaultUserRoleModel) Insert(ctx context.Context, data *UserRole) (sql.Result, error) { + userRoleIdKey := fmt.Sprintf("%s%v", cacheUserRoleIdPrefix, data.Id) + userRoleUidKey := fmt.Sprintf("%s%v", cacheUserRoleUidPrefix, data.Uid) + ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?, ?)", m.table, userRoleRowsExpectAutoSet) + return conn.ExecCtx(ctx, query, data.Brand, data.Uid, data.RoleId, data.Status, data.CreateTime, data.UpdateTime) + }, userRoleIdKey, userRoleUidKey) + return ret, err +} + +func (m *defaultUserRoleModel) Update(ctx context.Context, newData *UserRole) error { + data, err := m.FindOne(ctx, newData.Id) + if err != nil { + return err + } + + userRoleIdKey := fmt.Sprintf("%s%v", cacheUserRoleIdPrefix, data.Id) + userRoleUidKey := fmt.Sprintf("%s%v", cacheUserRoleUidPrefix, data.Uid) + _, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, userRoleRowsWithPlaceHolder) + return conn.ExecCtx(ctx, query, newData.Brand, newData.Uid, newData.RoleId, newData.Status, newData.CreateTime, newData.UpdateTime, newData.Id) + }, userRoleIdKey, userRoleUidKey) + return err +} + +func (m *defaultUserRoleModel) formatPrimary(primary any) string { + return fmt.Sprintf("%s%v", cacheUserRoleIdPrefix, primary) +} + +func (m *defaultUserRoleModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error { + query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", userRoleRows, m.table) + return conn.QueryRowCtx(ctx, v, query, primary) +} + +func (m *defaultUserRoleModel) tableName() string { + return m.table +} diff --git a/internal/model/vars.go b/internal/model/vars.go new file mode 100644 index 0000000..69ca814 --- /dev/null +++ b/internal/model/vars.go @@ -0,0 +1,5 @@ +package model + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var ErrNotFound = sqlx.ErrNotFound diff --git a/internal/server/tokenservice/token_service_server.go b/internal/server/tokenservice/token_service_server.go new file mode 100644 index 0000000..0ad10aa --- /dev/null +++ b/internal/server/tokenservice/token_service_server.go @@ -0,0 +1,83 @@ +// Code generated by goctl. DO NOT EDIT. +// Source: service.proto + +package server + +import ( + "context" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/logic/tokenservice" + "app-cloudep-permission-server/internal/svc" +) + +type TokenServiceServer struct { + svcCtx *svc.ServiceContext + permission.UnimplementedTokenServiceServer +} + +func NewTokenServiceServer(svcCtx *svc.ServiceContext) *TokenServiceServer { + return &TokenServiceServer{ + svcCtx: svcCtx, + } +} + +// NewToken 建立一個新的 Token,例如:AccessToken +func (s *TokenServiceServer) NewToken(ctx context.Context, in *permission.AuthorizationReq) (*permission.TokenResp, error) { + l := tokenservicelogic.NewNewTokenLogic(ctx, s.svcCtx) + return l.NewToken(in) +} + +// RefreshToken 更新目前的token 以及裡面包含的一次性 Token +func (s *TokenServiceServer) RefreshToken(ctx context.Context, in *permission.RefreshTokenReq) (*permission.RefreshTokenResp, error) { + l := tokenservicelogic.NewRefreshTokenLogic(ctx, s.svcCtx) + return l.RefreshToken(in) +} + +// CancelToken 取消 Token,也包含他裡面的 One Time Toke +func (s *TokenServiceServer) CancelToken(ctx context.Context, in *permission.CancelTokenReq) (*permission.OKResp, error) { + l := tokenservicelogic.NewCancelTokenLogic(ctx, s.svcCtx) + return l.CancelToken(in) +} + +// ValidationToken 驗證這個 Token 有沒有效 +func (s *TokenServiceServer) ValidationToken(ctx context.Context, in *permission.ValidationTokenReq) (*permission.ValidationTokenResp, error) { + l := tokenservicelogic.NewValidationTokenLogic(ctx, s.svcCtx) + return l.ValidationToken(in) +} + +// CancelTokens 取消 Token 從UID 視角,以及 token id 視角出發, UID 登出,底下所有 Device ID 也要登出, Token ID 登出, 所有 UID + Device 都要登出 +func (s *TokenServiceServer) CancelTokens(ctx context.Context, in *permission.DoTokenByUIDReq) (*permission.OKResp, error) { + l := tokenservicelogic.NewCancelTokensLogic(ctx, s.svcCtx) + return l.CancelTokens(in) +} + +// CancelTokenByDeviceId 取消 Token, 從 Device 視角出發,可以選,登出這個Device 下所有 token ,登出這個Device 下指定token +func (s *TokenServiceServer) CancelTokenByDeviceId(ctx context.Context, in *permission.DoTokenByDeviceIDReq) (*permission.OKResp, error) { + l := tokenservicelogic.NewCancelTokenByDeviceIdLogic(ctx, s.svcCtx) + return l.CancelTokenByDeviceId(in) +} + +// GetUserTokensByDeviceId 取得目前所對應的 DeviceID 所存在的 Tokens +func (s *TokenServiceServer) GetUserTokensByDeviceId(ctx context.Context, in *permission.DoTokenByDeviceIDReq) (*permission.Tokens, error) { + l := tokenservicelogic.NewGetUserTokensByDeviceIdLogic(ctx, s.svcCtx) + return l.GetUserTokensByDeviceId(in) +} + +// GetUserTokensByUid 取得目前所對應的 UID 所存在的 Tokens +func (s *TokenServiceServer) GetUserTokensByUid(ctx context.Context, in *permission.QueryTokenByUIDReq) (*permission.Tokens, error) { + l := tokenservicelogic.NewGetUserTokensByUidLogic(ctx, s.svcCtx) + return l.GetUserTokensByUid(in) +} + +// NewOneTimeToken 建立一次性使用,例如:RefreshToken +func (s *TokenServiceServer) NewOneTimeToken(ctx context.Context, in *permission.CreateOneTimeTokenReq) (*permission.CreateOneTimeTokenResp, error) { + l := tokenservicelogic.NewNewOneTimeTokenLogic(ctx, s.svcCtx) + return l.NewOneTimeToken(in) +} + +// CancelOneTimeToken 取消一次性使用 +func (s *TokenServiceServer) CancelOneTimeToken(ctx context.Context, in *permission.CancelOneTimeTokenReq) (*permission.OKResp, error) { + l := tokenservicelogic.NewCancelOneTimeTokenLogic(ctx, s.svcCtx) + return l.CancelOneTimeToken(in) +} diff --git a/internal/svc/service_context.go b/internal/svc/service_context.go new file mode 100644 index 0000000..c12077a --- /dev/null +++ b/internal/svc/service_context.go @@ -0,0 +1,13 @@ +package svc + +import "app-cloudep-permission-server/internal/config" + +type ServiceContext struct { + Config config.Config +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config: c, + } +} diff --git a/service.go b/service.go new file mode 100644 index 0000000..54b770a --- /dev/null +++ b/service.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + + "app-cloudep-permission-server/gen_result/pb/permission" + "app-cloudep-permission-server/internal/config" + tokenserviceServer "app-cloudep-permission-server/internal/server/tokenservice" + "app-cloudep-permission-server/internal/svc" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/core/service" + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" +) + +var configFile = flag.String("f", "etc/service.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + ctx := svc.NewServiceContext(c) + + s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { + permission.RegisterTokenServiceServer(grpcServer, tokenserviceServer.NewTokenServiceServer(ctx)) + + if c.Mode == service.DevMode || c.Mode == service.TestMode { + reflection.Register(grpcServer) + } + }) + defer s.Stop() + + fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) + s.Start() +}