Compare commits

...

2338 Commits

Author SHA1 Message Date
7c38a99973 fix(ci): исправить путь container registry
All checks were successful
Build & Push Docker Image / build (push) Successful in 2m15s
- исправлен путь образа на gromov/casdoor
2026-04-11 19:42:25 +03:00
7c26dbb7d0 fix(ci): убрать тест версии из Dockerfile
Some checks failed
Build & Push Docker Image / build (push) Failing after 6m15s
- удалён TestGetVersionInfo, падает без .git в контейнере
2026-04-11 19:32:22 +03:00
61bc75b12e chore(ci): добавить ручной запуск workflow
Some checks failed
Build & Push Docker Image / build (push) Failing after 2m5s
- добавлен workflow_dispatch для ручного запуска сборки
2026-04-11 19:26:23 +03:00
18a8694d28 chore(ci): добавить Gitea Actions для сборки Docker-образа
- добавлен workflow сборки и пуша в container registry
- сборка при пуше в ветку custom
- target STANDARD (Alpine)
2026-04-11 19:19:01 +03:00
8478543c6b feat(i18n): добавить русский язык и конфигурацию разработки
- добавлен русский перевод интерфейса (web/src/locales/ru)
- восстановлен русский перевод бэкенда из Crowdin (i18n/locales/ru)
- добавлен ru в список языков организации
- добавлен Русский в селект языков
- добавлена конфигурация для локальной разработки (PostgreSQL, порт 5434)
- добавлен docker-compose.dev.yml
2026-04-11 19:11:15 +03:00
Yang Luo
25d8595e66 fix: improve top-left logo position 2026-04-11 22:33:20 +08:00
Yang Luo
3aafa91937 fix: improve hosting badge position and UI 2026-04-11 22:23:46 +08:00
Yang Luo
0077839549 fix: hide global scrollbar 2026-04-11 22:07:54 +08:00
Yang Luo
e1ee2ddee8 fix: add margin to 3 store pages 2026-04-11 22:02:05 +08:00
Yang Luo
b93be2d3e2 fix: add top breadcrumb bar 2026-04-11 21:53:57 +08:00
Yang Luo
77b56a2e40 fix: increase left sidebar width 2026-04-11 21:48:13 +08:00
Yang Luo
c0591f316e fix: increase org-select's width 2026-04-11 21:43:56 +08:00
Yang Luo
6749d46561 fix: improve top-left logo position 2026-04-11 21:42:21 +08:00
Yang Luo
a4a50f182b fix: hide left sidebar's scrollbar 2026-04-11 21:21:11 +08:00
Yang Luo
221d10a172 fix: fix Can't resolve 'rc-util/es/isEqual' bug 2026-04-11 20:46:34 +08:00
Yang Luo
5c051ba03d feat: improve table column width
BREAKING CHANGE: major release
2026-04-11 19:08:54 +08:00
Yang Luo
c16f4d2fb5 fix: improve xxx list page table's column row height 2026-04-11 19:01:28 +08:00
Yang Luo
fe185f880c fix: improve i18n keys 2026-04-11 19:00:45 +08:00
Yang Luo
b3bed1992b fix: improve "Loading" position 2026-04-11 18:54:05 +08:00
Yang Luo
be38d178fd fix: increase org-select's width 2026-04-11 18:50:19 +08:00
Yang Luo
3eb164e149 fix: add left margin to top-right user avatar 2026-04-11 18:46:47 +08:00
Yang Luo
6c3cd8a74b fix: set Sidebar menu: selected item - darker background 2026-04-11 18:43:10 +08:00
Yang Luo
c5ab4eec59 fix: fix top-left logo missing bug 2026-04-11 18:41:20 +08:00
Yang Luo
e8170884d7 fix: improve record and session list page UI 2026-04-11 18:40:22 +08:00
Yang Luo
729b21e8ae fix: use Apple Inter font 2026-04-11 18:32:36 +08:00
Yang Luo
bed67a1ff2 fix: improve top-left menu text 2026-04-11 18:21:29 +08:00
Yang Luo
df5f5def31 fix: improve list page's table title bar height 2026-04-11 18:10:29 +08:00
Yang Luo
76c56e9b2d fix: fix top-left menu highlight 2026-04-11 18:09:27 +08:00
Yang Luo
f46e229d5b fix: improve top-left logo 2026-04-11 17:50:25 +08:00
Yang Luo
112be9714b fix: reduce content area margin 2026-04-11 17:47:46 +08:00
Yang Luo
9d85362a24 fix: reduce top bar height 2026-04-11 17:43:03 +08:00
Yang Luo
37e2f13d99 feat: change to left sidebar 2026-04-11 17:32:13 +08:00
Yang Luo
f35398ea5c fix: use outlined icons in top navbar 2026-04-11 17:19:09 +08:00
Yang Luo
5a5470d5a3 fix: use shadcn theme by default 2026-04-11 17:15:35 +08:00
Yang Luo
948fc017e1 fix: improve i18n data 2026-04-11 17:01:26 +08:00
Yang Luo
c63184fc67 feat: upgrade to Antd 6.3.5 2026-04-11 16:53:23 +08:00
Yang Luo
f5f4032b3b fix: fix code format 2026-04-11 11:02:59 +08:00
Yang Luo
7006041fa9 fix: remove OpenClaw session heartbeat logs 2026-04-11 10:54:59 +08:00
Yang Luo
d7bc2bf052 feat: add support for OAuth 2.0 DPoP (Demonstrating Proof of Possession) 2026-04-11 10:45:33 +08:00
Yang Luo
29eeb03f85 fix: refactor out token_oauth_util.go 2026-04-11 10:19:04 +08:00
Yang Luo
14b4b557f9 feat: support user's accessKey in auto signin filter 2026-04-11 01:07:36 +08:00
Yang Luo
49d35ac161 feat: add Provider.CustomLogoutUrl field 2026-04-11 01:01:58 +08:00
Yang Luo
5ed9158368 fix: improve GetSortedUsers code 2026-04-11 00:58:40 +08:00
Yang Luo
2bb728ad7d feat: fix wrong verb sent in oauth state (signup instead of signin) 2026-04-11 00:42:57 +08:00
nkanf-dev
f4665df477 fix: fix checking shared-app login permission in user organization (#5381) 2026-04-11 00:09:59 +08:00
Paperlz
12bbecb69d feat: build OpenClaw session graphs from DB entries (#5382) 2026-04-11 00:02:04 +08:00
Yang Luo
a5079cd0c5 feat: fix UpdatePolicy/UpdatePolicies APIs for empty field update 2026-04-09 01:00:02 +08:00
Yang Luo
e361044f86 fix: add RequestBodyFilter to fix POST body JSON error without Content-Type issue 2026-04-09 00:35:05 +08:00
Yang Luo
91cdf56636 feat: Enable ABAC support in /api/enforce and /api/batch-enforce 2026-04-09 00:32:48 +08:00
Yang Luo
10daed237e feat: improve objOwner check 2026-04-08 23:17:54 +08:00
cooronx
315a6bb040 feat: deduplicate permission RBAC by building grouping policies in run time (#5374) 2026-04-08 23:01:00 +08:00
Yang Luo
cef6b85389 feat: failed HTTP Basic Authentication won't trigger error now 2026-04-08 22:59:52 +08:00
Yang Luo
14a802f2c5 fix: fix add-new logic for provider 2026-04-08 22:18:44 +08:00
Yang Luo
40d1f63cd6 fix: don't collect OpenClaw metrics entries for now 2026-04-08 19:23:14 +08:00
Yang Luo
85c91c50d3 fix: add provider.State to log providers 2026-04-08 09:52:45 +08:00
Yang Luo
0e5f810f2f feat: fix "sqlite3" driverName to "sqlite" 2026-04-08 09:27:16 +08:00
asuka
e9c2ec0d6c fix: fix authz permission for well-known OAuth endpoints (#5372) 2026-04-07 22:38:12 +08:00
Paperlz
2a8ac578da feat: add local OpenClaw transcript sync for session logs (#5370) 2026-04-07 22:34:55 +08:00
DacongDA
31ce1512df feat: apply loginPage captcha rule check to SendCodeInput.js (#5369) 2026-04-06 17:54:27 +08:00
Yang Luo
bac824cb4f feat: improve filter check 2026-04-06 12:26:29 +08:00
DacongDA
1637ca1dfb feat: support GET request in MCP SSE (#5363) 2026-04-06 10:35:49 +08:00
Paperlz
c7ad2052c9 feat: add provider-based entry viewers for SELinux logs (#5364) 2026-04-06 00:59:32 +08:00
Yang Luo
117bf608ea fix: include xs namespace in C14N10 exclusive canonicalization prefix list 2026-04-05 21:09:54 +08:00
DacongDA
13e0af4b0a feat: switch server source to "https://mcp.casdoor.org/registry.json" (#5366) 2026-04-05 20:57:03 +08:00
Yang Luo
e8a0b268dc feat: add redirectUriMatchesPattern() 2026-04-05 20:38:12 +08:00
Yang Luo
2762390c32 fix: add Clear button to MCP server edit page 2026-04-05 17:54:27 +08:00
cooronx
a69c4454ca feat: add back buy-product API for compatibility (#5362) 2026-04-05 17:41:15 +08:00
Paperlz
c76d0d17ed fix: use SELinux collector for SELinux log providers (#5361) 2026-04-05 16:55:55 +08:00
Yang Luo
e10706cb6d fix: fix linter in saml_sp.go 2026-04-05 15:43:03 +08:00
Yang Luo
d92b856868 feat: add parseAndValidateSubjectToken() 2026-04-05 15:32:38 +08:00
Yang Luo
d14674e60e fix: improve buildSpCertificateStore logic 2026-04-05 15:22:09 +08:00
DacongDA
284dde292a feat: add Sync button to sync tools in MCP server edit page (#5360) 2026-04-05 15:09:39 +08:00
Yang Luo
ea56cfec2b fix: improve IsRedirectUriValid logic 2026-04-05 15:00:00 +08:00
Yang Luo
82d7f241bb fix: refactor out application_util.go 2026-04-05 14:56:24 +08:00
Yang Luo
56ac5cd221 feat: add Application.EnableGuestSignin field 2026-04-05 14:28:53 +08:00
Yang Luo
203a61cfef feat: improve GetOAuthToken logic 2026-04-05 14:22:09 +08:00
Yang Luo
b9500a27d9 fix: improve buildAuthFilterString logic 2026-04-05 10:19:19 +08:00
Yang Luo
c979a05c25 fix: fix bug in responseOtlpError() 2026-04-05 09:44:45 +08:00
Yang Luo
1e7a2d8dad fix: improve random handling 2026-04-05 09:42:52 +08:00
Yang Luo
f6a3fb9455 feat: improve error handling in OLTP APIs 2026-04-05 02:50:12 +08:00
Yang Luo
9030a06792 fix: add client IP and UA to entry 2026-04-05 02:08:45 +08:00
Yang Luo
fffb26deb9 fix: remove entry's useless fields 2026-04-05 01:59:32 +08:00
Yang Luo
fab57364db fix: refactor out log/agent_openclaw.go 2026-04-05 01:52:25 +08:00
Yang Luo
e73cfe8b40 fix: fix go linter issue 2026-04-05 00:18:31 +08:00
Yang Luo
facc1ec203 feat: support "/api/v1/metrics" and "/api/v1/logs" APIs from OpenClaw 2026-04-05 00:13:37 +08:00
Yang Luo
6cb9978475 feat: add SELinuxLogProvider 2026-04-04 23:48:56 +08:00
Yang Luo
f75cee76ae fix: set empty providerUrl in new provider 2026-04-04 23:43:43 +08:00
Yang Luo
c92e553e9b fix: fix provider_log_system_log's wrong provider field 2026-04-04 23:36:06 +08:00
Yang Luo
a824fc0f3c fix: improve getAutoProviderName with subtype 2026-04-04 23:36:06 +08:00
Yang Luo
98dea3a15a fix: add provider_log_agent_openclaw and IP check 2026-04-04 23:36:06 +08:00
DacongDA
c0d3fdf812 feat: can scan intranet MCP servers (#5359) 2026-04-04 23:25:13 +08:00
Yang Luo
1c60a4ddfa fix: fix parseAndPersistEvents() code in Windows system log provider 2026-04-04 23:06:51 +08:00
Yang Luo
ac43fb9cac fix: fix system log provider code 2026-04-04 22:46:19 +08:00
Yang Luo
2f7e6c1cc2 fix: refactor system log provider 2026-04-04 22:11:47 +08:00
Yang Luo
28b76cce76 fix: improve entry list page UI again 2026-04-04 22:03:54 +08:00
Yang Luo
319896267e fix: improve entry list page UI 2026-04-04 21:51:38 +08:00
Yang Luo
a3698024bc fix: fix writePermissionLog() hook position 2026-04-04 21:33:48 +08:00
Yang Luo
8ffca95c59 fix: add "Casdoor Permission Log" option to frontend 2026-04-04 21:03:03 +08:00
Yang Luo
4f68432349 feat: auto set name and display name for new provider 2026-04-04 21:00:52 +08:00
Yang Luo
17a52da2b8 fix: add Entry.Provider field 2026-04-04 21:00:52 +08:00
Yang Luo
5140053083 fix: add "Casdoor Permission Log" provider 2026-04-04 20:59:21 +08:00
Yang Luo
9b86530763 fix: rename to log package 2026-04-04 20:59:21 +08:00
Yang Luo
84f289ddc4 fix: ignore claude config 2026-04-04 20:59:20 +08:00
Modo
23cdb279e6 feat: add EntryMessageViewer (#5357) 2026-04-04 16:48:00 +08:00
Yang Luo
ea2408a7d2 feat: improve permission command API 2026-04-04 01:30:14 +08:00
Yang Luo
4ccb28571b fix: improve value in GetSession() 2026-04-04 01:15:29 +08:00
Yang Luo
1439031780 feat: add LogProvider interface 2026-04-03 01:33:15 +08:00
Modo
2ebe3f1d5d feat: add "/api/v1/traces" API to receive OpenClaw's OpenTelemetry metric (#5349) 2026-04-01 12:13:44 +08:00
Paperlz
0ff862dbc5 feat: enhance webhook worker reliability and event pagination (#5344) 2026-03-31 09:51:24 +08:00
DacongDA
bb11511029 feat: add MCP store page (#5343) 2026-03-31 09:49:49 +08:00
Yang Luo
18979caea4 feat: add Entry list and edit pages 2026-03-31 00:25:44 +08:00
Yang Luo
a61575f9d1 fix: improve menu for LLM AI 2026-03-30 23:26:37 +08:00
Paperlz
863d86d55f feat: add webhook delivery persistence, retry mechanism and replay UI (#5337) 2026-03-30 22:53:56 +08:00
Modo
b690ee4ea3 feat: add Agent list and edit pages (#5338) 2026-03-30 09:10:18 +08:00
ANormalDD
5b58d8bf16 feat: move configs of defaultApplication and maxItemsForFlatMenu to backend app.conf (#5325) 2026-03-28 12:27:53 +08:00
Yijun Gao
e5d2feb73d feat: add disk and network usage to system info page with improved layout (#5304) 2026-03-27 21:39:23 +08:00
Yang Luo
96359f78c5 feat: add CheckVerifyCodeWithLimitAndIp() 2026-03-26 23:02:11 +08:00
Stephane P. Pericat
6f18f67138 feat: upgrade Go toolchain to 1.25.8 (#5328) 2026-03-26 00:51:27 +08:00
Yang Luo
9038d8ab5b fix: improve LDAP handling for "(uid={})" filter 2026-03-25 22:40:27 +08:00
Yang Luo
b396a69ed7 fix: fix go.sum 2026-03-24 23:26:52 +08:00
Chlx
189277f9a2 feat: add Antd Select component for language selection (#5319) 2026-03-24 23:23:12 +08:00
Yang Luo
655777f0f1 feat: upgrade grpc dependency (#5318) 2026-03-24 22:12:48 +08:00
Yang Luo
fb0b93873c feat: fix 100% CPU/memory usage displaying as green success state on System Info page (#5306) 2026-03-23 21:28:13 +08:00
DacongDA
f5af87683d feat: can sync MCP tools and set "is allowed" for MCP tool (#5301) 2026-03-23 11:47:06 +08:00
DacongDA
df47f5785c fix: rename mcp package to mcpself (#5302) 2026-03-23 10:59:10 +08:00
ANormalDD
4879926977 fix: remove old use keys (#5299) 2026-03-22 14:40:14 +08:00
ANormalDD
7148c9db85 fix: check owner in UpdateKey() API (#5297) 2026-03-22 12:50:03 +08:00
Modo
29dccbe32f feat: preserve RFC 8707 resource across browser login flow (#5298) 2026-03-22 09:30:59 +08:00
Br1an
65755d3b28 feat: redirect to account page for forced password change (#5181) 2026-03-22 00:55:58 +08:00
Yang Luo
239e8bd694 feat: add key list/edit pages (#5285) 2026-03-21 20:06:06 +08:00
Modo
d23e8b205b feat: add permanent avatar switch to organization settings (#5295) 2026-03-21 09:21:11 +08:00
ANormalDD
1260db8c27 feat: remove Casvisor dependency and use local Record struct (#5287) 2026-03-19 22:48:06 +08:00
DacongDA
1506a5c895 feat: add MCP server list/edit pages (#5278) 2026-03-18 22:43:45 +08:00
ANormalDD
7b5f4aefab feat: use backend config app.conf instead of frontend config (#5279) 2026-03-18 21:37:46 +08:00
Modo
75bc8e6b0d feat: wrap xorm-adapter RemovePolicy to prevent mass deletion on empty fields (#5282) 2026-03-18 17:32:31 +08:00
Yang Luo
5965e75610 fix: add missing swagger annotations to rule and site APIs (#5281) 2026-03-18 17:31:05 +08:00
Modo
899c2546cf feat: fix last element not visible in Edit Application form tabs (#5275) 2026-03-17 20:41:34 +08:00
Yang Luo
95defad3b1 feat: fix OAuth state parameter re-encoding in redirect URL to prevent OIDC state mismatch (#5262) 2026-03-17 20:41:03 +08:00
Yang Luo
6a263cb5cb feat: fix LDAP sync crash on large user sets due to PostgreSQL parameter limit (#5268) 2026-03-14 23:07:22 +08:00
ANormalDD
54d6a59cb6 feat: add rate limiting to /api/verify-code OTP endpoint (#5270) 2026-03-14 23:01:52 +08:00
DacongDA
2693c07b3c feat: only init site map when proxy server is started (#5265) 2026-03-13 00:27:16 +08:00
Yang Luo
2895c72d32 fix: improve Actions field UI in permission list page 2026-03-11 21:43:32 +08:00
ANormalDD
f6129b09c8 feat: implement minimal HTML+JS OAuth callback and provider_hint flows (#5238) 2026-03-10 19:04:55 +08:00
Yang Luo
0bbbb48af1 feat: upgrade to golang:1.24.13 and node:20.20.1 (LTS), update Dockerfile base images (#5246) 2026-03-10 18:12:12 +08:00
gaël Prudhomme
34a8b252d5 feat: fix bug in site's owner/organization (#5239) 2026-03-09 23:55:41 +08:00
DacongDA
c756e56f74 feat: fix proxy server panic issue if port has been used (#5240) 2026-03-09 22:16:58 +08:00
DacongDA
dbc2a676ba feat: allow user to set binding rule in provider items (#5224) 2026-03-07 22:20:48 +08:00
Yang Luo
74e6b73e7b feat: fix empty "Binding providers" prompt step appearing after signup (#5221) 2026-03-07 17:41:24 +08:00
Yang Luo
07de8a40d6 feat: fix invitation code lost during signup when form field is not visible (#5231) 2026-03-07 15:35:47 +08:00
ANormalDD
c6a6ec8869 feat: fix bug that invitation links fail with external OAuth providers (#5229) 2026-03-07 14:45:22 +08:00
Yang Luo
394b3e1372 feat: add Kerberos/SPNEGO authentication (#5225) 2026-03-07 09:46:45 +08:00
Yang Luo
fa93d4eb8b feat: add LDAP server attribute filtering per organization (#5222) 2026-03-07 00:53:20 +08:00
Yang Luo
47a5fc8b09 feat: support regex/wildcard scopes in OAuth authorization requests (#5223) 2026-03-07 00:52:27 +08:00
Yang Luo
c1acb7a432 fix: fix go.sum 2026-03-07 00:02:33 +08:00
Yang Luo
c10b2c162f feat: fix Twilio SMS sending verification code bug (#5205) 2026-03-06 22:32:09 +08:00
ANormalDD
41ec8ba44f feat(web): add AutoComplete for SAML attributes value (#5215) 2026-03-06 20:27:40 +08:00
Yang Luo
7df722a103 fix: set organization.balanceCredit's max to 0 2026-03-06 14:10:07 +08:00
Yang Luo
04b1ca1157 fix: revert "feat: fix BalanceCredit to act as overdraft limit, not minimum balance floor" (#5214) 2026-03-06 13:36:21 +08:00
DacongDA
b0fecefeb7 feat: add Site and Rule to Casdoor (#5194) 2026-03-06 01:02:16 +08:00
Yang Luo
167d24fb1f fix: fix getOAuthGetParameters bug in Moodle 2026-03-05 23:05:20 +08:00
Yang Luo
dc58ac0503 feat: fix BalanceCredit to act as overdraft limit, not minimum balance floor (#5210) 2026-03-05 22:56:46 +08:00
Br1an
038d021797 fix: skip password columns in syncer when remote has no password data (#5183) 2026-03-05 22:35:27 +08:00
Yang Luo
7ba660fd7f feat: fix normal users blocked from /product-store (#5195) 2026-03-05 22:24:36 +08:00
Tomáš Karela Procházka
b1c31a4a9d feat: add Resend email provider (#5200) 2026-03-05 20:55:23 +08:00
Yang Luo
90d7add503 fix: remove useless returnUrl field from ProductEditPage (#5190) 2026-03-04 21:48:47 +08:00
Yang Luo
c961e75ad3 feat: fall back to English when unsupported Accept-Language locale is requested (#5177) 2026-03-04 21:41:10 +08:00
Br1an
547189a034 feat: add missing "min" param for Cloud PNVS SMS provider (#5180) 2026-03-03 09:08:31 +08:00
DacongDA
be725eda74 feat: merge CasWAF's cert related code into Casdoor's cert code (#5171) 2026-02-27 01:36:07 +08:00
Ke Wang
0765b352c9 fix: respect application's ID signup rule in WeChat Mini Program login (#5168) 2026-02-24 21:21:18 +08:00
Yang Luo
a2a8b582d9 feat: make DingTalk syncer respect TableColumns field mapping configuration (#5073) 2026-02-24 12:55:40 +08:00
Sriram-B-Srivatsa
0973652be4 fix: reduce code duplication in Logout logic (#5163) 2026-02-24 12:53:31 +08:00
Yang Luo
fef75715bf fix(web): prevent dashboard graph overlap when y-axis values increase 2026-02-23 15:24:05 +08:00
hikarukimi
4f78d56e31 feat: add OAuth consent page 2026-02-23 15:16:04 +08:00
hikarukimi
712bc756bc fix: improve code format 2026-02-23 15:09:57 +08:00
DacongDA
1c9952e3d9 feat: support JWT Profile for OAuth 2.0 Client Grants (RFC 7523) (#5124) 2026-02-23 14:44:34 +08:00
Yang Luo
bbaa28133f feat: apply application.DefaultGroup for OAuth signups (#5157) 2026-02-22 01:06:18 +08:00
Yang Luo
baef7680ea feat: validate OAuth scopes against Application config; return invalid_scope per RFC 6749 (#5153) 2026-02-21 17:44:26 +08:00
Yang Luo
d15b66177c feat: add missing Telegram field to User struct (#5151) 2026-02-21 17:21:31 +08:00
Yang Luo
5ce6bac529 fix: improve provider table links 2026-02-21 01:36:00 +08:00
Yang Luo
0621f35665 fix: improve tabs height UI in app edit page 2026-02-21 01:16:36 +08:00
Yang Luo
1ac2490419 fix: add OIDC and SAML tabs in application edit page 2026-02-21 01:13:54 +08:00
DacongDA
8c50ada494 feat: refactor provider edit page into different JS files (#5141) 2026-02-21 00:57:38 +08:00
Yang Luo
22da90576e feat: can free input in "Tag" in Addresses table 2026-02-20 16:49:50 +08:00
Yang Luo
b00404cb3a fix: fix RegionSelect cannot save value bug in Addresses table 2026-02-20 16:45:43 +08:00
Yang Luo
2ed27f4f0a fix: improve tables UI in my account page 2026-02-20 16:35:29 +08:00
Yang Luo
bf538d5260 fix: update UpdateUser() columns for missing User fields 2026-02-20 11:02:52 +08:00
Yang Luo
13ee5fd150 feat: sync newOrganization() accountItems with getBuiltInAccountItems() (#5146) 2026-02-20 10:47:02 +08:00
Yang Luo
04cdd5a012 feat: add missing user fields to GetTranslatedUserItems, getBuiltInAccountItems, init_data template, and UserFields (#5144) 2026-02-20 10:37:51 +08:00
Yang Luo
7b4873734b feat: fix "--config" flag to actually load specified configuration file (#5139) 2026-02-19 02:13:29 +08:00
Yang Luo
8d2290944a fix: add back Payment.ProductName and ProductDisplayName fields for backward compatibility 2026-02-18 19:28:14 +08:00
Yang Luo
6a2bba1627 feat: fix field visibility logic for provider types in ProviderEditPage (#5134) 2026-02-18 15:22:28 +08:00
Yang Luo
07554bbbe5 feat: fix Alipay OAuth provider by loading private key from cert object (#5119) 2026-02-17 14:42:21 +08:00
karatekaneen
a050403ee5 feat: fix bug that PKCE fails when multiple custom OAuth providers are configured (#5117) 2026-02-16 23:32:07 +08:00
IsAurora6
118eb0af80 feat: Optimize the display of payment products. (#5115) 2026-02-16 16:32:02 +08:00
Yang Luo
c16aebe642 fix: update README slogan 2026-02-16 02:33:45 +08:00
Yang Luo
3b8e7c9da2 fix: extend application with reverse proxy fields (#5113) 2026-02-16 02:23:47 +08:00
Yang Luo
4d5de767b0 fix: sync frontend i18n strings 2026-02-16 02:01:48 +08:00
Yang Luo
54bf8eae5c fix: improve category column UI in app list page 2026-02-16 01:46:06 +08:00
IsAurora6
1731b74fa0 fix: fix issue that dummy payments failed when there were too many items in the order (#5108) 2026-02-15 22:35:59 +08:00
Yang Luo
6e1e5dd569 feat: add scope-to-tool permission checking for Casdoor MCP server (#5104) 2026-02-15 22:31:35 +08:00
Yang Luo
b183359daf fix: rename order state PaymentFailed to Failed and improve UI (#5107) 2026-02-15 21:52:24 +08:00
Yang Luo
3cb9df3723 feat: [mcp-5] add Application.Category and Application.Type fields for agent applications (MCP, A2A) (#5102) 2026-02-15 21:28:00 +08:00
Yang Luo
9d1e5c10d0 feat: [mcp-4] implement RFC 8707 Resource Indicators for OAuth 2.0 (#5098) 2026-02-15 18:03:22 +08:00
Yang Luo
ef84c4b0b4 feat: [mcp-3] implement OAuth 2.0 Dynamic Client Registration (RFC 7591) (#5097) 2026-02-15 17:25:44 +08:00
Yang Luo
5a108bd921 fix: [mcp-2] add OAuth 2.0 Authorization Server Metadata endpoints (RFC 8414) (#5094) 2026-02-15 17:00:40 +08:00
Yang Luo
ac671ec1ee fix: rename to wellknown_oidc_discovery.go 2026-02-15 16:42:00 +08:00
Yang Luo
7814caf2ab feat: implement RFC 9728 OAuth 2.0 Protected Resource Metadata for MCP server discovery (#5092) 2026-02-15 16:40:48 +08:00
Yang Luo
f966f4a0f9 feat: fix Dummy payment provider returning zero price in NotifyResult (#5090) 2026-02-15 02:31:56 +08:00
Yang Luo
a4b1a068a8 feat: fix Azure SQL DB panic by migrating to the official go-mssqldb fork (#5082) 2026-02-15 01:52:06 +08:00
Yang Luo
362797678d feat: fix nil pointer panic in update-user API for non-existent account items (#5084) 2026-02-15 01:44:26 +08:00
Yang Luo
7879e1bf09 fix: fix Dummy payment provider to simulate external callback flow (#5080) 2026-02-15 00:18:09 +08:00
IsAurora6
c246f102c9 feat: fix issue that User.Cart cannot be updated without org account items (#5076) 2026-02-14 22:32:58 +08:00
IsAurora6
37d1c4910c feat: Fixed an error when clicking the “delete” button on the cart list page. (#5075) 2026-02-13 20:49:08 +08:00
Yang Luo
3bcde7cb7c feat: add Cart and payment fields to organization account items (#5070) 2026-02-13 10:40:37 +08:00
Yang Luo
6a90d21941 fix: add CreatedTime field to cart items and sort by timestamp (#5066) 2026-02-13 10:36:20 +08:00
Yang Luo
80b4c0b1a7 feat: remove special handling for Dummy payment provider (#5068) 2026-02-13 10:06:14 +08:00
Yang Luo
eb5a422026 feat: replace DisableSsl boolean with SslMode enum for Email providers (#5063) 2026-02-13 02:15:20 +08:00
DacongDA
f7bd70e0a3 feat: improve tab height UI in application edit page (#5055) 2026-02-12 21:57:57 +08:00
Copilot
5e7dbe4b56 feat: fix CAPTCHA rule enforcement in verification code flow (#5009) 2026-02-12 21:22:47 +08:00
Yang Luo
bd1fca2f32 feat: Add LDAP group/OU hierarchy syncing with automatic user membership (#5052) 2026-02-12 17:11:20 +08:00
IsAurora6
3d4cc42f1f feat: mark cart items as invalid when product is removed, renamed, or currency is changed. (#5050) 2026-02-12 00:46:54 +08:00
Yang Luo
1836cab44d feat: fix icons for 5 payment providers 2026-02-11 01:42:37 +08:00
Yang Luo
75b18635f7 feat: fix issue that Webhook records for set-password API were missing user context (#5008) 2026-02-11 01:32:11 +08:00
Yang Luo
47cd44c7ce feat: support "snsapi_privateinfo" scope in WeCom OAuth provider to support fetching Emails (#5034) 2026-02-11 01:21:29 +08:00
Yang Luo
090ca97dcd feat: bind provider IDs in WeCom/DingTalk/Lark syncers (#5033) 2026-02-11 01:04:26 +08:00
Yang Luo
bed01b31f1 feat: add AWS IAM syncer (#5043) 2026-02-11 01:00:41 +08:00
Yang Luo
c8f8f88d85 feat: add "Existing Field" category for token attributes table in application edit page (#5041) 2026-02-11 00:58:50 +08:00
IsAurora6
7acb303995 feat: Fixed cart anomalies when updating product information. (#5039) 2026-02-10 20:58:18 +08:00
IsAurora6
2607f8d3e5 feat: fix DingTalk syncer to fetch nested departments recursively (#5036) 2026-02-10 18:11:03 +08:00
IsAurora6
481db33e58 feat: Optimize the display of rechargeable product content on the ProductStorePage.js. (#5028) 2026-02-09 20:28:18 +08:00
DacongDA
f556c7e11f feat: add PaginateSelect widget to fix non-pagination fetch API issue (#5023) 2026-02-09 20:07:41 +08:00
IsAurora6
f590992f28 feat: update i18n translations (#5021) 2026-02-09 00:05:08 +08:00
Yang Luo
80f9db0fa2 feat: move captcha provider validation from frontend filter to backend check (#5019) 2026-02-08 02:16:47 +08:00
Yang Luo
0748661d2a feat: store OAuth tokens per provider instead of single originalToken field (#5016) 2026-02-08 01:22:24 +08:00
Yang Luo
83552ed143 feat: fix renderRightDropdown() scrollbar UI bug 2026-02-08 00:45:46 +08:00
Yang Luo
8cb8541f96 feat: add Plan.IsExclusive field for single subscription enforcement (#5004) 2026-02-07 01:23:22 +08:00
Yang Luo
5b646a726c fix: fix format issue in DuplicateInfo 2026-02-07 00:51:11 +08:00
Yang Luo
19b9586670 fix: fix broken links for role/plan/user/payment columns (#4999) 2026-02-07 00:46:36 +08:00
Yang Luo
73f8d19c5f fix: de-duplicate i18n translation keys in frontend and backend (#4997) 2026-02-07 00:35:46 +08:00
Yang Luo
04da531df3 fix: sync all i18n strings 2026-02-07 00:18:07 +08:00
Yang Luo
d97558051d fix: add duplicate key detection tests for i18n JSON files (#4994) 2026-02-07 00:17:53 +08:00
Yang Luo
ac55355290 fix: deduplicate the i18n strings 2026-02-06 21:42:10 +08:00
Yang Luo
a2da380be4 feat: add organization sync to DingTalk syncer (#4989) 2026-02-06 20:39:31 +08:00
IsAurora6
ecf8039c5d feat: Add cart icon to ProductStore/ProductBuy and quantity controls to ProductStore/ProductBuy/CartList. (#4984) 2026-02-05 23:07:22 +08:00
Yang Luo
0a6948034c feat: add OAuth 2.0 Token Exchange (RFC 8693) support (#4981) 2026-02-05 19:12:39 +08:00
Yang Luo
442f8fb19e feat: fix DeleteSession to handle missing sessions gracefully (#4979) 2026-02-05 15:41:15 +08:00
Yang Luo
b771add9e3 feat: auto-redirect OAuth signup to callback URL (#4941) 2026-02-05 15:18:33 +08:00
Yang Luo
df8e9fceea feat: disable /forget API when "Forgot Password?" signin item is hidden (#4977) 2026-02-04 23:04:00 +08:00
Yang Luo
d674f0c33d feat: update Swagger docs 2026-02-03 21:34:38 +08:00
buzaslan129
1e1b5273d9 feat: expose get-all-* Casbin endpoints in Swagger (#4952) 2026-02-03 21:32:50 +08:00
IsAurora6
cf5e88915c feat: The order.products display is divided into two parts. Remove the "startTime" and "endTime", and add an updateTime field. (#4968) 2026-02-03 21:12:27 +08:00
Yang Luo
c8973e6c9e feat: add Cloud PNVS SMS provider (#4964) 2026-02-03 02:00:08 +08:00
Yang Luo
87ea451561 feat: support group sync in Google Workspace syncer (#4962) 2026-02-03 01:58:28 +08:00
Yang Luo
8f32779b42 feat: fix invitation code group assignment for OAuth provider signup (#4961) 2026-02-03 01:23:36 +08:00
Yang Luo
aba471b4e8 feat: install lsof in ALLINONE Docker image (#4958) 2026-02-02 23:51:49 +08:00
DacongDA
72b70c3b03 feat: use sqlite DB instead of mariadb for all-in-one Docker image (#4949) 2026-02-02 00:13:14 +08:00
DacongDA
a1c56894c7 feat: add tabs to user edit page (#4945) 2026-02-01 14:01:28 +08:00
Yang Luo
a9ae9394c7 feat: add Linux machine login via LDAP with POSIX attributes (#4944) 2026-01-31 22:37:29 +08:00
Yang Luo
5f0fa5f23e feat: fix properties field xlsx import issue in user list page (#4943) 2026-01-31 01:49:36 +08:00
Yang Luo
f99aa047a9 feat: add Org.AccountItems.Tab field to have tabs in user edit page (#4892) 2026-01-30 21:56:35 +08:00
Yang Luo
1d22b7ebd0 feat: prevent duplicate webhook events from redundant payment notifications (#4936) 2026-01-30 21:56:09 +08:00
IsAurora6
d147053329 feat: Optimize the display of the products column on the order and payment, adjust the color of the “Add to Cart” button. (#4933) 2026-01-30 14:03:15 +08:00
IsAurora6
0f8cd92be4 feat: resolve returnUrl redirection failure of UserEditPage (#4931) 2026-01-29 09:37:47 +08:00
DacongDA
7ea6f1296d feat: fix i18n/generate.go bug in handling "\" (#4930) 2026-01-28 23:35:23 +08:00
Yang Luo
db8c649f5e feat: include payment status in notify-payment webhook payload (#4929) 2026-01-28 19:59:10 +08:00
DacongDA
a06d003589 feat: make codeChallenge dynamic for custom OAuth provider (#4924) 2026-01-28 17:56:28 +08:00
Jacob
33298e44d4 feat(ldap-sync): support syncing phone country code and formatting mobile number (#4919) 2026-01-28 14:09:52 +08:00
IsAurora6
f4d86f8d92 feat: fix incorrect clearing of the returnUrl path parameter in redirects (#4920) 2026-01-28 10:51:44 +08:00
Yang Luo
af4337a1ae feat: add multi-address support to user edit page (#4916) 2026-01-27 21:46:41 +08:00
IsAurora6
81e650df65 feat: Optimize the display of the order price column and improve parameter passing in the OrderPay view mode. (#4912) 2026-01-27 12:17:15 +08:00
Yang Luo
fcea1e4c07 feat: add SCIM 2.0 syncer (#4909) 2026-01-27 01:47:50 +08:00
Yang Luo
639a8a47b1 feat: add Okta syncer (#4908) 2026-01-27 01:19:39 +08:00
Yang Luo
43f61d4426 feat: add Lark syncer (#4897) 2026-01-27 01:00:19 +08:00
IsAurora6
e90cdb8a74 feat: add default payment providers on startup, improve checkProduct() logic (#4895) 2026-01-27 00:23:09 +08:00
DacongDA
bfe8955250 feat: remove bottom save button and extra scrollbar in application edit page (#4890) 2026-01-25 11:03:52 +08:00
DacongDA
36b9c4602a feat: add tab menu for application edit page (#4889) 2026-01-24 18:05:17 +08:00
IsAurora6
18117833e1 feat: Optimize button logic of product buy/store page,non-Created orders display "Detail" Button, and add "clear cart" Button (#4887) 2026-01-24 12:17:44 +08:00
Yang Luo
78dde97b64 feat: add PKCE support for Custom OAuth providers (#4880) 2026-01-23 21:29:57 +08:00
Yang Luo
3a06c66057 feat: fix Azure AD syncer OAuth2 token request - send parameters in body (#4878) 2026-01-22 23:01:38 +08:00
Yang Luo
aa59901400 feat: change Application.TermsOfUse length to 200 chars 2026-01-21 17:24:06 +08:00
IsAurora6
8e03b2d97c feat: Enable subscription-based products to be added to the cart and purchased, and optimize the cart page. (#4868) 2026-01-21 17:18:11 +08:00
MarshallHuang
d1da9499e8 fix: update OIDC discovery to use consistent authorization endpoint (#4872) 2026-01-21 16:54:51 +08:00
Yang Luo
2e7673c015 feat: use unionid in DingTalk syncer for consistency with OAuth provider (#4870) 2026-01-21 00:07:31 +08:00
DacongDA
2d1ace427e feat: support GetVersionInfo() API in released binary (#4860) 2026-01-20 18:05:11 +08:00
IsAurora6
039c12afa3 feat: add the shopping cart page (#4855) 2026-01-19 12:12:15 +08:00
slavb18
4236160fa7 feat: add User.OriginalRefreshToken field (#4721) 2026-01-19 12:08:18 +08:00
Yang Luo
071b5ddec0 feat: fix error for "/.well-known/:application/openid-configuration" API (#4866) 2026-01-19 03:06:33 +08:00
Gucheng Wang
f46b92d225 feat: reduce i18n languages (#4862) 2026-01-18 18:28:13 +08:00
Yang Luo
cc7eb4664c feat: support comma-separated user tags in application tag validation (#4856) 2026-01-17 01:26:12 +08:00
Yang Luo
1567723e2b feat: fix null issue for GrantTypes and RedirectUris in application 2026-01-17 01:18:57 +08:00
IsAurora6
074253f45e feat: Optimize PlaceOrder-related methods and pages to support the creation of multi-item orders. (#4847) 2026-01-16 16:52:02 +08:00
Yang Luo
23c86e9018 feat: add application.EnableSamlAssertionSignature to allow disabling SAML assertion signatures (#4850) 2026-01-16 14:30:48 +08:00
DacongDA
f088827a50 feat: redirect user to last login org's login page while cookie expired (#4844) 2026-01-15 18:17:12 +08:00
IsAurora6
663815fefe feat: The frontend supports payment logic for multi-item orders. (#4843) 2026-01-15 18:16:28 +08:00
DacongDA
0d003d347e fix: improve error handling in the syncer (#4845) 2026-01-15 15:02:24 +08:00
IsAurora6
7d495ca5f2 feat: The backend supports payment logic for multi-item orders. (#4842) 2026-01-14 21:57:09 +08:00
Jiachen Ren
f89495b35c fix: use unionid instead of job_number as user name in the OAuth provider (#4841) 2026-01-14 20:02:35 +08:00
IsAurora6
4a3aefc5f5 feat: improve filter logic in order, payment, subscription get APIs (#4839) 2026-01-14 12:08:29 +08:00
Yang Luo
15646b23ff feat: support ES/ECDSA signing method in ParseStandardJwtToken() (#4837) 2026-01-14 00:47:31 +08:00
gufeiyan1215
4b663a437f feat: add RRSA (RAM roles) support for the OSS storage provider (#4831) 2026-01-13 23:01:04 +08:00
DacongDA
9fb90fbb95 feat: support user impersonation (#4817) 2026-01-13 20:47:35 +08:00
Yang Luo
65eeaef8a7 feat: fix payment currency display to use product currency instead of user balance currency (#4822) 2026-01-13 20:47:31 +08:00
IsAurora6
ecf8e2eb32 feat: add supported currency validation for payment providers (#4818) 2026-01-13 20:47:28 +08:00
soliujing
e49e678d16 feat: improve build performance, separate build dependency to allow docker cache (#4815) 2026-01-13 20:47:24 +08:00
DacongDA
623ee23285 feat: in some case, saml replay state will include special character (#4814) 2026-01-13 20:47:09 +08:00
soliujing
0901a1d5a0 feat: handle default organization in get-orders API (#4790) 2026-01-13 20:46:50 +08:00
Yang Luo
58ff2fe69c feat: include access tokens in session-level (logoutAll=false) sso-logout notifications for Single Logout (SLO) (#4804) 2026-01-13 20:46:27 +08:00
IsAurora6
737f44a059 feat: optimize authentication handling in MCP (#4801) 2026-01-09 21:27:21 +08:00
soliujing
32cef8e828 feat: add permissions for get-order and get-orders APIs (#4788) 2026-01-09 17:33:29 +08:00
Yang Luo
9e854abc77 feat: don't auto-login for single SAML provider (#4795) 2026-01-09 17:03:16 +08:00
Yang Luo
9b3343d3db feat: fix multiple webhooks don't work bug (#4798) 2026-01-08 23:41:40 +08:00
Yang Luo
5b71725c94 feat: add OIDC-compliant email_verified claim to all JWT token formats (#4797) 2026-01-08 21:12:34 +08:00
IsAurora6
59b6854ccc feat: Optimize the notifications/initialized request and authentication failure handling in MCP. (#4781) 2026-01-08 17:42:36 +08:00
Yang Luo
0daf67c52c feat: fix UTF-8 encoding error in Active Directory syncer (#4783) 2026-01-08 01:50:47 +08:00
Yang Luo
4b612269ea feat: check whether refresh token is expired after SSO logout (#4771) 2026-01-07 19:42:35 +08:00
0xkrypton
f438d39720 feat: fix Telegram OAuth login error: "failed to verify Telegram auth data: data verification failed." (#4776) 2026-01-07 19:41:43 +08:00
Eng Zer Jun
f8df200dbf feat: update github.com/shirou/gopsutil to v4 (#4773) 2026-01-07 00:51:37 +08:00
IsAurora6
cb1b3b767e feat: improve "/api/mcp" check with demo mode (#4772) 2026-01-06 14:48:24 +08:00
IsAurora6
3bec49f16c feat: enhance MCP Permissions and Response Workflow, fix bugs (#4767) 2026-01-05 22:54:12 +08:00
Yang Luo
e28344f0e7 feat: add DingTalk syncer (#4766) 2026-01-05 21:43:57 +08:00
Yang Luo
93fefed6e8 feat: add Casdoor MCP server at "/api/mcp" for application management (#4752) 2026-01-05 21:38:34 +08:00
Yang Luo
ea9abb2f29 feat: fix bugs in ticket pages 2026-01-02 23:17:30 +08:00
Yang Luo
337a8c357b feat: fix error in order APIs 2026-01-02 22:04:51 +08:00
IsAurora6
d8cebfbf04 feat: Fixed the logic for updating order and transaction statuses in payment notifications. (#4749) 2026-01-02 19:30:23 +08:00
Yang Luo
91d5039155 feat: add all API endpoints to webhook Events dropdown (#4748) 2026-01-01 22:39:18 +08:00
DacongDA
5996ee8695 feat: add ID verification to init data template and organization UI (#4744) 2026-01-01 15:16:51 +08:00
Yang Luo
8c9331932b feat: initialize default values for fields like signupItems when adding applications via SDK (#4733) 2025-12-29 20:29:02 +08:00
DacongDA
db594e2096 feat: use org name as TOTP issuer (#4731) 2025-12-29 13:49:01 +08:00
Yang Luo
b46b79ee44 feat: improve error handling of hasGravatar() 2025-12-28 22:36:47 +08:00
Yang Luo
b9dbbca716 chore: improve README 2025-12-28 19:37:51 +08:00
Yang Luo
313cf6d480 fix: add missing ID Verification category to OtherProviderInfo (#4727) 2025-12-27 18:48:11 +08:00
DacongDA
0548597d04 feat: update dependencies (aws-sdk-go, go-git, goth and go-jose) to latest (#4729) 2025-12-27 18:17:18 +08:00
DacongDA
eb8e26748f feat: replace notify with notify2 for notification provider (#4728) 2025-12-27 10:47:36 +08:00
Yang Luo
516a23ab1b feat: fix CAPTCHA modal appearing when provider Rule is set to None (#4725) 2025-12-27 09:46:33 +08:00
DacongDA
9887d80e55 feat: upgrade beego to v2 (#4720) 2025-12-26 12:46:13 +08:00
slavb18
13dd4337a6 feat: Add phone number to CustomUserInfo (#4718) 2025-12-25 09:29:58 +08:00
Yang Luo
36c69a6da1 feat: add Telegram to OAuth provider options in web UI (#4719) 2025-12-25 09:29:36 +08:00
Yang Luo
3f4a60096a feat: add 28 missing User fields to syncer UI dropdown (#4713) 2025-12-24 20:56:11 +08:00
Yang Luo
b6240fa356 feat: improve GetFilteredUsers() 2025-12-24 20:31:09 +08:00
Yang Luo
d61f06b053 feat: add WebauthnCredentials and 27 other User fields to syncer (#4705) 2025-12-24 01:52:52 +08:00
IsAurora6
6fe785b6a4 feat: fix null address causing TypeError in management UI (#4706) 2025-12-24 01:31:47 +08:00
DacongDA
cccddea67e feat: fix unauthorized error when using app API to login (#4702) 2025-12-23 20:29:46 +08:00
IsAurora6
83b8c5477a feat: fix Transaction State field type from pp.PaymentState to string (#4699) 2025-12-21 01:31:54 +08:00
IsAurora6
ac0e069f71 feat: add Adyen payment provider (#4667) 2025-12-21 01:25:17 +08:00
DacongDA
4b25e56048 feat: Make session and cookie timeout configurable per application (#4698) 2025-12-21 01:04:38 +08:00
DacongDA
39740e3d6c feat: add support to delete single session and report err while deleting current session (#4694) 2025-12-18 21:15:57 +08:00
IsAurora6
87c5bf3855 fix: fixed balance and dummy payment errors (#4692) 2025-12-14 22:52:13 +08:00
IsAurora6
c4a28acbd8 feat: fix bug in i18n applyToOtherLanguage() (#4691) 2025-12-14 19:24:01 +08:00
IsAurora6
ee26b896f6 fix: show recharge options UI in product store page (#4682) 2025-12-13 15:46:26 +08:00
Yang Luo
4a8cb9535e feat: enforce failed signin limit for LDAP login (#4686) 2025-12-13 00:30:05 +08:00
Yang Luo
387a22d5f8 feat: add ticket list/edit pages (#4651) 2025-12-12 23:16:47 +08:00
Yang Luo
36cadded1c feat: add missing grant types to OIDC discovery endpoint (#4677) 2025-12-12 23:12:13 +08:00
DacongDA
7d130392d9 feat: add session-level single sign-out with authentication and configurable scope (#4678) 2025-12-12 23:08:01 +08:00
IsAurora6
f82c90b901 feat: Optimise the order confirmation page prompts and fix the issue where the transaction.application field was incorrectly populated as organisation. (#4681) 2025-12-12 21:31:22 +08:00
Yang Luo
1a08d6514e fix: improve IsRedirectUriValid() (#4672) 2025-12-11 22:18:56 +08:00
Yang Luo
4d5bf09b36 feat: fix signup application bug in /sso-logout API 2025-12-11 22:10:24 +08:00
Yang Luo
f050deada7 feat: add GoReleaser workflow for multi-platform binary releases (#4665) 2025-12-10 12:10:23 +08:00
Yang Luo
dee94666e0 fix: disable isValidRealName() check in backend 2025-12-10 12:00:23 +08:00
Yang Luo
b84b7d787b fix: fix isSelf() identity check for users without ID field in account items of user edit page (#4669) 2025-12-10 11:40:05 +08:00
Yang Luo
d425183137 feat: update Swagger docs 2025-12-10 01:55:08 +08:00
Yang Luo
ff7fcd277c feat: fix SAML authentication failure when username attribute is unmapped (#4663) 2025-12-10 01:50:03 +08:00
Yang Luo
ed5c0b2713 feat: remove "Please sign out first" check from signup and login APIs (#4659) 2025-12-09 21:16:54 +08:00
Yang Luo
eb60e43192 feat: use bcrypt password type by default for all organizations (#4654) 2025-12-08 22:11:19 +08:00
Yang Luo
d0170532e6 fix: improve Swagger annotations for session and token APIs (#4652) 2025-12-08 22:04:53 +08:00
Yang Luo
7ddb87cdf8 fix: Fix JWT-Custom token format: always include nonce/scope, add signinMethod and provider to dropdown (#4649) 2025-12-08 17:55:31 +08:00
Yang Luo
fac45f5ac7 feat: add Alibaba Cloud ID verification provider (#4645) 2025-12-08 17:48:52 +08:00
Yang Luo
266d361244 feat: fix "only the last session is displayed" bug by respecting application.EnableExclusiveSignin when adding sessions (#4643) 2025-12-08 17:14:11 +08:00
DacongDA
b454ab1931 feat: fix generated link has no org info bug while using shared application (#4647) 2025-12-08 16:35:17 +08:00
Yang Luo
ff39b6f186 feat: add Jumio ID Verification provider (#4641) 2025-12-08 00:39:34 +08:00
DacongDA
0597dbbe20 feat: always return array if item contains roles, groups or permissions in JWT (#4640) 2025-12-08 00:11:39 +08:00
Yang Luo
49c417c70e fix: add excel import support for groups, permissions, and roles (#4585) 2025-12-07 22:24:12 +08:00
IsAurora6
8b30e12915 feat: improve inventory logic: check stock before order and update stock/sales after payment. (#4633) 2025-12-07 19:38:41 +08:00
Jacob
2e18c65429 feat: add Application.DisableSamlAttributes field and fix C14N namespace issue (#4634) 2025-12-06 21:45:02 +08:00
IsAurora6
27c98bb056 feat: improve payment flow with order navigation and remove returnUrl field (#4632) 2025-12-06 17:57:59 +08:00
DacongDA
4400b66862 feat: fix silentSignin not working bug (#4629) 2025-12-06 11:10:10 +08:00
IsAurora6
e7e7d18ee7 fix: add permission control and view mode for product/order/payment/plan/pricing/subscription pages. (#4628) 2025-12-04 23:08:41 +08:00
IsAurora6
66d1e28300 feat: Add payment column to order list and refine product store card layout. (#4625) 2025-12-04 18:18:10 +08:00
IsAurora6
53782a6706 feat: support recharge products with preset amounts and disable custom amount option. (#4619) 2025-12-03 13:50:33 +08:00
Yang Luo
30bb0ce92f feat: fix signupItem.regex validation not working in signup page frontend (#4614) 2025-12-03 08:56:45 +08:00
Yang Luo
29f7dda858 feat: fix 403 error on /api/acs endpoint for SAML IdP responses (#4620) 2025-12-02 21:19:00 +08:00
Yang Luo
68b82ed524 fix: accept all file types in resources list page's upload button 2025-11-30 20:42:54 +08:00
Yang Luo
c4ce88198f feat: improve password popover positioning on signup page 2025-11-30 18:10:19 +08:00
Yang Luo
a11fa23add fix: fix i18n for "Please input your {field}!" validation message in signup page (#4610) 2025-11-30 17:47:25 +08:00
Yang Luo
add6ba32db fix: improve application edit page's Providers dropdown with search, icons, and display names (#4608) 2025-11-30 17:13:06 +08:00
Yang Luo
37379dee13 fix: fix get-groups API call in ApplicationEditPage to use correct owner parameter (#4606) 2025-11-30 16:23:28 +08:00
Yang Luo
2066670b76 feat: add Lemon Squeezy payment provider (#4604) 2025-11-30 13:40:48 +08:00
Yang Luo
e751148be2 feat: add FastSpring payment provider (#4601) 2025-11-30 12:02:18 +08:00
Yang Luo
c541d0bcdd feat: add Paddle payment provider (#4598) 2025-11-30 11:31:16 +08:00
Yang Luo
f0db95d006 feat: add Polar payment provider (#4595) 2025-11-30 10:45:11 +08:00
IsAurora6
e4db367eaa feat: Remove BuyProduct endpoint and legacy purchase logic. (#4591) 2025-11-28 23:51:22 +08:00
IsAurora6
9df81e3ffc feat: feat: add OrderPayPage.js, fix subscription redirect & refine list time format. (#4586) 2025-11-27 20:49:49 +08:00
IsAurora6
048d6acc83 feat: Implement the complete process of product purchase, order placement, and payment. (#4588) 2025-11-27 20:49:34 +08:00
Yang Luo
e440199977 feat: regenerate the Swagger docs 2025-11-25 22:24:32 +08:00
IsAurora6
cb4e559d51 feat: Added PlaceOrder, CancelOrder, and PayOrder methods, and added corresponding buttons to the frontend. (#4583) 2025-11-25 22:22:46 +08:00
zjumathcode
4d1d0b95d6 feat: drop legacy // +build comment (#4582) 2025-11-25 20:21:09 +08:00
Yang Luo
9cc1133a96 feat: upgrade gomail to v2.2.0 2025-11-25 01:03:45 +08:00
Yang Luo
897c28e8ad fix: fix SQL query in Keycloak syncer (#4578) 2025-11-24 23:40:30 +08:00
Yang Luo
9d37a7e38e fix: fix memory leaks in database syncer from unclosed connections (#4574) 2025-11-24 23:38:50 +08:00
Yang Luo
ea597296b4 fix: allow normal users to view their own transactions (#4572) 2025-11-24 01:47:10 +08:00
Yang Luo
427ddd215e feat: add Telegram OAuth provider (#4570) 2025-11-24 01:04:36 +08:00
Yang Luo
24de79b100 Improve getTransactionTableColumns UI 2025-11-23 22:07:33 +08:00
DacongDA
9ab9c7c8e0 fix: show error better for user upload (#4568) 2025-11-23 21:52:44 +08:00
Yang Luo
0728a9716b feat: deduplicate code between TransactionTable and TransactionListPage (#4567) 2025-11-23 21:47:58 +08:00
Yang Luo
471570f24a Improve AddTransaction API return value 2025-11-23 21:02:06 +08:00
Yang Luo
2fa520844b fix: fix product store page to pass owner parameter to API (#4565) 2025-11-23 20:48:15 +08:00
Yang Luo
2306acb416 fix: improve balanceCredit for org and user 2025-11-23 19:51:39 +08:00
Yang Luo
d3f3f76290 fix: add dry run mode to add-transaction API (#4563) 2025-11-23 17:36:51 +08:00
DacongDA
fe93128495 feat: improve user upload UX (#4542) 2025-11-23 16:05:46 +08:00
seth-shi
7fd890ff14 fix: ticket error handling in HandleOfficialAccountEvent() (#4557) 2025-11-23 14:58:23 +08:00
Yang Luo
83b56d7ceb feat: add product store page (#4544) 2025-11-23 14:54:35 +08:00
Yang Luo
503e5a75d2 feat: add User.OriginalToken field to expose OAuth provider access tokens (#4559) 2025-11-23 14:54:02 +08:00
seth-shi
5a607b4991 fix: close file handle in GetUploadXlsxPath to prevent resource leak (#4558) 2025-11-23 14:37:06 +08:00
Yang Luo
ca2dc2825d feat: add SSO logout notifications to user's signup application (#4547) 2025-11-23 00:47:29 +08:00
Yang Luo
446d0b9047 Improve TransactionTable UI 2025-11-23 00:45:47 +08:00
Yang Luo
ee708dbf48 feat: add Organization.OrgBalanceCredit and User.BalanceCredit fields for credit limit enforcement (#4552) 2025-11-23 00:37:44 +08:00
Yang Luo
221ca28488 fix: flatten top navbar to single level when ≤7 items (#4550) 2025-11-23 00:34:17 +08:00
Yang Luo
e93d3f6c13 Improve transaction list page UI 2025-11-22 23:35:04 +08:00
Yang Luo
e285396d4e fix: fix recharge transaction default values (#4546) 2025-11-22 23:27:29 +08:00
Yang Luo
10320bb49f Improve TransactionTable UI 2025-11-22 21:39:56 +08:00
seth-shi
4d27ebd82a feat: Use email as username when organization setting is enabled during login (#4539) 2025-11-22 20:58:27 +08:00
Yang Luo
6d5e6dab0a Fix account table missing item 2025-11-22 20:56:45 +08:00
Yang Luo
e600ea7efd feat: add i18n support for table column widgets (#4541) 2025-11-22 16:39:44 +08:00
Yang Luo
8002613398 feat: Add exchange rate conversion for balance calculations (#4534) 2025-11-21 22:13:26 +08:00
IsAurora6
a48b1d0c73 feat: Add recharge functionality with editable fields to transaction list page. (#4536) 2025-11-21 22:11:38 +08:00
Yang Luo
d8b5ecba36 feat: add transaction's subtype field and fix product recharge (#4531) 2025-11-21 19:27:07 +08:00
IsAurora6
e3a8a464d5 feat: Add balanceCurrency field to Organization and User models. (#4525) 2025-11-21 14:42:54 +08:00
IsAurora6
a575ba02d6 feat: Fixed a bug in addTransaction and optimized the transactionEdit page. (#4523) 2025-11-21 09:35:12 +08:00
IsAurora6
a9fcfceb8f feat: Add currency icons wherever currency appears, and optimize the display columns in the transaction table. (#4516) 2025-11-20 22:33:00 +08:00
ledigang
712482ffb9 refactor: omit unnecessary reassignment (#4509) 2025-11-20 18:47:03 +08:00
Yang Luo
84e2c760d9 feat: lazy-load Face ID models only when modal opens (#4508) 2025-11-20 18:46:31 +08:00
IsAurora6
4ab85d6781 feat: Distinguish and allow users to configure adminNavItems and userNavItems. (#4503) 2025-11-20 11:05:30 +08:00
Yang Luo
2ede56ac46 fix: refactor out Setting.CurrencyOptions (#4502) 2025-11-19 21:51:28 +08:00
Yang Luo
6a819a9a20 feat: persist hash column when updating users (#4500) 2025-11-19 21:50:32 +08:00
IsAurora6
ddaeac46e8 fix: optimize UpdateUserBalance and fix precision loss for orgBalance/userBalance. (#4499) 2025-11-19 21:13:32 +08:00
IsAurora6
f9d061d905 feat: return transaction IDs in API and disable links for anonymous user in transaction list (#4498) 2025-11-19 17:40:30 +08:00
Yang Luo
5e550e4364 feat: fix bug in createTable() 2025-11-19 17:33:51 +08:00
Yang Luo
146d54d6f6 feat: add Order pages (#4492) 2025-11-19 14:05:52 +08:00
IsAurora6
1df15a2706 fix: Transaction category & type links not navigating. (#4496) 2025-11-19 11:41:36 +08:00
Yang Luo
f7d73bbfdd Improve transaction fields 2025-11-19 09:14:49 +08:00
Yang Luo
a8b7217348 fix: add needSshfields() 2025-11-19 08:37:13 +08:00
Yang Luo
40a3b19cee feat: add Active Directory syncer support (#4495) 2025-11-19 08:30:01 +08:00
Yang Luo
98b45399a7 feat: add Google Workspace syncer (#4494) 2025-11-19 07:37:11 +08:00
Yang Luo
90edb7ab6b feat: refactor syncers into interface (#4490) 2025-11-19 01:28:37 +08:00
marun
e21b995eca feat: update payment providers when organization changes in PlanEditPage (#4462) 2025-11-19 00:14:01 +08:00
Yang Luo
81221f07f0 fix: improve isAllowedInDemoMode() for add-transaction API 2025-11-18 23:55:43 +08:00
Yang Luo
5fc2cdf637 feat: fix bug in GetEnforcer() API 2025-11-18 23:31:53 +08:00
Yang Luo
5e852e0121 feat: improve user edit page UI 2025-11-18 23:31:17 +08:00
Yang Luo
513ac6ffe9 fix: improve user edit page's transaction table UI 2025-11-18 23:31:16 +08:00
Yang Luo
821ba5673d Improve "Generate" button i18n 2025-11-18 23:31:16 +08:00
IsAurora6
d3ee73e48c feat: Add a URL field to the Transaction structure and optimize the display of the Transaction List. (#4487) 2025-11-18 21:45:57 +08:00
Yang Luo
1d719e3759 feat: fix OAuth-registered users to keep empty passwords unhashed (#4482) 2025-11-17 23:12:53 +08:00
Yang Luo
b3355a9fa6 fix: fix undefined owner in syncer edit page getCerts API call (#4471) 2025-11-17 22:51:12 +08:00
Yang Luo
ccc88cdafb feat: populate updated_time for all user creation paths (#4472) 2025-11-17 22:07:47 +08:00
Yang Luo
abf328bbe5 feat: allow setting email_verified in UpdateUser() API 2025-11-17 22:04:33 +08:00
DacongDA
5530253d38 feat: use correct org owner for UpdateOrganizationBalance (#4478) 2025-11-17 18:17:02 +08:00
Yang Luo
4cef6c5f3f feat: fix duplicate key error when re-importing users from different organization (#4473) 2025-11-17 02:13:35 +08:00
aozima
7e6929b900 feat: LDAP server adds more attributes: mail, mobile, sn, giveName (#4468) 2025-11-16 19:13:12 +08:00
aozima
46ae1a9580 fix: improve error handling for DingTalkIdProvider.GetUserInfo() (#4469) 2025-11-16 17:42:55 +08:00
Yang Luo
37e22f3e2c feat: support user custom password salt when organization salt is empty (#4465) 2025-11-15 02:35:15 +08:00
Yang Luo
68cde65d84 feat: fix bug about adding new permission in setEnforcerModel() 2025-11-12 20:39:44 +08:00
Yang Luo
1c7f5fdfe4 fix: fix transaction API to enforce user-level access control (#4447) 2025-11-12 20:31:14 +08:00
Yang Luo
1a5be46325 feat: add i18n support for password complexity error messages (#4458) 2025-11-12 19:40:21 +08:00
Yang Luo
f7bafb28d6 feat: support application's ExpireInHours and RefreshExpireInHours in float64 (#4442) 2025-11-12 17:01:56 +08:00
Yang Luo
6f815aefdf feat: update gopay to v1.5.115 to fix the payment URL (#4449) 2025-11-12 16:40:37 +08:00
DacongDA
eb49f29529 feat: fix e2e test backend start to fail caused by wrong GetModel param (#4454) 2025-11-12 15:44:20 +08:00
Yang Luo
5ad4e6aac0 feat: upgrade to Go 1.23 2025-11-11 22:43:38 +08:00
DacongDA
3c28a2202d feat: fix bug about "Failed to subscribe for new paid users" (#4450) 2025-11-11 22:37:14 +08:00
Yang Luo
0a9a9117e5 feat: allow org admins to access verification list and store organization in Owner field (#4441) 2025-11-11 01:12:16 +08:00
Yang Luo
f3ee1f83fe feat: fix bug about Permission.Model 2025-11-11 00:22:18 +08:00
Yang Luo
171af2901c feat: fix SAML signature verification failure with C14N10 canonicalization (#4439) 2025-11-10 20:50:57 +08:00
Yang Luo
2ded293e10 feat: fix namespace declaration issue in SAML C14N10 schema 2025-11-10 13:53:42 +08:00
Yang Luo
a1c6d6c6cf feat: fix bug in permission's model and adapter fields 2025-11-09 23:51:14 +08:00
Yang Luo
bf42176708 fix: add .editorconfig to web folder 2025-11-09 23:40:30 +08:00
Yang Luo
23a45c1d33 fix: remove wrong comments in lark.go 2025-11-07 23:02:48 +08:00
Yang Luo
6894ca407e fix: fix SAML assertion signing: add xmlns:xsi and xmlns:xs to assertion element (#4417) 2025-11-07 22:46:47 +08:00
Yang Luo
d288ecf6ed feat: support for WeChat Mobile (in-app browser) OAuth login (#4420) 2025-11-07 22:43:53 +08:00
Yang Luo
0a04174ec8 feat: add guest user authentication with automatic upgrade flow (#4421) 2025-11-07 22:05:22 +08:00
Yang Luo
3feb723abf feat: fix Lark OAuth login failure when user_id is empty (#4418) 2025-11-07 20:01:26 +08:00
Yang Luo
ff8b8fb631 feat: fix SAML Response schema validation by declaring xmlns:xs and xmlns:xsi at root (#4415) 2025-11-07 12:55:09 +08:00
Yang Luo
df38c0dd62 feat: fix null pointer panic in controllers package 2025-11-06 21:28:51 +08:00
Yang Luo
93e87e009e feat: add password obfuscation support to set-password API (#4410) 2025-11-06 20:06:11 +08:00
Copilot
f0a4ccbc3c feat: add CLI "export" arg to support exporting data to file (#4408) 2025-11-04 22:54:27 +08:00
Copilot
f17c8622f7 feat: fix authz filter's "Unauthorized operation" bug in /api/sso-logout API (#4404) 2025-11-04 20:23:58 +08:00
Copilot
09698b0714 feat: rename /api/logout-all to /api/sso-logout (#4401) 2025-11-04 14:43:43 +08:00
Copilot
1d913677a0 fix: add Transactions to account items of org edit page (#4399) 2025-11-04 14:19:24 +08:00
DacongDA
f3b00fb431 fix: support SSO logout: logout from all applications (#4390) 2025-11-04 14:14:33 +08:00
Copilot
c95a427635 feat: remove unused get-user-transactions API, use get-transactions API instead in user account page (#4395) 2025-11-04 12:22:57 +08:00
Copilot
778be62bae fix: add missing WeCom notification provider to dropdown (#4394) 2025-11-04 10:57:28 +08:00
hamidreza abedi
5574c6ad0d fix: refresh captcha on send code, prevent refreshing on signin (#4376) 2025-11-04 10:37:07 +08:00
Copilot
36db852a32 feat: fix JWT-Custom format including unselected fields with empty values (#4392) 2025-11-04 10:35:19 +08:00
Copilot
8ee8767882 feat: replace GetOwnerAndNameFromId with GetOwnerAndNameFromIdWithError everywhere (#4383) 2025-11-03 11:38:54 +08:00
Mohammed Tayeh
af5a9c805d feat: normalize email to lowercase to prevent duplicate accounts (#4380) 2025-11-02 21:39:18 +08:00
Copilot
f8e5fedf8b feat: add balance for user and org transactions (#4368) 2025-11-01 14:26:39 +08:00
Copilot
962a4970f4 feat: consolidate i18n "Failed to get" strings and wrap hardcoded error messages (#4374) 2025-11-01 10:51:10 +08:00
Copilot
d239b3f0cb fix: add flag icons to currency fields in product pages (#4370) 2025-11-01 08:57:51 +08:00
Copilot
0df467ce5e feat: add WeCom notification provider (#4367) 2025-11-01 01:11:51 +08:00
Copilot
3d5356a1f0 feat: add push notification as MFA method (#4364) 2025-11-01 00:19:18 +08:00
DacongDA
1824762e00 feat: fix missing dest parameter for signup with invitation code (#4363) 2025-10-31 20:46:37 +08:00
DacongDA
a533212d8a feat: fix bug that captcha will show twice if using inline captcha (#4358) 2025-10-30 23:13:59 +08:00
Copilot
53e1813dc8 feat: fix OTP countdown timer UI to respect application's codeResendTimeout config (#4357) 2025-10-30 22:16:55 +08:00
Copilot
ba95c7ffb0 feat: add cleanOldMEIFolders() for casbin-python-cli (#4353) 2025-10-30 17:44:48 +08:00
Copilot
10105de418 fix: add missing i18n wrappers to backend error messages and translate all strings (#4349) 2025-10-29 23:59:19 +08:00
anhuv
9582163bdd feat: upgrade some Go dependencies (#4350) 2025-10-29 23:53:01 +08:00
Copilot
cc7408e976 feat: improve Prometheus metric API handlers (#4346) 2025-10-29 20:46:52 +08:00
Copilot
d67d714105 feat: fix Custom HTTP Email provider: correct From address field binding and add missing To address field (#4341) 2025-10-29 11:10:28 +08:00
Copilot
0aab27f154 feat: add Azure AD syncer (#4335) 2025-10-28 00:55:52 +08:00
Copilot
212090325b feat: add WeCom syncer (#4329) 2025-10-27 23:30:57 +08:00
DacongDA
b24e43c736 feat: Add RADIUS MFA support for external authentication servers (#4333) 2025-10-27 22:51:26 +08:00
Copilot
1728bf01ac feat: translate untranslated backend i18n strings (#4322) 2025-10-27 10:29:43 +08:00
Attack825
86a7a87c57 feat: translate all untranslated i18n strings (#4313) 2025-10-27 09:30:50 +08:00
Copilot
61c8e08eb0 feat: fix duplicate CI workflow runs on pull requests (#4319) 2025-10-27 01:01:03 +08:00
Copilot
caccd75edb feat: add EnableProxy field for Email and SMS providers (#4317) 2025-10-26 21:37:54 +08:00
Copilot
7b2666d23e feat: add in-memory cache for run-casbin-command API (#4314) 2025-10-25 23:46:02 +08:00
Copilot
b7b6d2377a feat: add username matching in Login() API for automatic Wecom OAuth login association (#4308) 2025-10-25 01:50:24 +08:00
Copilot
d43ee2d48f feat: enable post-registration subscription upgrades for all user types, not only paid users (#4309) 2025-10-25 01:48:23 +08:00
Copilot
242c75d9dc feat: add CodeResendTimeout to Application edit page (#4264) 2025-10-25 01:13:17 +08:00
Copilot
6571ad88a2 feat: prevent re-registration via third-party login for soft-deleted users (#4306) 2025-10-25 01:09:08 +08:00
DacongDA
bb33c8ea31 feat: add support for exclusive login (#4301) 2025-10-23 22:00:09 +08:00
Copilot
48f5531332 feat: apply Casbin rules to users signing up via external providers with signup groups (#4253) 2025-10-22 14:53:57 +08:00
Copilot
3e5114e42d feat: can map claims from external Identity Providers (Okta, Azure AD, etc.) to additional user properties (#4296) 2025-10-22 01:45:34 +08:00
Yang Luo
03082db9f2 fix: update all i18n data 2025-10-22 00:35:16 +08:00
Attack825
a2363e55e7 feat: add missing "eft" in GetBuiltInModel()'s Casbin model (#4277) 2025-10-22 00:05:29 +08:00
Copilot
dde4e41e24 feat: add application-specific OIDC discovery endpoints (#4294) 2025-10-21 23:40:23 +08:00
Copilot
c3eea4d895 feat: enable applications to define custom title and favicon (#4291) 2025-10-21 01:27:53 +08:00
Copilot
4ff28cacbe feat: fix /api/logout API to support POST requests with form parameters (#4282) 2025-10-20 14:16:14 +08:00
Copilot
e8ed9ca9e3 feat: add support for custom HTTP headers, body mapping, and content types in Custom HTTP SMS provider (#4270) 2025-10-20 14:07:48 +08:00
Copilot
8f8b7e5215 feat: support "new-user" webhooks for LDAP and syncer (#4285) 2025-10-19 22:38:41 +08:00
Copilot
099e6437a9 feat: fix nil pointer dereference in Login handler when provider is nil (#4278) 2025-10-18 00:13:12 +08:00
DacongDA
fdbb0d52da feat: fix QRCode param error in payUrl and successUrl (#4276) 2025-10-17 23:18:02 +08:00
Copilot
9c89705a19 feat: fix SAML audience duplication and empty values in response generation (#4268) 2025-10-15 19:25:49 +08:00
DacongDA
18451a874e feat: add 9 more custom fields for custom oauth (#4265) 2025-10-14 22:26:41 +08:00
Copilot
99dae68c53 feat: add LDAP country attribute mapping to user region field (#4257) 2025-10-14 22:11:02 +08:00
Copilot
7e2c2bfc64 feat: Add RegisterType and RegisterSource fields to User struct (#4252) 2025-10-14 20:56:38 +08:00
Copilot
4ae6675198 feat: fix SAML assertion signing failure with C14N10 exclusive canonicalization (#4260) 2025-10-14 18:48:29 +08:00
Copilot
8c37533b92 feat: support SAML assertion signing at all times (#4237) 2025-10-14 00:25:26 +08:00
DacongDA
3e77bd30a0 feat: support "Casdoor API" resource type in permission edit page (#4251) 2025-10-13 23:51:14 +08:00
Copilot
55257d6190 feat: support user.Id parameter in /update-user API (#4249) 2025-10-13 23:10:17 +08:00
Attack825
b9046bec01 feat: support Form.Tag and remove unique formType checks (#4002) 2025-10-09 22:15:08 +08:00
Kevin D'souza
40d4e3a1a9 feat: accept if the SAML certificate is of type PEM as well (#4232) 2025-10-08 22:57:53 +08:00
Attack825
60bfc8891a fix: fix label's i18n in form edit page (#4226) 2025-10-05 23:18:52 +08:00
Attack825
126879533b feat: add Form.Label and change form.Width to string (#4225) 2025-10-05 21:03:36 +08:00
DacongDA
469b6036fd feat: fix JSON parse error with ObjectWithOrg in authz_filter.go's getObject() (#4224) 2025-10-04 23:36:15 +08:00
DacongDA
6c750867b0 feat: support different SAML hash algorithms: "SHA1", "SHA256", "SHA512" for SAML signature in application edit page (#4221) 2025-10-02 11:58:34 +08:00
Austin Riendeau
625b3e2c63 feat: fix missing subject in Sendgrid Email provider (#4220) 2025-10-02 11:45:31 +08:00
DacongDA
28dff8083a feat: fix bug that notify-payment webhook was not triggered (#4219) 2025-10-02 11:44:01 +08:00
Yang Luo
02c4bddb5f feat: improve user-upload button 2025-09-30 14:01:12 +08:00
Enze Wu
df65fb3525 feat: skip old password verification for OAuth users without a password (#4211) 2025-09-29 17:43:45 +08:00
DacongDA
d3bbf954f8 feat: fix issue that couldn't auto set invitatonCode when using oAuth signup link (#4212) 2025-09-29 17:19:58 +08:00
Attack825
f3755d925c feat: improve form edit page UI and add preview (#4210) 2025-09-27 16:26:12 +08:00
Attack825
ca819e7e83 feat: add form to customize columns (#4202) 2025-09-25 22:04:43 +08:00
M3ti
d619e91d9e feat: add support for custom attribute mapping to user properties in LDAP (#4201) 2025-09-23 00:57:12 +08:00
Robin Ye
5079c37818 feat: improve compatibility for MinIO storage provider (#4196) 2025-09-21 16:02:19 +08:00
DacongDA
d5f29d716a feat: change User.Avatar's DB type to text (#4199) 2025-09-20 21:32:51 +08:00
DacongDA
00b278a00f feat: check roles in CheckLoginPermission (#4198) 2025-09-20 19:50:36 +08:00
DacongDA
d883db907b feat: improve authz_filter (#4195) 2025-09-18 23:46:00 +08:00
Attack825
8e7efe5c23 feat: add code verification label in signin items (#4187) 2025-09-18 10:41:47 +08:00
DacongDA
bf75508d95 feat: add token attribute table to provide a more flexible Jwt-custom token in application edit page (#4191) 2025-09-17 21:57:17 +08:00
Mirko Rapisarda
986b94cc90 feat: improve domain field text in provider edit page (#4181) 2025-09-16 20:57:40 +08:00
Attack825
890f528556 feat: separate getLocalPrimaryKey() and getTargetTablePrimaryKey() in DB syncer (#4180) 2025-09-15 17:45:18 +08:00
Robin Ye
b46e779235 feat: persist custom signin item label in signin items table (#4179) 2025-09-15 17:43:20 +08:00
Attack825
5c80948a06 feat: add tag filtering in app list page (#4163) 2025-09-14 15:32:13 +08:00
DacongDA
1467199159 feat: add webhook for buy-product and add resp data (#4177) 2025-09-12 23:53:59 +08:00
DacongDA
64c2b8f0c2 feat: fix issue that init will add duplicate policy and not add permission policies to adapter (#4175) 2025-09-11 21:21:07 +08:00
DacongDA
8f7ea7f0a0 feat: fix Data Missing From casbin_rule Table After Importing init_data.json (#4167) 2025-09-09 21:20:25 +08:00
DacongDA
2ab85c0c44 feat: fix bug that send code type will be "phone" when logged-in via autofill (#4164) 2025-09-08 18:13:52 +08:00
Dev Hjz
bf67be2af6 feat: add username and loginHint to redirect URL in HandleSamlRedirect of SAML IdP (#4162) 2025-09-07 14:18:35 +08:00
DacongDA
bc94735a8d feat: add the username parameter in SAML or OAuth2 (#4161) 2025-09-06 22:03:18 +08:00
DacongDA
89c6ef5aae feat: support "permissionNames" field in JWT-Custom token (#4154) 2025-09-06 00:05:47 +08:00
anhuv
21da9f5ff2 feat: remove port from client IP in getIpInfo() (#4145) 2025-09-04 08:10:42 +08:00
karatekaneen
3b11e778e7 feat(i18n): Update faulty Swedish translations (#4149) 2025-09-03 20:45:57 +08:00
Attack825
ad240a373f feat: fix non-standard CAS bug (#4146) 2025-09-03 20:20:08 +08:00
amaankm
01000f7022 feat: update parameter descriptions in Session API (#4140) 2025-09-02 16:31:06 +08:00
Cleidson Oliveira
f93aeb5350 feat: improve pt i18n strings (#4143) 2025-09-02 15:53:51 +08:00
gongzhongqiang
8fa681f883 feat: add password change validation to ensure new password differs from current password (#4134) 2025-09-01 17:22:06 +08:00
DacongDA
3b16406442 feat: add signinMethod in JWT token (#4136) 2025-08-31 18:01:05 +08:00
Attack825
fbc16ef124 feat: change builtInMaxFields to 6 in Casbin policy length (#4130) 2025-08-29 22:39:39 +08:00
DacongDA
f26f56e88b feat: support auto signup with SAML (#4129) 2025-08-29 11:51:52 +08:00
DacongDA
9cb633c9e2 feat: use a more popular format for nameid to ensure compatibility in NewSamlResponse() (#4123) 2025-08-27 22:33:14 +08:00
DacongDA
d0d059d42f feat: fix Email and SMS check failures when enabling or verifying MFA (#4122) 2025-08-27 21:11:53 +08:00
biankasyo
c184dc7f3a feat(lark): support enterprise_email field as email fallback (#4128) 2025-08-27 20:55:32 +08:00
DacongDA
2fa0890c11 feat: fix bug that custom JWT token no longer includes properties (#4124) 2025-08-27 20:41:27 +08:00
DacongDA
a0e2be7ba8 feat: support inserting user's field to SAML attribute (#4105) 2025-08-22 11:27:21 +08:00
IsAurora6
09b389b1f7 feat: add a loading animation in DashboardPage (#4117) 2025-08-22 00:11:08 +08:00
DacongDA
a23033758f feat: Add "Send Invitation Email" action to User Invitation flow (#4113) 2025-08-21 18:53:43 +08:00
Attack825
f7bc822087 feat: refresh inline captcha on login failure (#4108) 2025-08-21 10:29:56 +08:00
kevin kwok
e533ff1ee1 feat: add support for casbin-dotnet-cli auto-download (#4110) 2025-08-20 18:38:00 +08:00
Attack825
9f187f690e feat: add copy button in ApplicationListPage (#4097) 2025-08-19 16:18:28 +08:00
Jerry
fe5aa1f214 feat: Add Phantom web3 onboard wallet support (#4100) 2025-08-19 13:31:35 +08:00
DacongDA
eda742a848 feat: support e164 phone number in GetUserByPhone() (#4099) 2025-08-19 02:19:15 +08:00
Attack825
83df077a02 feat: add Application.Order for sorting in Apps page (#4085) 2025-08-18 08:34:32 +08:00
DacongDA
ad6080e763 feat: fix issue that signing up via provider in shared application will sign up to built-in app (#4093) 2025-08-17 22:32:47 +08:00
DacongDA
c179324de4 feat: fix bug that SelfLoginButton will re-render when username field updates (#4091) 2025-08-17 19:50:34 +08:00
DacongDA
645716e485 feat: add country code to validate phone number when Code method's rule is Phone only (#4089) 2025-08-17 16:56:25 +08:00
IsAurora6
955e73ddd1 feat: fix the asynchronous issue in handleOrganizationChange in BaseListPage (#4090) 2025-08-17 14:59:49 +08:00
Robin Ye
2493ae9cfe feat: fix issue that a user can belong to two physical groups at the same time (#4084) 2025-08-15 23:42:09 +08:00
Attack825
b5c80513fb feat: change username too when "username as email" switch is enabled in ResetEmailOrPhone API (#4081) 2025-08-14 21:03:45 +08:00
Attack825
0653353be1 feat: update social_osonsms.svg URL (#4082) 2025-08-14 20:35:39 +08:00
Robin Ye
d6778fb4e6 feat: improve inline captcha UI by increasing spacing (#4079) 2025-08-14 16:15:34 +08:00
DacongDA
fee7773839 feat: add First name and Last name to account items (#4077) 2025-08-14 08:41:18 +08:00
Robin Ye
d47ac6b957 feat: add support for Azerbaijani language (az) (#4073) 2025-08-14 00:13:01 +08:00
Robin Ye
857824df19 feat: sync i18n texts (#4075) 2025-08-13 23:10:58 +08:00
Attack825
1e98d1e11b feat: fix MinIO provider logo URL (#4076) 2025-08-13 22:20:50 +08:00
Yang Luo
48ba88de2d feat: improve error handling in AutoSigninFilter 2025-08-13 15:27:52 +08:00
Yang Luo
a3a142db39 feat: fix error message in VerificationForm.CheckParameter() 2025-08-12 10:13:00 +08:00
hamidreza abedi
3bb7cc6b81 feat: increase LDAP's "basedn" field to 500 chars (#4062) 2025-08-11 16:46:15 +08:00
Robin Ye
1fb3249bfd fix: improve "Copy signup page URL" button UI in invitation edit page (#4038) 2025-08-10 23:03:13 +08:00
DacongDA
ff8f61a84c feat: fix missing search params bug in switchLoginOrganization() (#4058) 2025-08-10 22:11:06 +08:00
DacongDA
a118879dc0 feat: allow user to select organization in login page when using shared app (#4053) 2025-08-10 20:40:30 +08:00
DacongDA
386b673446 feat: support scanning code to login in the login page (#4052) 2025-08-10 00:09:43 +08:00
DacongDA
6abd46fe81 feat: fix issue that signing up with shared application will create user in wrong org (#4051) 2025-08-09 22:25:01 +08:00
IsAurora6
49d734d249 feat: standardize Resource APIs by handling path prefix internally and returning clean paths (#4047) 2025-08-08 23:31:22 +08:00
iderr
f5b4cd7fab feat: Fix GetFilteredPoliciesMulti when filtering only by ptype (#4039) 2025-08-05 22:51:40 +08:00
iderr
76f322861a feat: Refactor GetFilteredPolicies to support multiple filters via POST (#4037) 2025-08-04 19:51:25 +08:00
Seele.Clover
124c28f1e1 feat: allow Custom OAuth provider to not fill in email and avatarUrl in configuring user_mapping (#4035) 2025-08-04 12:26:12 +08:00
DacongDA
e0d9cc7ed1 feat: improve error handling on signInWithWebAuthn (#4033) 2025-08-03 01:26:18 +08:00
Seele.Clover
75c1ae4366 feat: support nested fields for configuring user_mapping in the Custom OAuth provider (#4032) 2025-08-03 00:33:52 +08:00
DacongDA
d537377b31 feat: show placeholder QR code with loading instead of "Loading" text in QR code login page (#4031) 2025-08-02 15:58:49 +08:00
raiki02
462ecce43b feat: check args in Enforce and BatchEnforce APIs (#4029) 2025-08-02 13:39:05 +08:00
raiki02
a84664b55d feat: remove toLower conversion in getPolicies() (#4030) 2025-08-02 13:38:49 +08:00
Justin Judd
941c56e69e feat(jwt): Enable using User Properties as custom claims (#3571) 2025-08-02 10:34:11 +08:00
DacongDA
a28b871a46 feat: add useGroupPathInToken boolean field in app.conf (#4026) 2025-08-02 01:40:26 +08:00
Robin Ye
387f5d58f7 feat: prevent two captcha providers are added to one single application (#4025) 2025-08-01 22:50:12 +08:00
Xiao Mao
7d846b2060 feat: implement root DSE handling and schema query in LDAP server (#4020) 2025-07-31 01:23:25 +08:00
raiki02
c1c2dcab38 feat: can disable signin within application and organization (#4012) 2025-07-30 21:07:35 +08:00
Robin Ye
f9264f700b feat: add get-filtered-policies API, improve Swagger docs (#4006) 2025-07-29 23:51:01 +08:00
Xiao Mao
f3af2a26aa feat: add posixAccount and posixGroup filter logic for more versatile usage in LDAP (#4014) 2025-07-29 21:49:39 +08:00
DacongDA
0ac69bde53 feat: fix objectClass filter will return empty response (#4011) 2025-07-28 23:39:04 +08:00
Yang Luo
70c99f0e59 feat: fix "Key text" multi-line input box for Apple OAuth provider 2025-07-28 17:49:36 +08:00
kevin kwok
8d1fdc3a08 feat: add support for casbin-python-cli auto-download (#4004) 2025-07-27 14:00:00 +08:00
DacongDA
30c15b8135 feat: fix the error effect of form post response type (#4003) 2025-07-26 23:26:37 +08:00
Kevin D'souza
2d6de216b8 feat: move to a more robust way of checking if element in slice (#4001) 2025-07-26 11:57:45 +08:00
IsAurora6
ac39722687 feat: fix issue that resource provider.PathPrefix is not used in GetDirectResources() API (#4000) 2025-07-25 22:06:08 +08:00
Attack825
26a9ec8ee6 feat: translate all i18n strings (#3992) 2025-07-25 21:22:25 +08:00
DacongDA
fea6317430 feat: add back support for non-discoverable credential WebAuthn login and display WebAuthn ID again (#3998) 2025-07-25 18:34:37 +08:00
DacongDA
5f702ca418 feat: make enableErrorMask work for corner cases by moving checks from controller to Translate() (#3996) 2025-07-25 00:39:01 +08:00
Robin Ye
0495d17a07 feat: support OAuth 2.0 form_post response mode (#3973) 2025-07-24 15:17:45 +08:00
Yang Luo
c6a2d59aa4 feat: update i18n strings 2025-07-24 15:15:19 +08:00
DacongDA
d867afdd70 feat: can set default value for "Auto sign in" in application edit page (#3987) 2025-07-22 22:57:01 +08:00
Attack825
a92430e8fd feat: fix auto sign-in flow on result page (#3983) 2025-07-22 20:19:45 +08:00
Yang Luo
447cb70553 feat: change some fields of organization and user to mediumtext 2025-07-21 23:43:17 +08:00
Yang Luo
e05fbec739 feat: keep backward compatibility in GetHashedPassword() 2025-07-21 19:32:59 +08:00
DacongDA
65ab36f073 feat: fix bug that GetHashedPassword() reports error (#3982) 2025-07-21 14:41:09 +08:00
M Zahid Rausyanfikri
d027e07383 feat: fix bug that needUpdatePassword is not respected (#3979) 2025-07-21 10:17:24 +08:00
DacongDA
d3c718b577 feat: fix bug that language cannot be switched to user selected language (#3980) 2025-07-21 10:16:07 +08:00
DacongDA
ea68e6c2dc feat: support inline-captcha in login page (#3970) 2025-07-19 01:12:07 +08:00
raiki02
7aa0b2e63f feat: change the method "login" to correct param "signup" (#3971) 2025-07-19 00:49:00 +08:00
raiki02
a39b121280 feat: support WeChat login directly in login page (#3957) 2025-07-18 01:29:31 +08:00
DacongDA
feef4cc242 feat: set ResponseModesSupported to standard OIDC: "query", "fragment" (#3968) 2025-07-17 10:20:37 +08:00
Attack825
1b5ef53655 feat: fix tour bug about orgIsTourVisible settings (#3965) 2025-07-16 18:00:44 +08:00
Attack825
18d639cca2 feat: fix tour button (#3961) 2025-07-16 12:02:14 +08:00
DacongDA
3ac5aad648 feat: fix validate text error caused by password length check (#3964) 2025-07-16 10:10:13 +08:00
Robin Ye
2a53241128 feat: support 15 more currencies (#3963) 2025-07-16 01:07:25 +08:00
DacongDA
835273576b feat: add Lark OAuth provider (#3956) 2025-07-13 19:51:45 +08:00
raiki02
7fdc264ff6 feat: check if MFA is verified when required (#3954) 2025-07-12 15:20:44 +08:00
DacongDA
a120734bb1 feat: support links in email to reset password (#3939) 2025-07-12 00:18:56 +08:00
Vickko
edd0b30e08 feat: Supports smooth migration of password hash (#3940) 2025-07-11 19:57:55 +08:00
Attack825
2da597b26f feat: add support for per-account MFA validity period in org setting to reduce repeated prompts (#3917) 2025-07-11 00:24:33 +08:00
DacongDA
ef14c84edc feat: show the popover on the top when window's width too small and close popover when password options is empty (#3952) 2025-07-10 19:56:05 +08:00
Yang Luo
cb5c7667b5 feat: change Subscription's StartTime and EndTime to string 2025-07-10 14:11:40 +08:00
Yang Luo
920ed87f75 fix: refactor the code in CheckPassword() 2025-07-10 00:49:13 +08:00
raiki02
6598f0ccdf feat: use token's client ID instead in IntrospectToken() API (#3948) 2025-07-09 22:07:44 +08:00
Yang Luo
8e71e23d75 feat: improve error message for GetConfigInt64() 2025-07-09 00:32:00 +08:00
Yang Luo
146a369f80 feat: improve error handling in AutoSigninFilter 2025-07-08 23:47:14 +08:00
raiki02
9bbe5afb7c feat: use only one salt arg in CredManager.IsPasswordCorrect() (#3936) 2025-07-07 17:56:25 +08:00
DacongDA
b42391c6ce feat: move needUpdatePassword to response's Data3 field to avoid refresh token conflict (#3931) 2025-07-05 22:48:44 +08:00
Raiki
fb035a5353 feat: CredManager.GetHashedPassword() only contains one salt arg now (#3928) 2025-07-05 18:41:37 +08:00
Raiki
b1f68a60a4 feat: set createDatabase to false in TestDumpToFile() (#3924) 2025-07-03 22:50:23 +08:00
Robin Ye
201d704a31 feat: improve TikTok username generation logic (#3923) 2025-07-03 20:53:15 +08:00
Robin Ye
bf91ad6c97 feat: add Internet-Only captcha rule (#3919) 2025-07-03 02:39:06 +08:00
Yang Luo
3ccc0339c7 feat: improve CheckToEnableCaptcha() logic 2025-07-03 02:32:07 +08:00
DacongDA
1f2b0a3587 feat: add user's MFA items (#3921) 2025-07-02 23:05:07 +08:00
DacongDA
0b3feb0d5f feat: use Input.OTP to input totp code (#3922) 2025-07-02 18:22:59 +08:00
DacongDA
568c0e2c3d feat: show Organization.PasswordOptions in login UI (#3913) 2025-06-28 22:13:00 +08:00
Yang Luo
f4ad2b4034 feat: remove "@" from name's forbidden chars 2025-06-27 18:41:50 +08:00
Attack825
c9f8727890 feat: fix bug in InitCleanupTokens() (#3910) 2025-06-27 02:08:18 +08:00
DacongDA
e2e3c1fbb8 feat: support Product.SuccessUrl (#3908) 2025-06-26 22:52:07 +08:00
David
73915ac0a0 feat: fix issue that LDAP user address was not syncing (#3905) 2025-06-26 09:38:16 +08:00
Attack825
bf9d55ff40 feat: add InitCleanupTokens() (#3903) 2025-06-26 09:31:59 +08:00
XiangYe
b36fb50239 feat: fix check bug to allow logged-in users to buy product (#3897) 2025-06-25 10:49:20 +08:00
Øßfusion
4307baa759 feat: fix Tumblr OAuth's wrong scope (#3898) 2025-06-25 09:55:02 +08:00
David
3964bae1df feat: fix org's LDAP table wrong link (#3900) 2025-06-25 09:51:40 +08:00
Yang Luo
d9b97d70be feat: change CRLF to LF for some files 2025-06-24 09:55:00 +08:00
Attack825
ca224fdd4c feat: add group xlsx upload button (#3885) 2025-06-17 23:43:38 +08:00
千石
37daea2bbc feat: improve error message in ApplicationEditPage (#3886) 2025-06-17 20:06:52 +08:00
千石
af231bf946 feat: add FieldValidationFilter to check object names (#3877) 2025-06-17 16:11:35 +08:00
DacongDA
6dc7b4d533 feat: get-user API respects org's account item's view rules now (#3882) 2025-06-16 20:09:21 +08:00
DacongDA
12cc0f429e feat: remove support for Non trace verification for Alibaba cloud captcha verification (#3881) 2025-06-13 00:36:29 +08:00
DacongDA
8cc22dec91 feat: upgrade Alibaba cloud captcha provider from v1 to v2 (#3879) 2025-06-12 23:02:36 +08:00
千石
0c08ae5365 feat: Add support for email verification logic (#3875) 2025-06-11 19:17:16 +08:00
Yang Luo
c3485268d3 feat: fix "Display name cannot be empty" in /update-user API 2025-06-11 00:32:05 +08:00
Yang Luo
64a4956c42 feat: improve getMemoryUsage() 2025-06-09 20:08:55 +08:00
DacongDA
855bdf47e8 feat: fix memory usage in sysinfo page (#3870) 2025-06-09 00:31:34 +08:00
DacongDA
de7e322fbb feat: limit the width of the organization.hasPrivilegeConsent popconfirm (#3869) 2025-06-07 00:30:41 +08:00
DacongDA
4cb0cd7c5a feat: add Organization.HasPrivilegeConsent to block add-user API for the "built-in" org (#3864) 2025-06-06 23:05:01 +08:00
DacongDA
c6a50349cc feat: add missing backend i18n texts (#3863) 2025-06-06 00:03:04 +08:00
DacongDA
8a098a4b6e feat: skip node_modules folder when generating i18n (#3862) 2025-06-05 20:51:14 +08:00
Yang Luo
09f98fd24a feat: rollback to Beego 1.12.12 to fix Redis session issue 2025-06-04 22:40:54 +08:00
DacongDA
515d209063 feat: update go dependencies (#3855) 2025-06-03 16:38:06 +08:00
DacongDA
4e17dae2c2 feat: fix unable to remove user from group bug (#3847) 2025-05-28 22:29:40 +08:00
DacongDA
0ad4d82d9c feat: fix GetGroups() API bug when parentGroup is in next page (#3843) 2025-05-28 18:31:52 +08:00
DacongDA
731daf5204 feat: allow org admin to change org user's password without old password (#3841) 2025-05-28 01:23:44 +08:00
Khanbala Rashidov
b6b77da7cf feat: refactor the code in NewSmtpEmailProvider() (#3832) 2025-05-26 20:23:47 +08:00
DacongDA
8b4637aa3a feat: provide a more complete Excel template for uploading users and fix any bugs (#3831) 2025-05-25 21:23:48 +08:00
Leon Koth
87506b84e3 feat: support special chars like "+" in username parameter of /api/get-email-and-phone API (#3824) 2025-05-23 17:29:00 +08:00
People257
fed9332246 feat: can configure Domain field in Nextcloud OAuth provider (#3813) 2025-05-23 17:23:34 +08:00
DacongDA
33afc52a0b feat: can redirect user to login page after linking provider in prompt page (#3820) 2025-05-23 07:15:53 +08:00
Eko Eryanto
9035ca365a feat: improve Indonesia i18n translations (#3817) 2025-05-22 20:42:47 +08:00
DacongDA
b97ae72179 feat: use the standard user struct for JWT-Standard to get a correct userinfo (#3809) 2025-05-21 18:54:42 +08:00
DacongDA
9190db1099 feat: fix bug that token endpoint doesn't return 400/401 when type is object.TokenError (#3808) 2025-05-20 10:39:55 +08:00
DacongDA
1173f75794 feat: return HTTP status 400 instead of 200 in GetOAuthToken() (#3807) 2025-05-20 01:05:43 +08:00
Yang Luo
086859d1ce feat: change User.Avatar length back to 500 2025-05-18 09:47:56 +08:00
Yang Luo
9afaf5d695 feat: increase User.Avatar length to 1000 2025-05-17 19:59:17 +08:00
DacongDA
521f90a603 feat: fix access_token endpoint cannot read clientId in form when using device code flow (#3800) 2025-05-17 18:53:38 +08:00
DacongDA
4260efcfd0 feat: add useIdAsName field for WeCom OAuth provider (#3797) 2025-05-17 02:27:06 +08:00
DacongDA
d772b0b7a8 feat: fix bug that username will be random with useEmailAsUsername enabled (#3793) 2025-05-16 18:40:50 +08:00
DacongDA
702b390da1 feat: fix MFA preference doesn't work bug (#3790) 2025-05-15 21:04:36 +08:00
DacongDA
b15b3b9335 feat: support adapter in app.conf logConfig (#3784) 2025-05-14 08:27:11 +08:00
DacongDA
f8f864c5b9 feat: add logged-in IDP provider info to access token (#3776) 2025-05-11 09:51:51 +08:00
Yang Luo
90e790f83c feat: increase Application.SamlReplyUrl from 100 chars to 500 2025-05-10 22:42:40 +08:00
DacongDA
58413246f3 feat: fix bug that db not found error in createDatabaseForPostgres (#3765) 2025-05-05 18:25:58 +08:00
Yang Luo
8f307dd907 feat: upgrade go-teams-notify to v2.13.0 2025-05-05 01:02:27 +08:00
People257
fe42b5e0ba feat: improve checkGroupName() (#3759) 2025-05-03 22:47:42 +08:00
DacongDA
383bf44391 feat: support OIDC device flow: "/api/device-auth" (#3757) 2025-04-30 23:42:26 +08:00
DacongDA
36f5de3203 feat: allow jwks to include the certs from non-admin owner (#3749) 2025-04-28 09:31:56 +08:00
DacongDA
eae69c41d7 feat: add object field filter for webhook (#3746) 2025-04-26 22:05:36 +08:00
Khaled Omara
91057f54f3 feat: add Pbkdf2DjangoCredManager (#3745) 2025-04-25 16:16:50 +08:00
DacongDA
daa7b79915 feat: improve error handling of webauthn login (#3744) 2025-04-24 01:11:24 +08:00
DacongDA
d3a5539dae feat: fix loading status not reset issue when failed to login (#3743) 2025-04-24 00:57:52 +08:00
DacongDA
7d1c614452 feat: use random name as name if user's name is invalid when created by third party provider (#3742) 2025-04-23 21:30:19 +08:00
Yang Luo
e2eafa909b feat: fix MODEL_URL in FaceRecognitionModal 2025-04-21 09:10:30 +08:00
DacongDA
56bcef0592 feat: support application.formCss in forget-password page (#3733) 2025-04-19 22:59:21 +08:00
DacongDA
0860cbf343 feat: can specify content type and http body field mapping for Custom HTTP Email provider (#3730) 2025-04-17 01:59:11 +08:00
Maxime LUCE
2f4180b1b6 feat: add missing currencies in plan edit page (#3727) 2025-04-15 16:01:14 +08:00
DacongDA
e3d5619b25 feat: support custom HTTP headers in custom HttpEmailProvider and hide unused fields (#3723) 2025-04-13 23:52:04 +08:00
closeobserve
019fd87b92 feat: fix code comment typos (#3724) 2025-04-13 17:57:37 +08:00
Yang Luo
5c41c6c4a5 feat: add BRL currency 2025-04-11 22:24:45 +08:00
Jefferson Rodrigues
b7fafcc62b feat: improve InitFromFile() code order to fix GetOrganizationApplicationCount always returns 0 bug (#3720) 2025-04-11 01:43:54 +08:00
Yang Luo
493ceddcd9 feat: improve error handling in system info page 2025-04-11 01:41:27 +08:00
Gabriel Brecci
fc618b9bd5 feat: add validation for optional fields in IntrospectionToken for custom token types (#3717) 2025-04-09 22:27:19 +08:00
DacongDA
a00900e405 feat: fix sqlite bug for failed to lookup Client-side Discoverable Credential: user not exist (#3719) 2025-04-09 22:26:47 +08:00
Gabriel Brecci
77ef5828dd feat(introspection): return correct active status for expired or revoked tokens (#3716) 2025-04-09 02:00:30 +08:00
DacongDA
c11f013e04 feat: return "Active: false" for expired token in IntrospectToken() (#3714) 2025-04-08 23:20:44 +08:00
DacongDA
b3bafe8402 feat: fix bug that unable to query webauthnCredentials when db is mssql or postgres in GetUserByWebauthID() (#3712) 2025-04-08 17:51:32 +08:00
DacongDA
f04a431d85 feat: Casdoor's LDAP client supports LDAP server's self-signed certificates now (#3709) 2025-04-07 02:02:32 +08:00
WindSpiritSR
952538916d feat: check application existence in object.AddUser() (#3686) 2025-04-05 16:38:20 +08:00
Eng Zer Jun
18bb445e71 feat: update github.com/golang-jwt/jwt dependency to v5 (#3708) 2025-04-05 02:05:41 +08:00
DacongDA
cca88e2cb0 feat: fix bug that when email/sms mfa is not preferred, message will send to masked address (#3705) 2025-04-04 01:08:29 +08:00
Yang Luo
86c10fe0ab feat: change org.CountryCodes to mediumtext 2025-04-02 20:23:04 +08:00
DacongDA
c1b3bf0f45 feat: set button to loading status immediately after click (#3696) 2025-04-02 01:15:36 +08:00
DacongDA
62bda61af5 feat: can use provider_hint arg to do OAuth redirect automatically (#3698) 2025-04-02 01:15:20 +08:00
DacongDA
b6f943e326 feat: support WebAuthn login without username and upgrade Go to 1.21 (#3695) 2025-04-01 16:35:59 +08:00
DacongDA
2cc5e82d91 feat: support login button loading state (#3694) 2025-04-01 00:57:24 +08:00
DacongDA
e55cd94298 feat: fix issue that user email is still unverified after signup (#3685) 2025-03-29 21:24:01 +08:00
WindSpiritSR
08f7a05e61 feat: fix MFA + LDAP bug in /check-user-password API (#3681) 2025-03-26 22:11:58 +08:00
Yang Luo
4bee21f4a3 feat: use StaticBaseUrl in frontend 2025-03-26 21:32:31 +08:00
DacongDA
5417a90223 feat: fix bug that there is already an object named 'casbin_api_rule' in the database (#3680) 2025-03-25 22:24:58 +08:00
Yang Luo
131820e34e feat: add application.ForcedRedirectOrigin 2025-03-24 13:42:35 +08:00
WindSpiritSR
2fcbf7cf6c feat: fix apps page grid style (#3679) 2025-03-22 18:19:14 +08:00
WindSpiritSR
14ade8b7e4 feat: fix provider test API's missing owner and name args for auth (#3676) 2025-03-22 17:53:20 +08:00
WindSpiritSR
a11fe59704 feat: support widget items config in org (#3674) 2025-03-21 23:00:07 +08:00
Yang Luo
af55d0547f feat: improve frontend i18n strings 2025-03-21 21:03:29 +08:00
WindSpiritSR
81102f8298 feat: fix permission update bug when both org and model are modified (#3671) 2025-03-20 09:05:27 +08:00
DacongDA
141372cb86 feat: support face ID provider (#3666) 2025-03-19 22:57:35 +08:00
if0else9
15a037ca74 feat: increase frontend build memory to 4096 in Dockerfile (#3672)
297.8 FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
2025-03-19 10:40:34 +08:00
Cutsin
73c680d56f feat: avoid using body in GET requests for AirwallexClient payment provider (#3669) 2025-03-18 20:04:15 +08:00
WindSpiritSR
aafc16e4f4 feat: fix dynamic width of navbar UI (#3664) 2025-03-16 16:12:58 +08:00
ruanjiefeng
7be026dd1f feat: Support for selecting existing users or scanning a QR code when logging into Dingtalk (#3660) 2025-03-13 21:49:07 +08:00
Anton Berezhnyi
3e7938e5f6 feat: don't panic when provider not found in Login() API (#3659) 2025-03-13 21:35:51 +08:00
DacongDA
30789138e2 feat: fix faceId loop error caused by async (#3651) 2025-03-11 21:03:04 +08:00
DacongDA
9610ce5b8c feat: can add faceId by uploading images (#3641) 2025-03-09 01:29:25 +08:00
DacongDA
a39a311d2f feat: fix webhook bug in RecordEx JSON (#3642) 2025-03-08 00:20:59 +08:00
DacongDA
08e41ab762 feat: can specify user fields in webhook edit page (#3635) 2025-03-04 14:16:16 +08:00
DacongDA
85ca318e2f feat: can assign default group during signup (#3633) 2025-03-02 22:55:51 +08:00
DacongDA
9032865e60 feat: support mobile background for login page (#3629) 2025-03-01 23:01:15 +08:00
WindSpiritSR
5692522ee0 feat: update user language when the language changed on login page (#3628) 2025-03-01 22:28:20 +08:00
hsluoyz
cb1882e589 feat: fix MFA bug, revert PR: "feat: don't send verification code if failed signin limit is reached" (#3627) 2025-03-01 12:58:28 +08:00
Yang Luo
41d9422687 feat: increase username limit to 255 chars 2025-03-01 00:44:34 +08:00
Yang Luo
3297db688b feat: support shared cert in GetCert() API 2025-02-28 23:02:13 +08:00
DacongDA
cc82d292f0 feat: set frontend origin to 7001 if in dev mode (#3615) 2025-02-26 22:35:50 +08:00
Cliff
f2e3037bc5 feat: don't send verification code if failed signin limit is reached (#3616) 2025-02-26 22:34:14 +08:00
Lai Zn
d986a4a9e0 feat: fix bug that initialize group children as empty array instead of empty string (#3620) 2025-02-26 08:50:09 +08:00
DacongDA
2df3878c15 feat: fix bug that group.HaveChildren is never set to false bug Something isn't working (#3609) 2025-02-22 01:46:35 +08:00
DacongDA
24ab8880cc feat: fix bug that organization might be nil in some case and cause nil point error (#3608) 2025-02-21 23:43:30 +08:00
ners
f26b4853c5 feat: bump Go version to go 1.18 (#3599) 2025-02-21 13:10:17 +08:00
DacongDA
d78e8e9776 feat: fix LDAP filter condition will return nil if error happened (#3604) 2025-02-21 13:09:39 +08:00
WindSpiritSR
d61f9a1856 feat: update antd from 5.2.3 to 5.24.1 (#3593) 2025-02-18 20:54:10 +08:00
WindSpiritSR
aa52af02b3 feat: fix style props of Editor (#3590) 2025-02-17 13:39:49 +08:00
WindSpiritSR
2a5722e45b feat: add detail sidebar for record list page, improve token list page (#3589) 2025-02-16 22:01:25 +08:00
Mayank
26718bc4a1 feat: update signinUrl storage to include pathname and query parameters only to prevent new tab popup after password reset (#3587) 2025-02-14 20:31:36 +08:00
Yang Luo
f8d44e2dca feat: set default CountryCode for user 2025-02-14 16:54:25 +08:00
Yang Luo
26eea501be feat: don't use organization.MasterVerificationCode when sending 2025-02-14 16:54:25 +08:00
Mayank
63b8e857bc feat: update signinUrl storage to include path and query parameters in forced reset password flow (#3583) 2025-02-14 01:32:10 +08:00
WindSpiritSR
81b336b37a feat: replace react-codemirror2 with @uiw/react-codemirror (#3577)
Signed-off-by: WindSpiritSR <simon343riley@gmail.com>
2025-02-14 00:10:33 +08:00
DacongDA
9c39179849 feat: fix bug that user forbidden check will be skipped in OAuth login (#3580) 2025-02-13 13:14:44 +08:00
Bui Le Anh Nguyen
37d93a5eea feat: update SendgridEmailProvider to support dynamic host/path, add From name field (#3576)
* feat: add fields into UI FromName, Host, Endpoint

* feat: update SendgridEmailProvider support dynamic host/path client init, code convention
2025-02-13 00:51:31 +08:00
Yang Luo
e926a07c58 feat: add "User type" to user list page 2025-02-12 21:29:18 +08:00
Yang Luo
9c46344e68 feat: improve default org passwordOptions handling 2025-02-12 21:20:32 +08:00
WindSpiritSR
c0ec73dfd3 feat: fix tableNamePrefix doesn't work bug in /get-dashboard API (#3572) 2025-02-11 17:20:45 +08:00
Brian Yu
b1b6ebe692 feat(jwt): add azp claim to ID token (#3570)
Added the `azp` (Authorized Party) claim to various JWT token structures
including Claims, ClaimsShort, ClaimsWithoutThirdIdp, and ClaimsStandard.
Updated the generateJwtToken and getClaimsCustom functions to handle the
new claim. This change aligns with the OpenID Connect specification.
2025-02-10 20:44:44 +08:00
Yang Luo
a0931e4597 feat: add userTypes to Organization 2025-02-09 17:12:13 +08:00
DacongDA
c181006661 feat: cache theme in signup page (#3568) 2025-02-09 15:12:35 +08:00
Cutsin
2e83e49492 feat: fix bug due to null characters in descriptor when creating a payment intent (#3567) 2025-02-08 19:35:51 +08:00
Coki
5661942175 feat: add CLI version cache and proxy support (#3565)
* feat: add CLI version cache mechanism

* feat: add /api/refresh-engines to allowed endpoints in demo mode

* feat: add proxy support for cli downloader

* feat: add SafeGoroutine for CLIDownloader initialization

* refactor: optimize code structure
2025-02-08 19:34:19 +08:00
Coki
7f9f7c6468 feat: add CLI tools auto-downloader and updater (#3559)
* feat: add CLI downloader feature

* feat: add CLI refresh endpoint and scheduler

* feat: improve binary names mapping for different platforms and architectures

* fix: format binary names in getBinaryNames function

* fix: change file permission notation to octal in cli_downloader.go

* feat: add isDemoMode check for CLI downloader features
2025-02-07 19:22:56 +08:00
Cutsin
b7a818e2d3 feat: support AirWallex payment provider (#3558)
* feat: support AirWallex payment provider

* chore: add some information due to AirWallex's risk control policy
2025-02-07 19:19:30 +08:00
DacongDA
1a8cfe4ee6 feat: can fetch SAML metadata from URL (#3560) 2025-02-06 23:50:39 +08:00
hsluoyz
b3526de675 feat: add checkOrgMasterVerificationCode() 2025-02-06 23:46:22 +08:00
Mayank
3b9e08b70d feat: Fix reset password flow for shared application (#3556) 2025-02-06 18:03:23 +08:00
IZUMI-Zu
cfc6015aca feat: rename Casdoor app URL to authenticator (#3553) 2025-02-05 23:08:06 +08:00
hsluoyz
1600a6799a feat: return error for updateUsedByCode() 2025-02-05 13:40:41 +08:00
DacongDA
ca60cc3a33 feat: show SAML cert parse error better in frontend (#3551) 2025-02-05 10:06:02 +08:00
DacongDA
df295717f0 feat: can define what Casdoor pages an org admin can see via Organization.NavItems (#3539)
* feat: support define what Casdoor pages an org admin can see

* feat: remove useless code

* fix: fix NavItemNodes i18next invalid

* fix: only global admin can edit navItems

* fix: move navItem tree to extra file
2025-02-03 00:40:21 +08:00
DacongDA
e3001671a2 feat: fix bug that can not delete user if user doesn't belong to any group (#3544) 2025-02-02 17:54:05 +08:00
DacongDA
bbe2162e27 feat: fix bug in GetTokenByTokenValue() (#3541) 2025-01-30 00:48:20 +08:00
Coki
92b5ce3722 feat: add identifier validation for security in RunCasbinCommand (#3535)
* feat: add identifier validation for security in RunCasbinCommand

* refactor: update identifier validation to use SHA-256 hash and timestamp
2025-01-29 18:30:06 +08:00
hsluoyz
bad21fb6bb feat: check empty password in CheckPassword() 2025-01-28 21:13:59 +08:00
DacongDA
5a78dcf06d feat: fix Casbin Permissions Not Working When Auto-login is Enabled (#3537)
* fix: fix Casbin Permissions Not Working When Auto-login is Enabled

* fix: fix oauth fastLogin not support permission
2025-01-28 19:15:53 +08:00
DacongDA
558b168477 feat: can verify OTP during OAuth login (#3531)
* feat: support verify OTP during OAuth login

* fix: fail to login if mfa not enable

* fix: fail to login if mfa not enable

* fix: fix mfaRequired not valid in saml/auth
2025-01-27 19:37:26 +08:00
DacongDA
802b6812a9 feat: fix strange "Email is invalid" error in forget password page (#3527) 2025-01-23 14:35:11 +08:00
DacongDA
a5a627f92e feat: optimize get-groups API and GroupListPage (#3518)
* fix: optimize get-groups api and GroupListPage

* fix: fix linter issue
2025-01-23 09:47:39 +08:00
DacongDA
9701818a6e feat: delete groups for user while deleting user (#3525) 2025-01-23 09:46:33 +08:00
DacongDA
06986fbd41 feat: fix theme filter for other URLs like SAML (#3523)
* fix: fix error cause by theme filter

* fix: add saml url to theme filter and use getGetOwnerAndNameFromIdWithError instead of using GetOwnerAndNameFromId

* fix: fix code error

* fix: add support for cas and pack judgement into a function

* fix: fix linter err
2025-01-22 19:12:12 +08:00
hsluoyz
3d12ac8dc2 feat: improve HandleScim() 2025-01-22 16:15:19 +08:00
DacongDA
f01839123f feat: fix missing param recoveryCodes in /mfa/setup/enable API (#3520) 2025-01-21 22:56:02 +08:00
DacongDA
e1b3b0ac6a feat: allow user use other mfaType in mfa step and skip redundant MFA verification (#3499)
* feat: allow user use other mfaType in mfa step and skip redundant MFA verification

* feat: improve format
2025-01-21 20:16:18 +08:00
DacongDA
4b0a2fdbfc feat: append HTML document title and favicon to cookie (#3519)
* feat: append HTML document title and favicon to cookie

* feat: remove useless cookie
2025-01-21 19:42:21 +08:00
DacongDA
db551eb24a feat: LDAP user can reset password with old password and new password (#3516)
* feat: support user reset password with old password and new password

* feat: merge similar code
2025-01-20 21:42:05 +08:00
DacongDA
18b49bb731 feat: can reset LDAP password with different password encryption methods (#3513) 2025-01-20 20:00:23 +08:00
hsluoyz
17653888a3 feat: refactor the TestSmtpServer code 2025-01-20 03:17:09 +08:00
hsluoyz
ee16616df4 feat: support socks5Proxy for AWS Email provider 2025-01-20 02:39:23 +08:00
hsluoyz
ea450005e0 feat: fix "logo" bug in footer 2025-01-20 00:01:46 +08:00
DacongDA
4c5ad14f6b fix: spin will squeeze login panel (#3509) 2025-01-19 23:35:04 +08:00
DacongDA
49dda2aea5 feat: append footerHtml to cookie (#3508) 2025-01-19 23:34:43 +08:00
DacongDA
a74a004540 feat: append logo url to cookie (#3507) 2025-01-19 08:02:44 +08:00
DacongDA
2b89f6b37b feat: fix issue that application theme is ignored in appendThemeCookie() (#3506) 2025-01-18 21:28:39 +08:00
DacongDA
c699e35e6b feat: load theme from first HTML render cookie (#3505) 2025-01-18 19:04:16 +08:00
DacongDA
e28d90d0aa feat: support CUCloud SMN notification provider (#3502) 2025-01-17 08:35:31 +08:00
DacongDA
4fc7600865 feat: skip update user ranking if ranking not in accountItem (#3500) 2025-01-14 22:43:49 +08:00
Wind Li
19f62a461b feat: fix SAML's redirectUrl and POST ProtocolBinding (#3498) 2025-01-13 20:55:37 +08:00
DacongDA
7ddc2778c0 feat: show error message when organization doesn't have default application in invitation edit page (#3495)
* fix: inform user when organization haven't default application in signup page

* fix: include org name in the error message
2025-01-12 22:48:21 +08:00
DacongDA
b96fa2a995 feat: skip GetUserCount() if there is no quota limit (#3491) 2025-01-10 22:28:25 +08:00
hsluoyz
fcfb73af6e feat: increase org password field length to 200 2025-01-09 20:07:49 +08:00
hsluoyz
43bebc03b9 feat: fix crash in roleChangeTrigger() 2025-01-09 16:41:56 +08:00
WindSpiritSR
c5f25cbc7d feat: getPidByPort() supports alpine now (#3483)
Signed-off-by: WindSpiritSR <simon343riley@gmail.com>
2025-01-08 12:18:46 +08:00
Cutsin
3feb6ce84d feat: add Kwai OAuth provider (#3480)
* feat: add Kwai OAuth provider

* fix: incorrect parameter in getAuthUrl
2025-01-08 00:09:16 +08:00
hsluoyz
08d6b45fc5 feat: keeps "build" folder during yarn build 2025-01-07 23:38:50 +08:00
hsluoyz
56d0de64dc feat: support StopOldInstance() 2025-01-07 21:39:21 +08:00
DacongDA
1813e8e8c7 feat: return goroutine error in get-dashboard API (#3479) 2025-01-07 10:35:45 +08:00
DacongDA
e27c764a55 feat: fix bug that GitHub oauth provider shows error if failed to fetch user's email (#3474)
* fix: fix github idp will stop login if it cannot fetch user's email through al restful api

* Update github.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2025-01-05 20:25:42 +08:00
DacongDA
e5a2057382 feat: fix empty scope bug in RefreshToken API (#3467)
* fix: fix scope will be empty when user not passing scope in refresh api

* fix: promote code format
2025-01-02 12:53:17 +08:00
Yang Luo
8457ff7433 feat: support radiusDefaultOrganization in app.conf 2025-01-02 00:10:58 +08:00
DacongDA
888a6f2feb feat: add regex to restrict Email addresses in OAuth provider (#3465)
* feat: support use regex expression to limit email receiver address

* feat: limit in correct pos

* feat: promote code format

* feat: promote code format

* fix: fix linter issue
2025-01-02 00:00:57 +08:00
IZUMI-Zu
b57b64fc36 feat: add origin field for mfaAccountTable (#3463) 2024-12-29 22:51:21 +08:00
DacongDA
0d239ba1cf feat: improve the error message of GitHub OAuth provider (#3462) 2024-12-29 21:54:54 +08:00
DacongDA
8927e08217 feat: speed up GetDashboard() by only fetching last 30 days data (#3458)
* feat: only check 30 days data

* refactor: refactor GetDashboard to reduce code line

* refactor: refactor GetDashboard to reduce code line

* refactor: remove unused where

* fix: fix error code
2024-12-29 16:15:52 +08:00
DacongDA
0636069584 feat: only fetch created_time field to reduce data size in get-dashboard API (#3457) 2024-12-28 23:52:19 +08:00
Yang Luo
4d0f73c84e feat: fix Casdoor OAuth provider doesn't use domain field bug 2024-12-28 10:01:56 +08:00
reserved
74a2478e10 feat: Make MinIO storage provider region setting configurable (#3433)
* fix: Make MinIO provider region setting configurable

* Fix: Correct the issue where modifications to MinIO's default logic caused behavioral discrepancies
2024-12-23 16:07:14 +08:00
nano
acc6f3e887 feat: escape the avatal URL in CAS response (#3434) 2024-12-20 17:11:58 +08:00
Xin-Fax
185ab9750a feat: fix VerificationRecord.IsUsed JSON Field Mapping 2024-12-18 13:56:54 +08:00
Cliff
48adc050d6 feat: can pass empty user id on user update (#3443) 2024-12-18 07:56:44 +08:00
Coki
b0e318c9db feat: add localized tab titles for Basic and Advanced Editors (#3431)
* feat: add localized tab titles for Basic and Advanced Editors

* docs: update translations for model editor labels in multiple locales
2024-12-16 08:34:13 +08:00
Coki
f9a6efc00f feat: advanced model editor should support changing UI language (#3430) 2024-12-15 15:53:29 +08:00
DacongDA
bd4a6775dd feat: get github user email with user/emails api (#3428)
* feat: get user email use `user/emails` api

* feat: improve code format

* feat: improve code format
2024-12-15 10:28:18 +08:00
Coki
e3a43d0062 feat: improve the advanced editor of model edit page (#3427) 2024-12-15 02:07:02 +08:00
DacongDA
0cf281cac0 feat: fix record's password regex bug (#3421) 2024-12-11 08:43:03 +08:00
XIAOZHUOWU
7322f67ae0 feat: add model, adapter and enforcer to the dashboard page chart (#3413)
* [feature] Add more data (Model, Adapter, Enforcer) to the dashboard page chart #3379

* feat: add model, adapter, enforcer to dashboard
2024-12-09 16:07:39 +08:00
Xin-Fax
b927c6d7b4 feat: support LDAP's SetPassword (#3395)
* fix: Resolve the issue mentioned in #3392

* fix: Change checkLdapUserPassword to CheckLdapUserPassword.

* fix: the issue mentioned by hsluoyz.

* fix: Check if the user parameter is nil

* fix: use existing i18n message
2024-12-09 16:06:24 +08:00
nohup
01212cd1f3 feat: add AiAssistantUrl to frontend config (#3385) 2024-12-08 20:44:28 +08:00
Xinyu Ge
bf55f94d41 feat: support CUCloud OSS storage provider (#3400) 2024-12-08 20:24:38 +08:00
Yang Luo
f14711d315 feat: fix frontend bug 2024-12-07 21:53:01 +08:00
DacongDA
58e1c28f7c feat: support LDAPS protocol (#3390)
* feat: support ldaps

* fix: unencrypted port 389 not work after enable SSL
fix: remove useless conf and set ldapsCertId to empty
fix: return and log getTLSconfig error

* fix: remove unused setting

* fix: check nil condition

* fix: not log fail when certId is empty
2024-12-07 21:26:07 +08:00
Yang Luo
922b19c64b feat: reduce i18n items 2024-12-07 21:22:57 +08:00
DacongDA
1d21c3fa90 feat: fix issue that introspectionResponse uses Bearer instead of raw tokenType (#3399) 2024-12-05 20:59:30 +08:00
DacongDA
6175fd6764 feat: make token_type_hint optional (#3397) 2024-12-04 20:10:15 +08:00
Luckery
2ceb54f058 feat: support most popular currencies (#3388) 2024-12-01 21:46:44 +08:00
DacongDA
aaeaa7fefa feat: update go sms sender (#3386) 2024-11-29 23:00:34 +08:00
DacongDA
d522247552 feat: fix countryCode param bug in MFA login (#3384) 2024-11-29 21:46:06 +08:00
DacongDA
79dbdab6c9 feat: fix "dest is missing" bug in MFA login (#3383)
* feat: support stateless mfa setup

* Revert "feat: support stateless mfa setup"

This reverts commit bd843b2ff3.

* feat: use new implement

* fix: missing set field on login
2024-11-29 19:59:30 +08:00
DacongDA
fe40910e3b feat: support stateless MFA setup (#3382) 2024-11-29 19:50:10 +08:00
Xinyu Ge
2d1736f13a feat: Add more data to the dashboard page chart #3365 (#3375)
* test

* feat: #3365 add more dada to the dashboard page chart

* feat: #3365 Add more data to the dashboard page chart
2024-11-26 09:16:35 +08:00
ming.zhang
12b4d1c7cd feat: change LDAP attribute from cn to title for correct username mapping (#3378) 2024-11-26 09:13:05 +08:00
hamidreza abedi
a45d2b87c1 feat: Add translations for Persian (#3372) 2024-11-23 16:24:07 +08:00
DacongDA
8484465d09 feat: fix SAML failed to redirect issue when login api returns RequiredMfa (#3364) 2024-11-21 20:31:56 +08:00
Luckery
dff65eee20 feat: Force users to change their passwords after 3/6/12 months (#3352)
* feat: Force users to change their passwords after 3/6/12 months

* feat: Check if the password has expired by using the last_change_password_time field added to the user table

* feat: Use the created_time field of the user table to aid password expiration checking

* feat: Rename variable
2024-11-19 21:06:52 +08:00
Eng Zer Jun
596016456c feat: update CI's upload-artifact and download-artifact actions to v4 (#3361)
v3 of `actions/upload-artifact` and `actions/download-artifact` will be
fully deprecated by 5 December 2024. Jobs that are scheduled to run
during the brownout periods will also fail. See [1][2].

[1]: https://github.blog/changelog/2024-04-16-deprecation-notice-v3-of-the-artifact-actions/
[2]: https://github.blog/changelog/2024-11-05-notice-of-breaking-changes-for-github-actions/

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2024-11-19 00:07:59 +08:00
DacongDA
673261c258 feat: fix placeholder bug in signin page (#3359) 2024-11-17 00:14:26 +08:00
DacongDA
3c5985a3c0 fix: fix several bugs in samlRequest (#3358) 2024-11-17 00:14:04 +08:00
DacongDA
4f3d62520a feat: fix the dashboard page shows zero data in mobile phone (#3356) 2024-11-16 22:02:49 +08:00
DacongDA
96f8b3d937 feat: fix SAML metadata URL and XML generation issue when enablePostBinding is enabled (#3354) 2024-11-16 15:35:30 +08:00
Yang Luo
7ab5a5ade1 feat: add processArgsToTempFiles() to RunCasbinCommand() 2024-11-15 20:25:48 +08:00
Yang Luo
5cbd0a96ca Use json format for argString in RunCasbinCommand() 2024-11-15 18:27:25 +08:00
Yang Luo
7ccd8c4d4f feat: add RunCasbinCommand() API 2024-11-15 17:44:57 +08:00
ZhaoYP 2001
b0fa3fc484 feat: add Casbin CLI API to Casdoor (#3351) 2024-11-15 16:10:22 +08:00
Yang Luo
af01c4226a feat: add Organization.PasswordExpireDays field 2024-11-15 11:33:28 +08:00
DacongDA
7a3d85a29a feat: update github token to fix CI cannot release issue (#3348) 2024-11-14 18:05:56 +08:00
IZUMI-Zu
fd5ccd8d41 feat: support copying token to clipboard for casdoor-app (#3345)
* feat: support copy token to clipboard for casdoor-app auth

* feat: abstract casdoor-app related code
2024-11-13 17:06:09 +08:00
Yang Luo
a439c5195d feat: get token only by hash now, remove get-by-value backward-compatible code 2024-11-13 17:04:27 +08:00
Yang Luo
ba2e997d54 feat: fix CheckUpdateUser() logic to fix add-user error 2024-11-06 08:34:13 +08:00
Luckery
0818de85d1 feat: fix username checks when organization.UseEmailAsUsername is enabled (#3329)
* feat: Username support email format

* feat: Only fulfill the first requirement

* fix: Improve code robustness
2024-11-05 20:38:47 +08:00
Yang Luo
457c6098a4 feat: fix MFA empty CountryCode bug and show MFA error better in frontend 2024-11-04 16:17:24 +08:00
Yang Luo
60f979fbb5 feat: fix MfaSetupPage empty bug when user's signup application is empty 2024-11-04 00:04:47 +08:00
Luckery
ff53e44fa6 feat: use virtual select UI in role edit page (#3322) 2024-11-03 20:05:34 +08:00
Yang Luo
1832de47db feat: fix bug in CheckEntryIp() 2024-11-03 20:00:52 +08:00
Yang Luo
535eb0c465 fix: fix IP Whitelist field bug in application edit page 2024-11-03 19:55:59 +08:00
ithilelda
c190634cf3 feat: show Domain field for Qiniu storage provider (#3318)
allow Qiniu Provider to edit the Domain property in the edit page.
2024-10-27 14:10:58 +08:00
Cliff
f7559aa040 feat: set created time if not presented in AddUser() API (#3315) 2024-10-24 23:06:05 +08:00
DacongDA
1e0b709c73 feat: pass signin method to CAS login to fix bug (#3313) 2024-10-24 14:56:12 +08:00
DacongDA
c0800b7fb3 feat: add util.IsValidOrigin() to improve CORS filter (#3301)
* fix: CORS check issue

* fix: promote format

* fix: promote format

* fix: promote format

* fix: promote format

* Update application.go

* Update cors_filter.go

* Update validation.go

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-10-20 20:09:21 +08:00
eya46
6fcdad2100 feat: fix bug that fails to login when PasswordObfuscator is enabled (#3299) 2024-10-19 23:09:59 +08:00
Cliff
69d26d5c21 feat: add-user/update-user API should check if username/id/email/phone has duplicated with existing user (#3295) 2024-10-18 22:18:37 +08:00
DacongDA
94e6b5ecb8 feat: fix bug in SetPassword() API (#3296) 2024-10-18 20:50:43 +08:00
DacongDA
95e8bdcd36 feat: add initDataNewOnly to app.conf to skip overriding existing data in initDataFromFile() (#3294)
* feat: support control whether overwrite existing data during initDataFromFile

* feat: change conf var name

* feat: change conf var name
2024-10-18 00:08:08 +08:00
liuaiolos
6f1f93725e feat: fix GetAllActions()'s bug (#3289) 2024-10-16 21:55:06 +08:00
DacongDA
7ae067e369 feat: only admin can specify user in BuyProduct() (#3287)
* fix: balance can be used without login

* fix: balance can be used without login

* fix: fix bug

* fix: fix bug
2024-10-16 00:02:04 +08:00
Yang Luo
dde936e935 feat: fix null application crash in CheckEntryIp() 2024-10-15 22:11:15 +08:00
Yang Luo
fb561a98c8 feat: fix null user crash in RefreshToken() 2024-10-15 21:38:33 +08:00
ZhaoYP 2001
7cd8f030ee feat: support IP limitation for user entry pages (#3267)
* feat: support IP limitation for user entry pages

* fix: error message, ip whiteList, check_entry_ip

* fix: perform checks on the backend

* fix: change the implementation of checking IpWhitelist

* fix: add entryIpCheck in SetPassword and remove it from VerifyCode

* fix: remove additional error message pop-ups

* fix: add isRestricted and show ip error in EntryPage.js

* fix: error message

* Update auth.go

* Update check_ip.go

* Update check_ip.go

* fix: update return value of the check function from string to error

* fix: remoteAddress position

* fix: IP whitelist

* fix: clientIp

* fix:add util.GetClientIpFromRequest

* fix: remove duplicate IP and port separation codes and remove extra special characters after clientIp

* fix: gofumpt

* fix: getIpInfo and localhost

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-10-15 20:40:14 +08:00
Yang Luo
a3f8ded10c feat: refactor util.GetClientIpFromRequest() 2024-10-15 12:22:38 +08:00
DacongDA
e3d135bc6e feat: improve MFA desc text (#3284)
* fix: fix i18n error for mfa

* fix: fix i18n error for mfa

* fix: promote translate
2024-10-14 18:31:48 +08:00
千石
fc864b0de4 feat: support ".login-panel-dark" CSS for signup/login pages (#3269)
* feat: add custom dark mode CSS for login and registration forms.

* refactor: extract dark theme check to Setting.js
2024-10-13 22:31:54 +08:00
ZhaoYP 2001
3211bcc777 feat: add getCaptchaRule() to fix bug (#3281)
* feat: update captcha rule when the login page component is mounted

* fix: remove enableCaptchaModel from the state of the login page to avoid inconsistency issues

* fix: use this.getApplicationObj() instead of this.props.application
2024-10-12 10:02:45 +08:00
DacongDA
9f4430ed04 feat: fix MFA's i18n error (#3273) 2024-10-08 21:58:06 +08:00
Yang Luo
05830b9ff6 feat: update import lib: github.com/casdoor/ldapserver 2024-10-08 19:18:56 +08:00
千石
347b25676f feat: dark mode now works for login/signup pages too (#3252)
* fix: trying to fix dark mode not applying on login/registration interface

* fix: trying to fix dark mode not applying on login/registration interface

* fix: trying to fix dark mode not applying on login/registration interface

* fix: Clean up unused code

* fix: loginBackgroundDark move to App.less

* fix: fix typo
2024-10-05 21:26:25 +08:00
DacongDA
2417ff84e6 feat: support initial group assignment for new invited users via invitation.SignupGroup field (#3266) 2024-10-04 20:15:51 +08:00
DacongDA
468631e654 feat: support "All" in organization's country codes (#3264) 2024-10-03 22:58:09 +08:00
ZhaoYP 2001
e1dea9f697 feat: add organization's PasswordObfuscator to obfuscate login API's password (#3260)
* feat: add PasswordObfuscator to the login API

* fix: change key error message

* fix: remove unnecessary change

* fix: fix one

* fix: fix two

* fix: fix three

* fix: fix five

* fix: disable organization update when key is invalid

* fix: fix six

* fix: use Form.Item to control key

* fix: update obfuscator.js

* Update obfuscator.go

* Update obfuscator.go

* Update auth.go

* fix: remove real-time key monitoring

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-10-03 10:38:37 +08:00
Corey Gaspard
c0f22bae43 feat: better handling of organization.AccountItems on init_data import (#3263)
* Better handling of accountitems on init_data import.

* Removed commented code.

* Update init_data.go

* Update init_data.go

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-10-03 08:49:09 +08:00
DacongDA
c9635d9e2b feat: improve i18n (#3259) 2024-10-01 00:10:49 +08:00
DacongDA
3bd52172ea feat: add Hide-Password option for signin method rule field (#3258) 2024-09-30 23:31:41 +08:00
Yang Luo
bf730050d5 feat: increase Organization.Favicon to 200 chars 2024-09-29 11:45:56 +08:00
Yang Luo
5b733b7f15 feat: improve filterRecordIn24Hours() logic 2024-09-29 11:45:15 +08:00
ZhaoYP 2001
034f28def9 feat: logout if app.conf's inactiveTimeoutMinutes is reached (#3244)
* feat: logout if there's no activities for a long time

* fix: change the implementation of updating LastTime

* fix: add logoutMinites to app.conf

* fix: change the implementation of judgment statement

* fix: use sync.Map to ensure thread safety

* fix: syntax standards and Apache headers

* fix: change the implementation of obtaining logoutMinutes in app.conf

* fix: follow community code standards

* fix: <=0 or empty means no restriction

* Update logout_filter.go

* Update app.conf

* Update main.go

* Update and rename logout_filter.go to timeout_filter.go

* Update app.conf

* Update timeout_filter.go

* fix: update app.conf

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-09-27 01:18:02 +08:00
DacongDA
c86ac8e6ad feat: fix UTF-8 charset for Alipay IdP (#3247) 2024-09-27 00:59:52 +08:00
Jack Merrill
d647eed22a feat: add OIDC WebFinger support (#3245)
* feat: add WebFinger support

* lint: used gofumpt

* oidc: ensure webfinger rel is checked
2024-09-26 13:06:36 +08:00
Yang Luo
717c53f6e5 feat: support enableErrorMask2 config 2024-09-25 19:37:14 +08:00
千石
097adac871 feat: support single-choice and multi-choices in signup page (#3234)
* feat: add custom signup field

* feat: support more field in signup page

* feat: support more field in signup page

* feat: support more field in signup page

* feat: Reduce code duplication in form item rendering

* feat: Simplify gender and info checks using includes

* feat: update translate

* Revert "feat: update translate"

This reverts commit 669334c716.

* feat: address feedback from hsluoyz
2024-09-25 12:48:37 +08:00
IZUMI-Zu
74543b9533 feat: improve QR code for casdoor-app (#3226)
* feat: simplify login url for casdoor-app

* feat: add token check

* fix: improve logic
2024-09-23 22:27:58 +08:00
Yang Luo
110dc04179 feat: Revert "feat: fix permission problem in standard image" (#3231)
This reverts commit 6464bd10dc.
2024-09-23 22:19:27 +08:00
DacongDA
6464bd10dc feat: fix permission problem in standard image (#3228) 2024-09-23 18:40:39 +08:00
Yang Luo
db878a890e feat: add type and options to signup items 2024-09-21 23:40:29 +08:00
Yang Luo
12d6d8e6ce feat: fix cookie expire time too short bug 2024-09-21 22:45:13 +08:00
Yang Luo
8ed6e4f934 feat: improve UI for "No account?" 2024-09-21 07:35:33 +08:00
limingxie
ed9732caf9 feat: add condition for getWebBuildFolder function (#3219) 2024-09-20 23:59:13 +08:00
Blackcbears
0de4e7da38 feat: fix organization pagination count error (#3215)
* fix(organization): ensure count includes shared organizations

Adjust the `GetOrganizationCount` function to account for shared organizations by adding
an additional parameter and modifying the count query accordingly. This change ensures that
the organization count correctly reflects shared organizations within the system.

* ```fix(organization): optimize GetOrganizationCount query

Refactor the GetOrganizationCount function to use a more efficient search
method by leveraging the 'is_shared' field directly in the query condition.
This change improves the performance for counting organizations by avoiding
unnecessary iteration over potentially large result sets.
```

---------

Co-authored-by: CuiJing <cuijing@tul.com.cn>
2024-09-20 23:58:46 +08:00
Yang Luo
a330fbc11f docs: fix Docker link 2024-09-17 20:45:32 +08:00
Coki
ed158d4981 feat: support advanced editor in model edit page (#3176)
* feat: integrate external model editor and handle message events for model updates

* feat: add CasbinEditor and IframeEditor components for model editing

* feat: add tabbed editor interface for CasbinEditor

* fix: Synchronize content between basic and advanced editors

* refactor: simplify CasbinEditor and ModelEditPage components

* refactor: Refactor CasbinEditor for improved iframe initialization and model synchronization

* refactor: update default state of CasbinEditor active tab to "advanced

* chore: add Apache License header to CasbinEditor.js and IframeEditor.js files

* refactor: update CasbinEditor class names for consistency
2024-09-16 22:25:25 +08:00
千石
8df965b98d feat: improve SAML XML's xmlns to fix SAML support for some clouds (#3207) 2024-09-16 08:01:28 +08:00
千石
2c3749820e feat: add application.UseEmailAsSamlNameId field for SAML (#3203)
* feat: Add option to use email as SAML NameID based on application config

- Updated NewSamlResponse11 to accept an application parameter.
- Conditionally set SAML NameIdentifier to user's email or username based on application.UseEmailAsNameId.

* refactor: Update GetValidationBySaml to pass application to NewSamlResponse11

- Modified GetValidationBySaml function to include application parameter in NewSamlResponse11 call.

* feat: Rename field and update logic for using Email as SAML NameID

- Renamed the `UseEmailAsNameId` field to `UseEmailAsSamlNameId` in the `Application` struct.
- Updated `NewSamlResponse` and `NewSamlResponse11` functions to use `UseEmailAsSamlNameId` for setting the NameID value.
- Modified `ApplicationEditPage.js` to reflect the field name change and update the corresponding logic.
2024-09-15 23:00:50 +08:00
ZhaoYP 2001
0b17cb9746 feat: make Organization.EnableSoftDeletion and User.IsDeleted work (#3205)
* feat: make Organization.EnableSoftDeletion and User.IsDeleted work

* fix: add handling of the situation where organization is nil
2024-09-15 14:35:44 +08:00
ZhaoYP 2001
e2ce9ad625 feat: handle null account item issue in CheckPermissionForUpdateUser() (#3202)
* feat: improve the logic of the permission check code for users to modify account items

* fix: add skip operation for deleted account items in update-user API

* fix: add the function of removing deleted account item
2024-09-14 15:00:10 +08:00
DacongDA
64491abc64 feat: fix CORS issue of /api/acs for SAML IdP (#3200)
* fix: fix CORS problem of /api/acs when login with saml idp

* fix: fix origin get null when receive post with http protocol
2024-09-14 12:48:51 +08:00
ZhaoYP 2001
934a8947c8 feat: fix CAS logout failure caused by Beego session update problem (#3194)
* feat: fix the cas logout failure caused by beego session update problem

* fix: simplify the implementation of logout timer

* fix: change the location of the login success code

* fix: add i18n to CasLogout.js
2024-09-10 21:31:37 +08:00
IZUMI-Zu
943edfb48b feat: support QR login for casdoor app (#3190)
* feat: add MFA devices QR code to UserEditPage

* chore: remove mfa devices
2024-09-08 22:38:13 +08:00
Yang Luo
0d02b5e768 feat: remove disabled state in syncer.table 2024-09-07 21:08:21 +08:00
Yang Luo
ba8d0b5f46 feat: Revert "feat: Users added through LDAP cannot log in using the set password" (#3186)
This reverts commit 973a1df6c2.
2024-09-07 20:55:14 +08:00
DacongDA
973a1df6c2 feat: Users added through LDAP cannot log in using the set password (#3175)
* fix: login will prioritize the use of password set in casdoor and use ldap when use LDAP option in login form or user never change their password in casdoor after sync

* fix: promote if statement
2024-09-06 10:31:34 +08:00
DacongDA
05bfd3a3a3 feat: fix bug that custom SAML providers are removed by GetMaskedApplication() (#3165) 2024-09-05 20:08:56 +08:00
Yang Luo
69aa3c8a8b feat: Revert "feat: add Casbin editor's checking in model editor" (#3167)
This reverts commit a1b010a406.
2024-09-03 21:59:06 +08:00
Coki
a1b010a406 feat: add Casbin editor's checking in model editor (#3166)
* feat: add model syntax linting and update dependencies

* refactor: move model linter logic to separate module
2024-09-03 21:32:45 +08:00
DacongDA
89e92cbd47 feat: when using basic auth to fetch access_token will return restful response to oidc client (#3164) 2024-09-03 08:05:29 +08:00
ZhaoYP 2001
d4c8193357 feat: support reCAPTCHA v3 captcha provider (#3160)
* feat: support reCAPTCHA v3 captcha provider

* fix: modify the implementation of row component style in CaptchaModal.js
2024-09-02 22:15:03 +08:00
DacongDA
9b33800b4c feat: add email_verified, phone_number and phone_number_verified field for standard jwt token (#3156)
* feat: add email_verified, phone_number and phone_number_verified field for standard jwt token

* fix: fix linter err
2024-08-31 12:49:39 +08:00
DacongDA
ec98785172 feat: certEditPage will be redirected to 404 when name is changed (#3154) 2024-08-30 23:04:50 +08:00
DacongDA
45dd4cc344 feat: fix nonce not parsed issue in fastAutoSignin() (#3153)
* fix: fix nonce none passed when auto sign enabled

* fix: fix query error
2024-08-30 22:29:23 +08:00
DacongDA
1adb172d6b feat: add more crypto algorithm for jwt signing (#3150)
* feat: add more algorithm support for JWT signing

* feat: add i18n support

* feat: add i18n support

* feat: optimize if statement

* fix: remove additional space line
2024-08-30 16:59:41 +08:00
DacongDA
c08f2b1f3f feat: support Casdoor storage provider (#3147)
* feat: support Casdoor storage provider

* fix: fix code format and nil pointer error

* feat: change cert if statement
2024-08-27 23:54:03 +08:00
Yang Luo
62bb257c6d feat: make Resource.Url length to 500 2024-08-26 23:57:41 +08:00
Love98
230a77e3e3 feat: add captcha page (#3144) 2024-08-26 23:22:53 +08:00
Yang Luo
dce0a96dea feat: improve uploaded file URL 2024-08-26 21:41:28 +08:00
千石
65563fa0cd feat: Ensure MFA email and phone are validated before enabling (#3143)
Added validation checks to ensure that a user's email and phone number are provided before enabling MFA email and phone respectively. This fixes the issue where MFA could be enabled without these values, causing inconsistencies.
2024-08-26 08:40:22 +08:00
DacongDA
f2a94f671a feat: complete i18n translation (#3141)
* feat: complete i18n translation

* fix: fix problem in cs/data
2024-08-24 23:27:59 +08:00
DacongDA
1460a0498f feat: support assign a default group for synchronized from external openldap (#3140)
* feat: support default sync group for ldap (with without add i18n translate)

* feat: improve translation

* feat: update all i18n translation

* revert: remove new i18n translation
2024-08-24 00:12:52 +08:00
Yang Luo
adc63ea726 feat: fix wrong error alert in ApiFilter's getObject() 2024-08-23 23:36:55 +08:00
Yang Luo
0b8be016c5 feat: add enableErrorMask config 2024-08-23 22:19:17 +08:00
Yang Luo
986dcbbda1 feat: handle error in ApiFilter 2024-08-23 21:50:48 +08:00
Yang Luo
7d3920fb1f feat: add ManagedAccounts to JWT 2024-08-20 22:23:58 +08:00
Yang Luo
b794ef87ee feat: Revert "feat: support reCAPTCHA v3 captcha provider" (#3135)
This reverts commit a0d6f2125e.
2024-08-20 17:56:53 +08:00
ZhaoYP 2001
a0d6f2125e feat: support reCAPTCHA v3 captcha provider (#3130) 2024-08-20 17:29:37 +08:00
Yang Luo
85cbb7d074 feat: add replaceAll polyfill to be compatible with Firefox 68 2024-08-17 18:37:21 +08:00
June
fdc1be9452 feat: add provider.Bucket to fileUrl response and TrimPrefix "/" before delete GCS object (#3129)
* feat: add provider.Bucket to fileUrl response

* feat: TrimPrefix "/" before Google Cloud Storage delete object
2024-08-17 11:46:58 +08:00
June
2bd7dabd33 feat: allow custom Domain of Google Cloud Storage Provider (#3128) 2024-08-15 23:28:36 +08:00
June
9b9a58e7ac feat: update casdoor/oss version to support Google Cloud's Application Default Credentials (#3125) 2024-08-15 13:45:27 +08:00
Zheming Bao
38e389e8c8 feat: Pagination not updating after last item deletion (#3120) 2024-08-13 16:09:16 +08:00
DacongDA
ab5fcf848e feat: support accessKey and accessSecret login in AutoSigninFilter (#3117) 2024-08-12 12:20:41 +08:00
Yang Luo
b4e51b4631 feat: improve error message in GetFailedSigninConfigByUser() 2024-08-10 09:31:46 +08:00
DacongDA
45e25acc80 feat: fix JWT generate issue cause by shared application (#3113)
* fix: fix jwt generate cause by shared application

* fix: fix built-in org will not add -org-
2024-08-09 22:48:44 +08:00
Yang Luo
97dcf24a91 feat: improve error message in GetAuthorizationCodeToken() 2024-08-09 21:06:23 +08:00
DacongDA
4c0fff66ff feat: support shared application across organizations (#3108)
* feat: support share application

* revert: revert i18n

* fix: improve code format

* fix: improve code format and move GetSharedOrgFromApp to string.go
2024-08-09 15:43:25 +08:00
Yang Luo
e7230700e0 feat: Revert "feat: fix Beego session delete concurrent issue" (#3105)
This reverts commit f21aa9c0d2.
2024-08-07 16:51:54 +08:00
Alan Xu
f21aa9c0d2 feat: fix Beego session delete concurrent issue (#3103) 2024-08-07 16:29:35 +08:00
Ondřej Šibrava
4b2b875b2d feat: Czech, Slovak localization (#3095)
* feat: add l10n Czech, Slovak language support

* feat: i18n Czech, Slovak translation
2024-08-02 09:39:47 +08:00
DacongDA
df2a5681cc feat: add missing account items in CheckPermissionForUpdateUser() (#3094) 2024-08-01 23:34:12 +08:00
DacongDA
ac102480c7 feat: support Radius Challenge/Response for MFA (RFC2865) feature request (#3093)
* feat: support RFC2865 for radius server when user enable TOTP mfa

* fix: fix linter err
2024-08-01 22:02:49 +08:00
千石
feff47d2dc feat: skip agreement check when the terms are not visible (#3088) 2024-07-30 14:04:03 +08:00
千石
79b934d6c2 feat: enforce acceptance of terms and conditions for social logins (#3087)
* feat: Enforce acceptance of terms and conditions for social logins (#2975)

* feat: add error message for agreement acceptance
2024-07-29 17:22:48 +08:00
DacongDA
365449695b fix: fix application field in invitationEditPage will use translation of "All" as value (#3085) 2024-07-29 01:35:28 +08:00
DacongDA
55a52093e8 feat: fix bug that user can signup without invitation code via OAuth (#3084)
* fix:fix user can signup without invitation code when using 3rd oauth

* fix:use correct i18n translation
2024-07-29 00:59:02 +08:00
Giang Dinh
e65fdeb1e0 feat: ABAC support for /api/batch-enforce endpoint (#3082) 2024-07-27 09:43:58 +08:00
千石
a46c1cc775 feat: update WeCom OAuth URLs (#3080) 2024-07-26 22:03:24 +08:00
DacongDA
5629343466 feat: fix missing extendApplicationWithSigninMethods() in getDefaultApplication() (#3076) 2024-07-24 22:30:15 +08:00
王天成
3718d2dc04 feat: improve name mapping in LarkIdProvider (#3075)
* fix: change user identifier to the `user_id` field in IdP Lark, and use Chinese name to be the display name

* Update lark.go

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-07-23 21:12:53 +08:00
Mohammad Yosefpor
38b9ad1d9f feat: Add Support for memberOf Overlay in LDAP Server (#3068)
* feat: Allow All Users to Perform LDAP Search Lookups in their org

* feat: add ldap member of support
2024-07-21 01:25:42 +08:00
IZUMI-Zu
5a92411006 feat: add MFA accounts table (#3066)
* feat: add mfa accounts store

* fix: change MFA to Mfa

* fix: change MFA to Mfa

* fix: delete api
2024-07-20 22:51:15 +08:00
Mohammad Yosefpor
52eaf6c822 feat: Allow All Users to Perform LDAP Search Lookups in their org (#3064) 2024-07-20 20:44:29 +08:00
DacongDA
cc84709151 feat: add webhook support for invoice-payment and notify-payment (#3062) 2024-07-20 12:49:34 +08:00
Yang Luo
22fca78be9 feat: fix bug in AdapterEditPage 2024-07-19 00:57:56 +08:00
DSP
effd257040 feat: fix isPasswordWithLdapEnabled logic in handleBind() for redirecting to other LDAP sources (#3059)
* Added parameters to function call in server.go

Added needed parameters for redirection to other LDAP sources to function correctly and not always run into the "wrong credentials" error

* Update server.go

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-07-18 21:04:17 +08:00
Yang Luo
a38747d90e feat: fix bug in GetPolicies() 2024-07-18 18:40:55 +08:00
ZhaoYP 2001
da70682cd1 feat: fix bug in obtaining Casdoor version in Docker (#3056) 2024-07-16 18:13:44 +08:00
ZhaoYP 2001
4a3bd84f84 feat: fix the problem of abnormal tour when refreshing (#3054)
* fix: fix the problem of abnormal tour when refreshing

* fix: change the way enableTour configuration is stored
2024-07-12 19:27:55 +08:00
DacongDA
7f2869cecb feat: link transaction with balance and payment (#3052)
* feat: add and update transaction when recharging

* feat: add pay with balance

* feat: improve code format

* feat: update icon url for balance
2024-07-12 15:48:37 +08:00
DacongDA
cef2ab213b feat: add JWT-Standard format to fix oidc address type problem (#3050)
* feat: add JWT-Standard option to return standard OIDC UserInfo

* fix: fix error occurs by different claim type

* feat: improve code format and add missing return
2024-07-12 09:36:50 +08:00
Zhen Xiao
cc979c310e feat: OAuth provider lark supports getting phone number (#3047) 2024-07-11 08:56:28 +08:00
Yang Luo
13d73732ce fix: improve initBuiltInOrganization() 2024-07-10 14:18:30 +08:00
赵尧鹏
5686fe5d22 feat: use orgnization logo as tour logo and allow to configure whether to enable tour in organization edit page (#3046) 2024-07-10 14:18:04 +08:00
Yang Luo
d8cb82f67a feat: upgrade CI Node.js version to 20 2024-07-09 13:09:40 +08:00
赵尧鹏
cad2e1bcc3 feat: don't drop empty table for adapters (#3043)
* fix: solve the problem of update operation returning 'unaffected'

* feat: remove the action for Dropping empty adapter data table
2024-07-09 11:35:22 +08:00
赵尧鹏
52cc2e4fa7 feat: fix bug in permission's owner edit (#3041) 2024-07-06 11:24:08 +08:00
Leon Koth
8077a2ccba feat: fix bug for access key and secret login (#3022)
* fix: get username for keys

* chore: move user nil check
2024-06-27 21:24:54 +08:00
Eric Luo
4cb8e4a514 feat: Revert "feat: fix OIDC address field" (#3020)
This reverts commit 2f48d45773.
2024-06-25 16:14:26 +08:00
Husile
2f48d45773 feat: fix OIDC address field (#3013)
* feat:add fields of sync-database

* feat:add fields of sync-database

* feat: add several fields related to the OIDC specification address

* feat: add the field Address to Address structure in UserWithoutThirdIdp

* fix: delete redundant fields

* fix: add Address struct and delete redundant fields
2024-06-25 11:54:34 +08:00
Grégoire
cff0c7a273 feat: support "Use Email as username" in org (#3002)
Signed-off-by: Grégoire Bélorgey <gregoire@jianda.fr>
2024-06-22 16:52:11 +08:00
DacongDA
793a7d6cda feat: add free charge price mode for product buy page (#3015)
* feat: add free charge price mode for product buy page

* fix: improve code format
2024-06-22 14:05:53 +08:00
ailiujiarui
4cc2120fed feat: fix the top Navbar UI is broken issue (#3000) 2024-06-09 17:05:04 +08:00
Yang Luo
93b0f52f26 feat: Revert "feat: fix cannot create "/files" folder issue in local file storage provider in Docker" (#2997)
This reverts commit e228045e37.
2024-06-06 11:09:02 +08:00
DacongDA
e228045e37 feat: fix cannot create "/files" folder issue in local file storage provider in Docker (#2994) 2024-06-06 10:49:56 +08:00
DacongDA
6b8c24e1f0 feat: fix password not encrypted issue in SetPassword() API (#2990)
* fix: fix password not encrypted in set password and password type not changed

* Update user.go

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-06-04 13:32:13 +08:00
DacongDA
8a79bb64dd feat: test SMTP connection with browser parameters (#2986) 2024-06-04 01:34:36 +08:00
DacongDA
e5f9aab28f feat: support resetting password on first login (#2980)
* feat: support reset password in first login

* feat: disable needUpdatePassword when user haven't email and phone and mfa
2024-06-02 01:00:55 +08:00
Yang Luo
7d05b69aac feat: remove useless code 2024-05-28 20:33:55 +08:00
DacongDA
868e66e866 feat: fix QQ login error when using mobile browser (#2971) 2024-05-27 01:07:15 +08:00
Husile
40ad3c9234 feat: support MFA fields in syncer (#2966)
* feat:add fields of sync-database

* feat:add fields of sync-database
2024-05-27 01:06:59 +08:00
Alex Babel
e2cd0604c2 feat: add back arm64 support in Docker image (#2969) 2024-05-26 01:22:49 +08:00
Yang Luo
78c3065fbb feat: fix address field bug in user edit page 2024-05-24 17:19:27 +08:00
DacongDA
af2a9f0374 feat: get phone number and country from Google OAuth provider (#2965)
* feat: get phone number and country from Google OAuth provider

* feat: fix i18n
2024-05-23 00:42:36 +08:00
DacongDA
bfcfb56336 feat: add address line 1 and 2 in web UI (#2961) 2024-05-19 23:55:38 +08:00
DacongDA
c48306d117 feat: check signup item email regex in signup page (#2960)
* feat: check email regex in frontend

* Update SignupPage.js

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-05-19 22:07:34 +08:00
DacongDA
6efec6b4b5 feat: support "label" field for signin item table (#2956) 2024-05-19 03:07:36 +08:00
DacongDA
2daf26aa88 feat: use lowercase username when isUsernameLowered is enabled (#2952)
* feat: auto trim username during login and lowercase when isUsernameLowered enabled in conf

* fix: fix linter error

* fix: fix linter error

* fix: fix linter error
2024-05-17 11:43:19 +08:00
DacongDA
21c151bcf8 feat: fix password not updated bug when updating syncer (#2945) 2024-05-13 00:12:35 +08:00
DacongDA
b6b0b7d318 feat: support checking whether send-webhook API has error (#2944)
* feat: add webhook response for record

* refactor: refactor SendWebhook and use readall to read response body

* fix: improve code format

* fix: improve code format

* fix: improve code format
2024-05-12 20:30:15 +08:00
Yang Luo
0ecc1d599f feat: fix bug in AddUsersInBatch() 2024-05-11 16:59:33 +08:00
Yang Luo
3456fc6695 fix: update go-sms-sender to v0.23.0 2024-05-10 14:05:53 +08:00
DacongDA
c302dc7b8e fix: fix bug when init plan and pricing and record (#2934)
* fix: fix potential bugs in init data

* fix: improve code format

* fix: fix bug when init plan and pricing and record
2024-05-07 23:33:01 +08:00
DacongDA
d24ddd4f1c feat: fix potential bugs in init_data.go (#2932)
* fix: fix potential bugs in init data

* fix: improve code format
2024-05-07 23:11:08 +08:00
Yang Luo
572616d390 fix: fix bug in ProviderItem.CountryCodes 2024-05-07 17:17:45 +08:00
Yang Luo
2187310dbc feat: fix bug in initDefinedOrganization() 2024-05-06 13:57:08 +08:00
DacongDA
26345bb21b feat: add sms provider sendcloud (#2927) 2024-05-06 13:38:55 +08:00
DacongDA
e0455df504 feat: improve record content masking (#2923)
* feat: hide password in record

* feat: improve code format

* feat: improve code format
2024-05-05 12:42:09 +08:00
DacongDA
1dfbbf0e90 feat: fix bug that fails to import built-in org via init_data.json (#2922) 2024-05-05 01:06:15 +08:00
Yang Luo
d43d58dee2 feat: fix getProviders() owner bug in product edit page 2024-05-01 18:04:50 +08:00
Yang Luo
9eb4b12041 fix: rename to countryCodes for UI 2024-05-01 11:44:21 +08:00
Yang Luo
3a45a4ee77 fix: rename to countryCodes 2024-05-01 09:47:44 +08:00
Yang Luo
43393f034b feat: fix the Email provider fails to match bug in GetProviderByCategoryAndRule() 2024-05-01 09:44:19 +08:00
Yang Luo
bafa80513b fix: improve ProviderTable column UI 2024-05-01 00:46:48 +08:00
Yang Luo
8d08140421 fix: fix typo in initBuiltInPermission() 2024-05-01 00:41:16 +08:00
DacongDA
3d29e27d54 feat: support multiple SMS providers for different regions (#2914)
* feat: support using different sms provider for different region

* feat: add multiple support for select and remove log

* feat: revert change for countryCode in loginPage

* feat: revert change for countryCode in user_util.go

* feat: revert change for countryCode in auth.go

* Update application_item.go

* Update CountryCodeSelect.js

* Update ProviderTable.js

---------

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2024-05-01 00:40:47 +08:00
filwaline
199f1d4d10 feat: fix Auto-login causing AuthCodeWithPKCE Failures (#2911) 2024-04-30 12:14:50 +08:00
DacongDA
227e938db6 feat: fix error behavior of custom oauth/saml provider in login page in big icon mode (#2900) 2024-04-26 23:33:41 +08:00
Yang Luo
739cfd84ed feat: cannot empty SigninMethodTable now 2024-04-26 21:23:23 +08:00
DacongDA
8dbb041a34 feat: fix empty custom CSS for new rows in signin items table (#2897) 2024-04-24 15:19:30 +08:00
Yang Luo
af2d26daf2 Add object.IsAppUser() 2024-04-24 01:10:38 +08:00
DacongDA
90d502ab2b feat: add custom css style for signup page and enhance css edit (#2880)
* feat: add custom css style for signup page and enhance css edit in signintable

* feat: change cssStyle to customCss

* feat: auto hide <style> label, fix display problem on providers, remove auto add providers in signup page

* fix: fix indent in signin items customCss and fix providers display in signup items

* fix: fix login replace logical
2024-04-21 11:56:18 +08:00
MyColorfulDays
d51af3378e fix: fix init data not saved to database (#2885) (#2886) 2024-04-21 11:55:06 +08:00
Yang Luo
87e2b97813 feat: translate Ukrainian language i18n 2024-04-20 02:14:23 +08:00
Yang Luo
d9e44c1f2d fix: add "Is used" to verification list page 2024-04-20 00:18:52 +08:00
Yang Luo
dfa4503f24 feat: support "mfa_phone_enabled", "mfa_email_enabled" in update-user API 2024-04-20 00:16:45 +08:00
guangwu
f7fb32893b fix: close file in LocalFileSystemProvider's Put() (#2882) 2024-04-20 00:11:52 +08:00
Yang Luo
66d0758b13 feat: fix DisableVerificationCode bug about empty email and phone 2024-04-19 13:28:13 +08:00
Yang Luo
46ad0fe0be Improve Email Send() logic 2024-04-11 19:09:48 +08:00
Yang Luo
6b637e3b2e feat: fix SendgridEmailProvider error handling, fix send-email template 2024-04-11 00:18:39 +08:00
DacongDA
3354945119 feat: add SendGrid Email provider (#2865)
* feat: add support for email provider send grid

* feat: rename send grid to sendgrid

* feat: rename send grid to sendgrid

* feat: change logo url of send grid
2024-04-09 22:16:01 +08:00
DacongDA
19c4416f10 feat: degrade the ant-design/cssinjs version to fix the Chrome 87 broken UI issue (#2861) 2024-04-09 09:15:39 +08:00
Yang Luo
2077db9091 fix: fix bug in VerificationListPage 2024-04-07 15:39:25 +08:00
无别
800f0ed249 feat: add tzdata package in Dockerfile to fix timezone issue (#2857)
Add tzdata to resolve possible time zone errors
2024-04-07 14:27:45 +08:00
xyt
6161040c67 fix: Dismiss google one tap after logged in by setting disableCancelOnUnmount to false (#2854)
* fix: Google One Tap should be hidden after logged in

* Change the call location for google.accounts.id.cancel()

* fix: hide google one tap after login by set disableCancelOnUnmount to false
2024-04-05 23:39:33 +08:00
xyt
1d785e61c6 feat: Google One Tap should be hidden after logged in (#2853)
* fix: Google One Tap should be hidden after logged in

* Change the call location for google.accounts.id.cancel()
2024-04-05 20:10:13 +08:00
Yang Luo
0329d24867 feat: add isUsernameLowered to config 2024-04-02 21:54:16 +08:00
Yang Luo
fb6f3623ee feat: add requireProviderPermission() 2024-03-30 23:24:59 +08:00
DacongDA
eb448bd043 fix: fix permission problem in provider (#2848) 2024-03-30 23:18:03 +08:00
xyt
ea88839db9 feat: add back button in forget password page (#2847)
* feat: add back button in forget password page

* fix: can't step back when directly entering forgot password page

* feat: forget password page always return to login page

* feat: if has history then go back to history & change style

* Update ForgetPage.js

* fix: reset button position

* Update ForgetPage.js

* Update ForgetPage.js

---------

Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-30 23:17:47 +08:00
Yang Luo
cb95f6977a fix: fix PasswordModal error when changing username 2024-03-30 12:28:55 +08:00
Eric Luo
9067df92a7 feat: revert "feat: Support metamask mobile login" (#2845)
This reverts commit bfa2ab63ad.
2024-03-30 00:36:25 +08:00
HGZ-20
bfa2ab63ad feat: Support metamask mobile login (#2844) 2024-03-30 00:08:52 +08:00
DacongDA
505054b0eb feat: use minWidth for a better display effect in org select (#2843) 2024-03-29 15:47:27 +08:00
Yang Luo
f95ce13b82 fix: support "Email or Phone" in signup table 2024-03-29 09:07:37 +08:00
xyt
5315f16a48 feat: can specify UI theme via /?theme=default and /?theme=dark (#2842)
* feat: set themeType through URL parameter

* Update App.js

---------

Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-29 00:52:18 +08:00
Will.Feng
d054f3e001 feat: The /login/oauth/access_token api supports the token and id_token grant types. (#2836)
* In the response of the /api/get-captcha endpoint, add the parameters "owner" and "name" because these two parameters will be used when calling the /api/verify-captcha endpoint.

* The /login/oauth/access_token api supports the token and id_token grant types.
2024-03-28 00:41:54 +08:00
Yang Luo
b158b840bd Add "new-user" to webhook event list 2024-03-27 15:23:06 +08:00
Yang Luo
b16f1807b3 fix: fix bug in "new-user" record 2024-03-27 15:15:40 +08:00
Yang Luo
d0cce1bf7a Order by "id" in GetPaginationRecords() 2024-03-27 15:14:41 +08:00
Yang Luo
9892cd20ab Improve erorr message in CheckVerificationCode() 2024-03-27 15:14:20 +08:00
Yang Luo
d1f31dd327 feat: fix linter 2024-03-26 23:24:53 +08:00
Yang Luo
94743246a1 Improve "%{user.friendlyName}" handling 2024-03-25 21:26:36 +08:00
Yang Luo
39ad1bc593 Add signup's object in AfterRecordMessage() 2024-03-25 21:20:33 +08:00
Will.Feng
d97f833d2a feat: Add 'owner' and 'name' Parameters to /api/get-captcha Response for /api/verify-captcha Usage (#2834) 2024-03-25 16:34:42 +08:00
Yang Luo
948fa911e2 feat: add users to getGroups() and getGroup() APIs 2024-03-22 23:32:30 +08:00
Yang Luo
6073a0f63d Rename GroupListPage and GroupEditPage 2024-03-22 23:14:05 +08:00
Yang Luo
91268bca70 Improve enableAutoSignin option UI 2024-03-22 22:55:10 +08:00
DacongDA
23dbb0b926 feat: add response to Records page (#2830)
* feat: add response to Records page

* feat: improve AddRecord

* feat: remove log and return err

* feat: improve record in signup and record deny

* fix: filter will generate 403 record correctly
2024-03-22 14:53:38 +08:00
pfeak
97cc1f9e2b fix: delete duplicate err check in utils/validation.go (#2831) 2024-03-21 18:17:38 +08:00
Yang Luo
8c415be7c7 feat: upgrade goth to v1.79.0 2024-03-20 19:57:15 +08:00
Yang Luo
e87165cfc8 Upgrade go.mod versions 2024-03-20 19:51:56 +08:00
DacongDA
fc4fa2e8b6 feat: add verification list page and related API (#2822)
* feat: add verification list page and relevant api

* feat: improve code format

* fix: fix timestamp display error
2024-03-19 19:10:52 +08:00
Yaodong Yu
44ae76503e feat: add default user mapping in custom oauth2 provider (#2819) 2024-03-18 23:01:17 +08:00
Yang Luo
ae1634a4d5 feat: fix user cannot logout issue about bug in GetSessionToken() 2024-03-18 02:11:39 +08:00
HGZ-20
bdf9864f69 fix: add FaceIdSigninBegin() to verify user information before face login (#2815)
* feat: add FaceIdSigninBegin() to verify user information before face login

* Update face.go

---------

Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-18 00:04:12 +08:00
Yang Luo
72839d6bf5 feat: fix TokenFormat error in get-account API 2024-03-17 23:03:50 +08:00
Will.Feng
2c4b1093ed fix: Correct expiresIn calculation for WeChat Mini Program token. (#2814) 2024-03-17 22:20:21 +08:00
Yang Luo
d1c55d5aa7 fix: improve error message in token_cas.go 2024-03-17 22:01:49 +08:00
SamYSF
c8aa35c9c6 feat: add token to the page for Chrome extension (#2804)
* feat: add token to the page for Chrome extension

* Update token_oauth.go

---------

Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-17 22:01:28 +08:00
Yang Luo
6037f37b87 feat: add default token format for built-in app 2024-03-17 20:46:01 +08:00
Yang Luo
1b478903d8 feat: fix login page error cannot show bug 2024-03-17 11:39:12 +08:00
Yang Luo
4f5ac7a10b Fix Face IDs label 2024-03-17 09:56:24 +08:00
Yang Luo
e81ba62234 Improve Face ID signin method UI 2024-03-17 09:56:23 +08:00
Ron
a19060c7cb fix: missing parameter type_token_hint in IntrospectToken() (#2812)
* fix: missing parameter type_token_hint in IntrospectToken(); fix key token type
2024-03-17 01:39:04 +08:00
HGZ-20
96812f676b fix: "fs" module not found issue in face-api.js for browser usage (#2810) 2024-03-17 01:35:43 +08:00
HGZ-20
04f0458b5c feat: improve handleCameraError() and camera call logic (#2809)
add i18n for face recognition
2024-03-16 22:52:57 +08:00
Yang Luo
fd0bcd9a17 Improve getObject() for "/api/get-policies" 2024-03-16 21:42:00 +08:00
Yang Luo
01a5958307 Improve error text in RequireAdmin() 2024-03-16 21:14:19 +08:00
Yang Luo
be88b00278 feat: improve RequireAdmin() logic 2024-03-16 20:49:17 +08:00
Yang Luo
1bd0245e7a Improve CheckVerificationCode() error message, add receiver to index 2024-03-16 18:16:29 +08:00
Yang Luo
cc84bd37cf Add object field in RecordListPage 2024-03-16 16:57:04 +08:00
Yang Luo
8302fcf805 Improve handleCameraError() 2024-03-16 09:55:55 +08:00
HGZ-20
391a533ce1 feat: add "Face ID" login method (#2782)
Face Login via face-api.js
2024-03-16 09:04:00 +08:00
Will.Feng
57431a59ad fix: Ensure /api/get-app-login Returns Captcha Provider for Applications Configured with Captcha (#2800)
In LoginPage.js, the line 92:const captchaProviderItems = this.getCaptchaProviderItems(this.props.application); 

captchaProviderItems have no Captcha Provider.
2024-03-15 19:56:12 +08:00
Yang Luo
88a4736520 feat: fix GetDashboard() page 2024-03-15 19:52:19 +08:00
xiao-kong-long
2cb6ff69ae fix: show selected organizations' statistics in dashboard page (#2805)
* fix: show selected organizations' statistics in dashboard page

* Update get-dashboard.go

* Update saml_idp.go

---------

Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-15 19:36:39 +08:00
leon.zhao
e1e5943a3e fix: fix the issue of adding xmlns="" when generating XML (#2799)
* fix:solve the problem of adding xmlns="" when generating XML

* fix:remove fmt.Println

* Update saml_idp.go

---------

Co-authored-by: zhaoxianfei <zhaoxianfei@meiqia.cn>
Co-authored-by: Eric Luo <hsluoyz@qq.com>
2024-03-13 23:59:05 +08:00
DacongDA
3875896c1e feat: support custom header logo (#2801)
* feat: support custom header logo

* feat: add i18n

* feat: preview default logo when field is empty

* feat: improve logo setting and display logic

* feat: change logoLight to logo
2024-03-13 23:33:43 +08:00
DacongDA
7e2f265420 feat: improve organization select UI (#2798) 2024-03-12 19:39:53 +08:00
Yang Luo
53ef179e9b Set Webhook.Url length to 200 2024-03-11 18:18:01 +08:00
Yang Luo
376ef0ed14 feat: support custom Email content in /send-email API 2024-03-11 11:48:00 +08:00
Yang Luo
ca183be336 Improve ManagedAccountTable UI 2024-03-11 00:13:34 +08:00
Yang Luo
e5da57a005 feat: fix cert's ES options 2024-03-10 19:30:05 +08:00
Yang Luo
e4e225db32 Use "ES512" value 2024-03-10 19:25:41 +08:00
Yang Luo
a1add992ee Support legacy "RSA" value 2024-03-10 19:23:54 +08:00
Yang Luo
2aac265ed4 Improve populateContent() 2024-03-10 18:58:53 +08:00
xiao-kong-long
2dc755f529 fix: add more cert algorithms like ES256 and PS256 (#2793) 2024-03-10 18:39:41 +08:00
Yang Luo
0dd474d5fc feat: fix public profile page shows blank page bug 2024-03-10 14:12:24 +08:00
Yang Luo
6998451e97 fix: support roles and permissions in /userinfo API 2024-03-10 12:34:56 +08:00
Yang Luo
9175e5b664 Fix bug in GetMaskedEmail() 2024-03-10 11:49:55 +08:00
DacongDA
dbc6b0dc45 feat: fix issue that forget password page fails to redirect back to signin page (#2792) 2024-03-10 09:55:44 +08:00
Yang Luo
31b7000f6a fix: enable the only language for login page 2024-03-09 11:28:23 +08:00
DacongDA
d25eaa65cd feat: support custom page footer (#2790) 2024-03-08 23:11:03 +08:00
Yang Luo
f5bcd00652 Add language to records page 2024-03-08 23:03:30 +08:00
Yang Luo
0d5f49e40a fix: fix GetResources() bug for app users 2024-03-08 16:15:31 +08:00
Yang Luo
3527e070a0 Fix my account page UI 2024-03-08 15:18:18 +08:00
Yang Luo
0108b58db4 Return status 200 for unauthorized operation, revert commit: 2fd2d88d20 2024-03-08 15:11:25 +08:00
Yang Luo
976b5766a5 feat: refactor out token_oauth.go 2024-03-08 15:03:28 +08:00
Yang Luo
a92d20162a feat: show all resources for org admin 2024-03-08 15:03:03 +08:00
Yang Luo
204b1c2b8c Fix resource page link error 2024-03-08 14:44:39 +08:00
Yang Luo
49fb269170 Improve error handling for GetSamlResponse() 2024-03-08 02:17:50 +08:00
Yang Luo
c532a5d54d Remove suspense fallback loading. 2024-03-07 23:21:25 +08:00
DacongDA
89df80baca feat: remove loading fallback in Suspense and use spin to display (#2780) 2024-03-06 20:30:54 +08:00
DacongDA
d988ac814c fix: fix account items display error (#2781) 2024-03-06 20:30:34 +08:00
Yang Luo
e4b25055d5 Improve isAllowedInDemoMode() 2024-03-06 02:17:28 +08:00
DacongDA
4123d47174 feat: callback will jump to blank page when from param start with "http" (#2778) 2024-03-06 01:07:52 +08:00
Yang Luo
fbdd5a926d Fix normal user my-account page blank bug 2024-03-06 01:07:28 +08:00
xiao-kong-long
92b6fda0f6 feat: support more objects in init_data JSON (#2776) 2024-03-05 23:41:46 +08:00
DacongDA
6a7ac35e65 fix: fix wechat media account can not bind issue (#2774)
* fix: fix wechat media account can not bind

* fix: improve code format
2024-03-05 18:46:28 +08:00
DacongDA
fc137b9f76 feat: fix custom JS doesn't reload after refresh bug (#2773) 2024-03-05 15:03:25 +08:00
DacongDA
11dbd5ba9a fix: fix duplicated load bug of custom JS (#2771) 2024-03-05 00:09:37 +08:00
Yang Luo
19942a8bd4 Add webhook.SingleOrgOnly 2024-03-04 21:14:52 +08:00
Yang Luo
f9ee8a68cb Support Chrome extension redirecting 2024-03-04 18:31:56 +08:00
Ron
f241336ad7 feat: add OSON SMS provider (#2769)
* implemented SMS provider 'OSON SMS' for frontend

* feat: add 'OSON SMS' provider for frontend
2024-03-04 01:05:53 +08:00
Yang Luo
8b64d113fb Upgrade go-sms-sender dependency to 0.20.0 2024-03-04 01:05:28 +08:00
DacongDA
a8800c4d5c fix: add missing / for style tag in signin items (#2768) 2024-03-03 23:46:57 +08:00
Yang Luo
75fc9ab9f7 Improve GetMaskedApplication()'s logic 2024-03-03 22:01:49 +08:00
Yang Luo
d06da76c3d feat: fix bug in /get-organization-applications API 2024-03-03 21:08:36 +08:00
Yang Luo
bc399837cc Rename label to "Custom CSS" 2024-03-03 20:45:14 +08:00
Yang Luo
265abfe102 fix: handle error in storage.GetStorageProvider() 2024-03-03 18:18:54 +08:00
DacongDA
12acb24dbc feat: add transaction pages (#2761) 2024-03-02 10:41:16 +08:00
Yang Luo
ba1ddc7e50 fix: admin can modify user ID now 2024-02-28 18:07:53 +08:00
Yang Luo
59e07a35aa Add balance to user 2024-02-28 16:54:30 +08:00
DacongDA
cabe830f55 feat: use dynamic import to load web3Auth (#2757)
* feat: use dynamic import to load web3Auth and success reduce the size of signin page to 720KB when web3 idp disabled

* feat: avoid frequent import in OAuthWidget.js which may cause e2e test EPIPE error

* feat: remove import may cause e2e error

* feat: remove import may cause e2e error

* feat: remove bug may cause e2e error

* feat: try use chrome in ci/cd instead of electron to solve e2e error
2024-02-28 15:58:04 +08:00
DacongDA
78af5daec3 feat: use resourcesToBackend to load i18n files (#2755) 2024-02-28 01:43:55 +08:00
Lénaïc Grolleau
6c76913f71 fix: Set default value for email and SMS rule to all instead of none (#2754) 2024-02-28 01:28:59 +08:00
Yang Luo
5a0d1bcb6e Support login by user ID 2024-02-28 01:28:24 +08:00
Yang Luo
37232faa07 feat: fix bug for missing SMS and Email provider in application 2024-02-27 22:54:35 +08:00
Yang Luo
4d9c81ef96 Fix broken error messages 2024-02-27 22:48:33 +08:00
DacongDA
b0d87f60ae feat: use lazy load to load management pages (#2752) 2024-02-27 22:31:02 +08:00
DacongDA
a5499219d1 fix: refactor out ManagementPage.js from App.js (#2750)
* feat: basic separate

* feat: nearly fully separate

* feat: add License

* feat: full load application in /login url, lazy load in /login/oauth... etc

* fix: fix onChangeTheme error in organization edit page

* fix: revert lazy load
2024-02-27 18:49:23 +08:00
DacongDA
6a813a1f8c feat: fix headerHtml script not running bug (#2749)
* fix: fix custom head not exec <script> tag

* fix: fix create element bug
2024-02-26 20:21:07 +08:00
DacongDA
e4cf244cf8 fix: theme will fully restore after page reload (#2743)
* fix: theme will set to default after flush

* fix: use consume theme to ensure EntryPage will always use default themeAlgorithm

* fix: fix logo render, add try catch to handle
potential err cause by JSON.parse
2024-02-25 00:05:13 +08:00
DacongDA
f5a6415e57 feat: improve dark theme UI (#2742) 2024-02-24 20:11:42 +08:00
DacongDA
13e871043c fix: fix theme switch bug (#2741) 2024-02-24 16:56:12 +08:00
DacongDA
a8699d0b87 feat: use React routing to remove spin between signup and signin pages (#2740)
* fix: Regarding the color of loading

* fix: use goToLinkSoft and use same code format with result and forget psw

* fix: update signup url
2024-02-24 12:59:09 +08:00
hsluoyz
6621d693de feat: revert "feat: use i18next-resources-to-backend to lazy load i18n" (#2739)
This reverts commit dc3131c683.
2024-02-23 23:38:49 +08:00
DacongDA
dc3131c683 feat: use i18next-resources-to-backend to lazy load i18n (#2738)
* feat: use i18next-resources-to-backend to lazy load i18n file

* feat: change source in yarn.lock
2024-02-23 22:35:59 +08:00
zhuying1999
042a8d0ad6 feat: add rule for SMS and Email provider (#2733)
* add phonecoderule

* feat:add phone code rule

* feat: add email rule

* fix: merge
2024-02-23 00:09:37 +08:00
DacongDA
44abfb3430 feat: support custom header HTML in entry pages (#2731) 2024-02-22 17:56:47 +08:00
Yang Luo
53b8424a1f feat: fix JSON typo in init_data.json template 2024-02-21 17:33:08 +08:00
DacongDA
23c2ba3a2b feat: support ssh key/pem file in DB syncer (#2727)
* feat: support connect database with ssh tunnel in syncer

* feat: improve i18n translate

* feat: improve code format and i18n
2024-02-21 17:27:37 +08:00
许懿赫
3a9ffedce4 feat: support phone and Email in /api/login/oauth/access_token API (#2725)
Phone Number supports for /api/login/oauth/access_token as username

 Closes: #2724
2024-02-21 17:27:24 +08:00
Yang Luo
03f005389f feat: fix organizationChangeTrigger() and userChangeTrigger() bugs 2024-02-21 01:14:32 +08:00
Yang Luo
69a8346d05 Remove "/auto-signup/oauth/authorize" path introduced in PR: #896 2024-02-20 17:40:39 +08:00
Yang Luo
546512a0ea Fix getCasvisorApplication() 2024-02-20 13:45:03 +08:00
DacongDA
c4a307b9ec feat: add built-in "Records" pages back (#2720) 2024-02-20 13:28:29 +08:00
DacongDA
d731c3c934 feat: add regex support for account item (#2714)
* feat: add regex support for account item

* feat: use reflect to process user field

* fix: fix lint problem

* feat: improve code format and fix reflect error
2024-02-17 15:24:36 +08:00
Yang Luo
4a68dd65cd Fix typo in renderFormItem() 2024-02-16 10:13:50 +08:00
Yang Luo
d59148890e Improve error handling for CheckVerificationCode() 2024-02-16 08:53:56 +08:00
Yang Luo
7f52755e32 feat: improve error messages 2024-02-16 01:13:34 +08:00
Yang Luo
eaa6f50085 Add initial value for grantTypes 2024-02-15 23:18:23 +08:00
Yaodong Yu
f35a5f9a47 feat: fix issue that admin cannot enable MFA for user (#2702) 2024-02-14 23:29:04 +08:00
Yang Luo
7481b229a4 feat: show domain field for MinIO storage provider 2024-02-14 13:54:17 +08:00
Yang Luo
39e485ae82 Fix SigninTable issue 2024-02-14 12:20:03 +08:00
Yang Luo
764c64e67c Fix SigninTable CSS 2024-02-14 12:10:30 +08:00
Yang Luo
e755a7331d Fix renderLink() 2024-02-14 09:45:21 +08:00
hsluoyz
6d9d595f86 fix: Revert "fix: fix display bug in SigninTable" (#2700)
This reverts commit d52058d2ae.
2024-02-14 09:44:42 +08:00
DacongDA
d52058d2ae fix: fix display bug in SigninTable (#2698)
* fix: fix display bug in SigninTable

* fix: fix code bug

* feat: improve code format

* feat: improve code format
2024-02-14 09:26:51 +08:00
Yang Luo
bcfbfc6947 Support "signinUrl" in forget page 2024-02-14 02:36:52 +08:00
Yang Luo
75699c4a26 feat: improve code in getObject() 2024-02-13 23:50:21 +08:00
DacongDA
3e8bfb52a8 feat: add signin items table (#2695)
* feat: add signin items table

* fix:unable to login

* feat: improve code format

* fix: fix display err on signup link

* feat: improve display of sign up link
2024-02-13 23:12:40 +08:00
Yaodong Yu
bbbd857a45 fix: fix bug that failed to run initApi adapter in docker (#2696) 2024-02-13 23:12:25 +08:00
Andrey
498900df76 feat: allow dot in the username (like john.smith) (#2692) 2024-02-12 20:52:17 +08:00
Dmitri Aleksandrov
7e3c1a6581 fix: improve goth code (#2693)
Signed-off-by: Dmitrii Aleksandrov <goodmobiledevices@gmail.com>
2024-02-12 20:51:58 +08:00
github-actions[bot]
6e28043dba refactor: New Crowdin translations (#2648)
* refactor: New Crowdin translations by Github Action

* refactor: New Crowdin Backend translations by Github Action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2024-02-12 18:54:31 +08:00
Yang Luo
cb200687dc feat: fix GetUserByUserId() API crash issue 2024-02-12 18:51:55 +08:00
Lars Lehtonen
23bb0ee450 feat: fix error handling in AdfsIdProvider (#2687) 2024-02-10 15:38:38 +08:00
Yang Luo
117259dfc5 ci: fix repo name in CI 2024-02-10 15:38:17 +08:00
DacongDA
e71d0476f0 feat: support data initialization for groups, adapters, enforcers, plans and pricings (#2685) 2024-02-08 20:46:40 +08:00
Yang Luo
b5d26767b2 docs: improve README 2024-02-08 00:02:31 +08:00
DacongDA
5c4e22288e feat: improve error handling and code format (#2682)
* feat: improve error process and code format

* feat: improve error process and code format
2024-02-07 20:55:33 +08:00
Satinder Singh
3ac4be64b8 fix: error msg for invalid org & app names in signup (#2679) 2024-02-07 08:53:50 +08:00
DacongDA
97db54b6b9 feat: full support for wechat official account login (#2677)
* feat: full support for wechat official account login

* feat: improve provider edit page

* fix: improve i18n format
2024-02-07 00:00:10 +08:00
Yang Luo
3a19d4c7c8 fix: do not filter webhooks by org 2024-02-06 20:33:11 +08:00
Yaodong Yu
a60be2b2ab feat: refactor MFA code and fix no-session bug (#2676)
* refactor: refactor mfa

* refactor: refactor mfa

* refactor: refactor mfa

* lint

* chore: reduce wait time
2024-02-06 20:17:59 +08:00
Yang Luo
06ef97a080 feat: can delete the whole SigninMethodTable 2024-02-06 16:43:16 +08:00
dacongda
167c1b0f1b feat: fix bug in WeChat OA login (#2674)
* fix: fix the problem of Wechat Official Account login

* fix: fix code format problem

* fix: add error display and fix the code format problem

* fix: i18n problem and code format
2024-02-05 21:38:12 +08:00
Satinder Singh
7d0eae230e fix: fix /signup organization parameter issue (#2669) 2024-02-03 11:47:36 +08:00
Yang Luo
901867e8bb feat: fix /signup parameter issue 2024-02-03 10:00:47 +08:00
HGZ-20
b7be1943fa feat: Add Invitation Code to Generate Invitation Link (#2666)
Add auto-population of invitation fields in the registration page based on the invitation code in the link
2024-02-02 21:12:56 +08:00
Yaodong Yu
bbbda1982f feat: fix missing MFA session issue (#2667) 2024-02-02 10:23:17 +08:00
dacongda
e593f5be5b fix: improve code format (#2665)
* feat: replace io/ioutils pacakage with io/os package

* fix: add missing error handling
2024-02-01 23:06:12 +08:00
Dmitri Aleksandrov
0918757e85 feat: add template support for Custom HTTP SMS provider (#2662) 2024-02-01 17:50:22 +08:00
dacongda
ce0d45a70b feat: support SAML POST binding (#2661)
* fix: support saml http post binding

* fix: support saml http post binding

* fix: support saml post binding sp
2024-02-01 17:28:56 +08:00
Konstantin
c4096788b2 feat: ABAC support for /api/enforce endpoint (#2660) 2024-01-31 23:14:55 +08:00
dacongda
523186f895 feat: Support sha512 password encryption algorithm (#2657)
* add sha512 encryption support for password

* fead: add sha512 encryption support for password
2024-01-31 00:06:06 +08:00
Satinder Singh
ef373ca736 feat: add deletedTime to user (#2652) 2024-01-30 23:18:32 +08:00
Yang Luo
721a681ff1 fix: improve error handling in GetUserApplication() 2024-01-30 21:40:39 +08:00
Yang Luo
8b1c4b0c75 feat: make phone field longer to 100 2024-01-30 19:06:18 +08:00
Yang Luo
540f22f8bd feat: refactor GetTokenByTokenValue() 2024-01-29 10:03:33 +08:00
Yang Luo
79f81f1356 Improve error handling in IntrospectToken() 2024-01-29 09:58:40 +08:00
Yaodong Yu
4e145f71b5 feat: improve MFA UI and jump URL (#2647)
* fix: mfa UI

* fix: mfa UI
2024-01-28 16:46:35 +08:00
Yang Luo
104f975a2f fix: fix wrong org issue for user's "signupApplication" 2024-01-28 01:51:03 +08:00
Yang Luo
71bb400559 feat: support using org's defaultAvatar when adding user in web UI 2024-01-28 01:07:20 +08:00
Yang Luo
93c3c78d42 feat: support "id_card" in UpdateUser() 2024-01-26 08:23:55 +08:00
Zhang Zhe
dd51bbbabf feat: fix autoComplete for MFA passcode and SMS code (#2642)
* update: mfa autoComplete="off"

* Update SendCodeInput.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2024-01-23 19:52:16 +08:00
HGZ-20
5318519bf8 fix: fix bug in LDAP user login error count (#2636)
Fix the issue where the login error count is not reset to 0 after a successful LDAP user login.
2024-01-22 13:42:11 +08:00
HGZ-20
d7c40459c0 feat: implement the enforcement for new invitation page (#2628)
Added new invitation code implementation
2024-01-22 02:25:13 +08:00
LiusCraft
de2932b5fb feat: use standalone Twitter OAuth provider instead of goth (#2632) 2024-01-20 21:49:02 +08:00
Yang Luo
f4c873ffe6 Fix user profile page UI 2024-01-20 19:28:43 +08:00
Yang Luo
97c7f2631a feat: fix organization.IsProfilePublic issue 2024-01-20 16:00:04 +08:00
Yang Luo
93f0425759 Remove old application's InvitationCodes 2024-01-20 10:58:08 +08:00
Yang Luo
6a00657e42 feat: fix forbidden and soft-delete check in forget password page 2024-01-19 22:13:02 +08:00
Yang Luo
88130bf020 feat: add forbidden check in SetPassword() 2024-01-19 16:30:22 +08:00
Yang Luo
5e99007fc9 Update goth to v1.78.0 2024-01-19 16:09:32 +08:00
Yang Luo
66aca3124c fix: improve error handling in LarkIdProvider 2024-01-19 15:37:15 +08:00
github-actions[bot]
61deb75c84 refactor: New Crowdin translations (#2512)
* refactor: New Crowdin translations by Github Action

* refactor: New Crowdin Backend translations by Github Action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2024-01-18 22:18:51 +08:00
Yang Luo
b8db07db4d feat: enable GetMaskedSyncers() 2024-01-18 20:59:27 +08:00
Yang Luo
a681c267b3 Refactor code format 2024-01-18 20:53:04 +08:00
Yang Luo
5fb6ea0ab4 Fix "password" tab in SigninMethods 2024-01-18 20:17:05 +08:00
Yang Luo
0f6b7984d4 feat: improve isAllowedInDemoMode() 2024-01-17 13:07:44 +08:00
Yang Luo
ba9d6e5d78 Fix Swagger API version 2024-01-16 00:09:28 +08:00
Yang Luo
a4524e9996 fix: fix Swagger @Tag 2024-01-15 23:35:40 +08:00
Yang Luo
b469928780 Fix Swagger @router 2024-01-15 23:27:42 +08:00
Yang Luo
dc6fe13f75 feat: use signupItem.Regex to check signup page 2024-01-15 18:12:38 +08:00
Yang Luo
8227762988 Support more special chars in password validating 2024-01-15 18:12:38 +08:00
hsluoyz
d92b072ed0 feat: revert PR: "feat: more RFC like LDAP server behaviour" (#2611) 2024-01-15 13:58:33 +08:00
hsluoyz
1161310f81 feat: improve README.md 2024-01-15 10:14:01 +08:00
xiao-kong-long
48ba5f91ed feat: add Synology NAS storage provider (#2605) 2024-01-14 22:38:31 +08:00
Satinder Singh
53df2c2704 fix: add semantic versioning for helm charts (#2603) 2024-01-14 09:44:16 +08:00
Yang Luo
78066da208 Improve setCorsHeaders() for "include" mode 2024-01-13 23:46:05 +08:00
Yang Luo
60096468fe fix: fix CI email 2024-01-13 18:12:52 +08:00
Yang Luo
39d6bc10f7 Fix GetCaptchaStatus() crash if not logged in 2024-01-13 18:04:38 +08:00
Yang Luo
177f2f2f11 Add userId param to GetAllObjects() API 2024-01-13 18:03:40 +08:00
Yang Luo
79b393afee feat: add regex to SignupTable 2024-01-13 16:08:49 +08:00
Yang Luo
5bb12a30d4 Don't show two errors in verificationCode login page 2024-01-13 16:01:22 +08:00
Yang Luo
fdb68bf9c8 Rename to SigninMethodTable 2024-01-13 15:53:01 +08:00
Yang Luo
37748850c8 Fix nameFormat in SamlItem 2024-01-13 15:32:49 +08:00
Yang Luo
8968396ae5 Fix bug in getDefaultLoginMethod() 2024-01-13 12:13:09 +08:00
Yang Luo
f5395f15f9 feat: fix isSigninMethodEnabled() bug in frontend 2024-01-13 11:35:06 +08:00
Yang Luo
73e44df867 Improve GetAllRoles() error handling 2024-01-13 10:06:08 +08:00
Yang Luo
0b575ccf84 Refactor getAllValues() 2024-01-13 09:58:55 +08:00
Yang Luo
9b7f465a47 Fix failedSigninFrozenTime typo 2024-01-13 02:12:29 +08:00
Yang Luo
b1fe28fb83 Refactor application.FailedSigninLimit code 2024-01-13 02:09:18 +08:00
Satinder Singh
530d054adb feat: ci should commit index.yaml and push to docker hub (#2600) 2024-01-11 16:10:08 +08:00
SamYSF
a2b9f9baaf feat: support "JWT-Custom" to customize user properties inside access token (#2594)
* feat: add custom attribute to access token

* Update token_jwt.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2024-01-10 00:59:02 +08:00
Yang Luo
a2d20fcb63 Update i18n 2024-01-09 22:16:17 +08:00
Yang Luo
b118a3bb76 Add TokenFields to application 2024-01-09 22:09:21 +08:00
Yang Luo
280867d0cb Add checkSigninErrorTimes() for LDAP signin 2024-01-09 21:53:44 +08:00
Yang Luo
30fa2f7d81 Disable LDAP login method by default 2024-01-09 21:36:09 +08:00
Michael
518288691d fix(ci): fix the helm publish step (#2593)
fixes https://github.com/casdoor/casdoor-helm/issues/3
2024-01-09 17:48:01 +08:00
HGZ-20
ffa54247cd feat: add LDAP signin method (#2591)
Add support for LDAP login methods
Add option to control LDAP user in password login method.
2024-01-08 21:07:34 +08:00
Anh Tu Nguyen
0199ad9aaa fix: missing table prefix in get user group (#2590)
- Sort field and order field are missing table name prefix

Co-authored-by: xgenvn <brian7.ng@gmail.com>
2024-01-08 21:07:13 +08:00
Michael
b9d171718f chore(helm): move to dedicated helm-repo (#2587)
* chore(helm): move to dedicated helm-repo: https://github.com/casdoor/casdoor-helm

* feat(actions): explicit checkout helm repo

* chore: feedback from pr comment
2024-01-08 02:02:05 +08:00
Yang Luo
e841d0ba8e feat: fix /api/send-email API for app user 2024-01-07 21:11:22 +08:00
Yang Luo
e5a9594f90 Hide Google OneTap in iframe 2024-01-07 10:33:25 +08:00
Satinder Singh
c542929835 fix: add vscode local debugging support (#2585) 2024-01-07 09:26:33 +08:00
hsluoyz
86dea71efd ci: update helm index.yaml 2024-01-06 19:31:07 +00:00
Michael
9e536850fd feat(helm): support for extra volume mounts (#2584)
* feat(helm): support for extraVolumes and extraVolumeMounts

* ci(helm): run helm unittests
2024-01-07 03:30:44 +08:00
Michael
fddd4a12b8 chore: update helm version to v1.492.0 (#2582) 2024-01-07 00:14:53 +08:00
Yang Luo
2d6fae32be feat: support custom config path via "config" 2024-01-06 14:09:48 +08:00
Yang Luo
741cff99df Remove isCreateDatabaseDefined 2024-01-06 14:08:34 +08:00
Satinder Singh
cad9c28e92 feat: helm hpa yaml must reference correct apiVersion (#2581) 2024-01-06 08:55:59 +08:00
李洛克
524cf4dda5 feat: fix update application failed for permissions with the same name (#2579)
* fixed: update application failed where have two same permission in different organization

* Update application.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2024-01-05 20:45:55 +08:00
Lê Tuấn Vũ
077a1cb8b7 fix: support owner parameter in enforce API (#2578) 2024-01-05 15:12:59 +08:00
Yang Luo
00efdf1d03 Fix EmailVerified in UserInfo() 2024-01-05 09:37:42 +08:00
Known Rabbit
aa543f1abb feat: more RFC like LDAP server behaviour (#2574)
* feat: more RFC like LDAP server behaviour

* Extend FieldRelationMap to support case insensitive mapping, add more fields definition

* feat: Add group syncing for LDAP server
2024-01-05 09:24:12 +08:00
Lars Lehtonen
1d1d3049bd feat: fix dropped getAffiliationMap error in object (#2576) 2024-01-05 09:03:39 +08:00
Yang Luo
4f497d44a5 Enable at least password login in extendApplicationWithSigninMethods() 2024-01-03 22:19:43 +08:00
Yaodong Yu
369de36987 feat: add users with correct application (#2570) 2024-01-02 23:49:04 +08:00
HGZ-20
e3f28e8b4c feat: Support more flexible login method control (#2566) 2024-01-02 21:11:52 +08:00
Yang Luo
3373174c65 fix: add missing tableNamePrefix in some places 2023-12-31 22:40:41 +08:00
Yang Luo
2fb79e4092 Add invitation pages 2023-12-31 21:38:36 +08:00
Yang Luo
5846e337c7 feat: fix gofmt issue 2023-12-30 19:47:04 +08:00
Yang Luo
44f4de1440 feat: support empty fileUrl in GetUploadFileUrl() 2023-12-30 19:06:35 +08:00
Yang Luo
27adeb4620 Refactor initAPI() 2023-12-30 14:28:45 +08:00
Yang Luo
5c107db43b fix: fix i18n typo 2023-12-30 00:49:39 +08:00
Yang Luo
27187b3a54 feat: add "Reset to Default HTML" button 2023-12-30 00:47:10 +08:00
Yang Luo
14fcedcc5d feat: support HTML in Email content 2023-12-29 23:31:50 +08:00
xiao-kong-long
e7c015f288 feat: fix comment and configs for successfully generating OpenAPI typescript-axios sdk (#2560)
* fix: fix swagger.json, successfully generate java sdk

* fix:fix comment and change some content for successfully generating typescript-axios sdk
2023-12-29 15:12:40 +08:00
Yang Luo
c4819602ec fix: add mfa API to isAllowedInDemoMode() 2023-12-26 20:06:27 +08:00
Eng Zer Jun
dea03cdd15 feat: replace deprecated github.com/RobotsAndPencils/go-saml (#2558)
The `github.com/RobotsAndPencils/go-saml` has been officially deprecated
and archived on 7 June 2023.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2023-12-25 21:15:53 +08:00
xiao-kong-long
21f394847e fix: fix Swagger docs by improving comments 2023-12-23 11:57:18 +08:00
Yang Luo
9bef9691fb feat: fix volcengine SMS provider error handling 2023-12-22 20:49:45 +08:00
Yang Luo
141f22a707 feat: upgrade to Node.js 18 and Go 1.20 in Dockerfile 2023-12-22 14:46:41 +08:00
Yang Luo
02329d342a feat: fix bug in "*" users and roles in permission edit page. 2023-12-22 14:16:00 +08:00
Yang Luo
b9d3e2184c fix: update CI node version from 16 to 18 2023-12-22 09:28:45 +08:00
Yang Luo
28caf8550e Support token parsed result 2023-12-22 02:04:25 +08:00
Yang Luo
79159dc809 Improve TokenEditPage 2023-12-22 00:44:34 +08:00
Yang Luo
63081641d6 Improve i18n text 2023-12-22 00:25:46 +08:00
Yang Luo
698f24f762 feat: fix template code bug in SMS provider of Amazon SNS 2023-12-21 23:32:55 +08:00
HGZ-20
5499e62d7f feat: add the FailedSigninLimit and FailedSigninfrozenTime configuration options to the application (#2552)
Add configuration items to the application to limit the number of logins and the login wait time after the maximum number of errors is reached
feat: #2272

fix: fixed the issue where the token parameter could be set to a negative value
2023-12-20 22:29:53 +08:00
Yang Luo
f8905ae64c Fix S3-compliant storage providers support 2023-12-20 14:38:32 +08:00
Yang Luo
a42594859f feat: improve enforce() and batchEnforce() API response 2023-12-20 11:41:54 +08:00
Yang Luo
46e0bc1a39 Improve i18n texts 2023-12-20 10:09:00 +08:00
Gucheng Wang
ffe2330238 Fix tag field in user list page 2023-12-20 01:57:56 +08:00
Gucheng
ec53616dc8 Update README.md 2023-12-20 01:52:29 +08:00
Gucheng Wang
067276d739 Add new B2C provider 2023-12-17 16:29:29 +08:00
Yang Luo
468ceb6b71 Fix get-all-objects API 403 issue 2023-12-15 21:32:45 +08:00
Satinder Singh
b31a317585 feat: add helm release github action (#2546) 2023-12-15 19:30:10 +08:00
Yang Luo
396b6fb65f feat: refactor custom HTTP related filenames 2023-12-15 00:06:05 +08:00
Yang Luo
be637fca81 fix: fix wrong POST param logic in custom HTTP providers 2023-12-15 00:00:47 +08:00
link89
374928e719 feat: add custom HTTP Email provider (#2542)
* feat: implement Custom HTTP Email provider

* Update Setting.js

* Update ProviderEditPage.js

* Update http.go

* Update provider.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-12-14 22:35:25 +08:00
Yang Luo
5c103e8cd3 Improve error handling in GenerateIdForNewUser() 2023-12-14 10:12:00 +08:00
Lars Lehtonen
85b86e8831 fix: dropped object group errors (#2545) 2023-12-14 09:00:25 +08:00
Yang Luo
08864686f3 feat: fix Google cloud storage provider bug 2023-12-14 00:25:50 +08:00
HGZ-20
dc06eb9948 feat: fix secret information issue in the CAPTCHA provider code (#2531) 2023-12-11 18:01:56 +08:00
Yang Luo
b068202e74 Improve Radius username handling 2023-12-11 18:01:28 +08:00
Satinder Singh
cb16567c7b feat: helm support extra containers (#2530) 2023-12-10 14:41:56 +08:00
Yang Luo
4eb725d47a Improve image upload UI 2023-12-08 19:42:20 +08:00
Yang Luo
ce72a172b0 feat: add back Custom HTTP SMS provider 2023-12-07 16:59:41 +08:00
Yang Luo
5521962e0c feat: update go-sms-sender to v0.17.0 to improve error handling 2023-12-07 14:25:21 +08:00
Yang Luo
37b8b09cc0 feat: update go-sms-sender to v0.16.0 to fix first number missing bug in AmazonSNSClient.SendMessage 2023-12-06 20:05:48 +08:00
Yang Luo
482eb61168 feat: improve StaticFilter() 2023-12-05 18:33:06 +08:00
Lars Lehtonen
8819a8697b feat: fix dropped error in stripe.go (#2525) 2023-12-05 16:02:33 +08:00
Yang Luo
85cb68eb66 feat: unbind LDAP clients if not used any more 2023-12-02 17:51:25 +08:00
Yang Luo
b25b5f0249 Support original accessToken in token APIs 2023-12-02 16:56:18 +08:00
Yang Luo
947dcf6e75 Fix "All" roles bug in permission edit page 2023-12-02 15:26:52 +08:00
Yang Luo
113c27db73 Improve logout's id_token_hint logic 2023-12-02 02:13:34 +08:00
Nex Zhu
badfe34755 feat: add "nonce" into the OAuth and OIDC tokens, for some apps require "nonce" to integrate (#2522) 2023-12-01 18:29:39 +08:00
Yang Luo
a5f9f61381 feat: add token hash to improve performance 2023-11-30 18:05:30 +08:00
Daniil Mikhaylov
2ce8c93ead feat: Improve LDAP filter support (#2519) 2023-11-26 23:11:49 +08:00
Yang Luo
da41ac7275 Improve error handling in getFaviconFileBuffer() 2023-11-25 18:31:33 +08:00
hsluoyz
fd0c70a827 feat: Revert "feat: fix login page path after logout" (#2516)
This reverts commit 23d4488b64.
2023-11-24 15:52:59 +08:00
Yang Luo
c4a6f07672 Allow app user in demo mode 2023-11-24 01:04:23 +08:00
Nex Zhu
a67f541171 feat: in LDAP, search '*' should return all properties (#2511) 2023-11-22 23:52:40 +08:00
Yang Luo
192968bac8 Improve permission.State 2023-11-22 00:03:33 +08:00
aiden
23d4488b64 feat: fix login page path after logout (#2493)
Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-11-21 23:37:35 +08:00
songjf
23f4684e1d feat: make MFA works for CAS login (#2506)
* feat: make MFA works for CAS login

* fix: Reduced code redundancy

* fix: Modified the format of the code.

* fix: fix an error with the 'res' variable

* Update LoginPage.js

* Update LoginPage.js

* Update LoginPage.js

* Update MfaAuthVerifyForm.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-11-21 21:35:19 +08:00
xzgan
1a91e7b0f9 feat: support LDAP in Linux (#2508) 2023-11-21 14:01:27 +08:00
Yang Luo
811999b6cc feat: fix error handling in CheckPassword() related functions 2023-11-20 21:49:19 +08:00
Jiankun Yang
7786018051 feat: use short state for OAuth provider (#2504)
* fix: use fixed length of state

* fix: use short state
2023-11-19 07:30:29 +08:00
xzgan
6c72f86d03 fix: support LDAP in linux (#2500)
Co-authored-by: Xiang Zhen Gan <m1353825@163.com>
2023-11-16 23:58:09 +08:00
Yang Luo
5b151f4ec4 feat: improve cert edit page UI 2023-11-13 15:57:46 +08:00
Yang Luo
e9b7d1266f Fix API typo: /get-global-certs 2023-11-13 14:22:40 +08:00
Yang Luo
2d4998228c Add organization.MasterVerificationCode 2023-11-13 13:53:41 +08:00
Yang Luo
d3ed6c348b Improve GetOAuthToken() API's parameter handling 2023-11-13 02:30:32 +08:00
songjf
a22e05dcc1 feat: fix the UI and navigation errors on the prompt page (#2486) 2023-11-12 15:54:38 +08:00
haiwu
0ac2b69f5a feat: support WeChat Pay via JSAPI (#2488)
* feat: support wechat jsapi payment

* feat: add log

* feat: update sign

* feat: process wechat pay result

* feat: process wechat pay result

* feat: save wechat openid for different app

* feat: save wechat openid for different app

* feat: add SetUserOAuthProperties for signup

* feat: fix openid for wechat

* feat: get user extra property in buyproduct

* feat: remove log

* feat: remove log

* feat: gofumpt code

* feat: change lr->crlf

* feat: change crlf->lf

* feat: improve code
2023-11-11 17:16:57 +08:00
Yang Luo
d090e9c860 Improve downloadImage() 2023-11-10 08:35:21 +08:00
Yang Luo
8ebb158765 feat: improve README 2023-11-09 21:52:52 +08:00
Yang Luo
ea2f053630 feat: add fields like Email to user profile in JWT-Empty mode 2023-11-09 20:20:42 +08:00
Yang Luo
988b14c6b5 Fix user's UpdatedTime in other APIs 2023-11-08 20:22:28 +08:00
Yang Luo
a9e72ac3cb feat: fix bug in GetAllowedApplications() 2023-11-08 10:31:24 +08:00
Yang Luo
498cd02d49 feat: add GetAllowedApplications() in user's app homepage 2023-11-08 09:48:31 +08:00
Yang Luo
a389842f59 Improve Product fields 2023-11-06 19:44:21 +08:00
aiden
6c69daa666 feat: fix search for ldap users' name within an organization (#2476)
* fix: #2304

* fix: when logging in with OAuth2 and authenticating via WebAuthn, retrieve the application from the clientId.

* fix: search for ldap users' name within an organization

---------

Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-11-06 11:48:23 +08:00
Yang Luo
53c89bbe89 feat: upgrade xorm-adapter to add id to CasbinRule 2023-11-03 02:48:01 +08:00
Yang Luo
9442aa9f7a Remove useless PermissionRule 2023-11-03 00:39:16 +08:00
Yang Luo
8a195715d0 Remove migrator code 2023-11-03 00:25:09 +08:00
Lars Lehtonen
b985bab3f3 fix: fix dropped errors in GetUser() (#2470)
* controllers: fix dropped errors

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-11-01 23:07:24 +08:00
aiden
477a090aa0 feat: when logging in with OAuth2 and authenticating via WebAuthn, retrieve the application from the clientId (#2469)
* fix: #2304

* fix: when logging in with OAuth2 and authenticating via WebAuthn, retrieve the application from the clientId.

---------

Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-11-01 18:40:05 +08:00
songjf
e082cf10e0 fix: fix Okta provider no host issue (#2467) 2023-11-01 18:14:39 +08:00
吃着土豆坐地铁
3215b88eae fix: ADFS GetToken() and GetUserInfo() bug (#2468)
* fix adfs bug

* Update adfs.go

---------

Co-authored-by: Gucheng <85475922+nomeguy@users.noreply.github.com>
2023-11-01 17:58:17 +08:00
Yang Luo
9703f3f712 Support Apple OAuth login now 2023-10-31 23:10:36 +08:00
Yang Luo
140737b2f6 Fix some bugs in Apple OAuth login path 2023-10-31 23:10:36 +08:00
haiwu
b285144a64 ci: support MySQL data sync (#2443)
* feat: support tool for mysql master-slave sync

* feat: support mysql master-master sync

* feat: improve log

* feat: improve code

* fix: fix bug when len(res) ==0

* fix: fix bug when len(res) ==0

* feat: support master-slave sync

* feat: add deleteSlaveUser for TestStopMasterSlaveSync

* feat: add deleteSlaveUser for TestStopMasterSlaveSync
2023-10-31 21:00:09 +08:00
github-actions[bot]
49c6ce2221 refactor: New Crowdin translations (#1667)
* refactor: New Crowdin translations by Github Action

* refactor: New Crowdin Backend translations by Github Action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2023-10-31 18:11:05 +08:00
Yang Luo
2398e69012 Improve fastAutoSignin() 2023-10-31 16:54:30 +08:00
Yang Luo
ade9de8256 Add DumpToFile() to export init_data.json 2023-10-31 14:39:50 +08:00
Yang Luo
1bf5497d08 Improve error handling for GetUser() 2023-10-31 14:01:37 +08:00
Yang Luo
cf10738f45 Fix typo in AddUserKeys() 2023-10-31 13:31:12 +08:00
Yang Luo
ac00713c20 Improve error handling for object/user.go 2023-10-31 13:20:44 +08:00
Yang Luo
febb27f765 Remove useless fields in GenerateCasToken() 2023-10-30 18:45:34 +08:00
aiden
49a981f787 fix: fix that GROUPS is a reserved keyword introduced in MySQL 8.0 (#2458)
Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-30 10:59:48 +08:00
aiden
34b1945180 feat: fix bugs in custom app sso login with WebAuthn authentication (#2457)
Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-30 10:54:34 +08:00
Yang Luo
b320cca789 Can disable ldapServerPort by setting to empty string 2023-10-29 23:55:08 +08:00
Yang Luo
b38654a45a Add renderAiAssistant() 2023-10-28 23:58:51 +08:00
Yang Luo
f77fafae24 Fix hidden top navbar item 2023-10-28 17:07:29 +08:00
songjf
8b6b5ffe81 feat: fix go-reddit module checksum mismatch (#2451) 2023-10-28 15:32:36 +08:00
Chao
a147fa3e0b feat: fix bug that tableNamePrefix caused getRolesByUserInternal() to fail (#2450)
If set tableNamePrefix in app.conf, while cause sql error
2023-10-28 09:45:54 +08:00
Yang Luo
9d03665523 Fix FromProviderToIdpInfo() bug 2023-10-27 18:10:22 +08:00
Yang Luo
0106c7f7fa Fix GetIdProvider() bug 2023-10-27 17:03:37 +08:00
Yang Luo
6713dad0af Fix this.props.account null issue 2023-10-27 02:13:23 +08:00
Yang Luo
6ef2b51782 Support fastAutoSignin by backend redirection 2023-10-27 00:44:50 +08:00
Yang Luo
1732cd8538 Fix the bug that sometimes cannot auto login with enableAutoSignin = true 2023-10-27 00:06:17 +08:00
Yang Luo
a10548fe73 Fix org admin's enforcer policy APIs 2023-10-26 23:31:36 +08:00
Yang Luo
f6a7888f83 Deleted user cannot perform actions 2023-10-26 10:41:38 +08:00
Yang Luo
93efaa5459 Fix FileExist() error handling 2023-10-26 10:40:28 +08:00
jump2cn
0bfe683108 feat: change canonicalizer algorithm to xml-exc-c14n# (#2440) 2023-10-24 14:13:09 +08:00
Yang Luo
8a4758c22d Update sync code 2023-10-22 11:56:56 +08:00
Yang Luo
ee3b46e91c Allow permission.Model to be empty 2023-10-22 02:35:51 +08:00
Yang Luo
37744d6cd7 Improve permission error handling 2023-10-22 02:30:29 +08:00
Yang Luo
98defe617b Add providerItem.SignupGroup 2023-10-20 23:10:43 +08:00
Yang Luo
96cbf51ca0 Remove useless alertType field 2023-10-20 23:01:11 +08:00
Yang Luo
22b57fdd23 Add application.EnableSamlC14n10 2023-10-20 22:37:23 +08:00
haiwu
b68e291f37 feat: support SAML Custom provider (#2430)
* 111

* feat: support custom saml provider

* feat: gofumpt code

* feat: gofumpt code

* feat: remove comment

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-10-20 21:11:36 +08:00
aiden
9960b4933b feat: respect isReadOnly in the syncer (#2427)
Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-19 18:57:12 +08:00
aiden
432a5496f2 fix: skip checking password when the code is provided (#2425)
Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-19 18:25:25 +08:00
aiden
45db4deb6b feat: support checking permissions for group roles (#2422)
* fix(permission): fix CheckLoginPermission() logic

* style: fix code format

* feat: support settting roles for groups

* fix: fix field name

* style: format codes

---------

Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-19 15:33:45 +08:00
Yang Luo
3f53591751 Improve verification no provider error message 2023-10-18 15:32:12 +08:00
Yang Luo
d7569684f6 Local admin can edit its org user's other fields now 2023-10-18 12:16:05 +08:00
Yang Luo
a616127909 Add organization.DefaultPassword 2023-10-18 11:58:25 +08:00
Yang Luo
f2e2b960ff Improve downloadImage() error handling 2023-10-18 02:25:22 +08:00
Yang Luo
fbc603876f feat: add originFrontend to app.conf 2023-10-17 21:47:18 +08:00
Yang Luo
9ea77c63d1 Local admin can edit its org users now 2023-10-17 18:23:39 +08:00
songjf
53243a30f3 feat: support tencent cloud SAML SSO authentication with casdoor (#2409)
* feat: Support Tencent Cloud SAML SSO authentication with Casdoor

* feat: support SamlAttributeTable in the frontend

* fix:fixed the error where frontend fields did not match the database fields

* fix:fix lint error

* fix:fixed non-standard naming

* fix:remove if conditional statement

* feat:Add Saml Attribute format select

* fix:fix typo

* fix:fix typo

* fix:fix typo

* Update SamlAttributeTable.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-10-17 15:40:41 +08:00
aiden
cbdeb91ee8 feat: support groups in app login permissions (#2413)
* fix(permission): fix CheckLoginPermission() logic

* style: fix code format

---------

Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-10-17 14:35:13 +08:00
Yang Luo
2dd1dc582f Add text to app's signup table 2023-10-15 18:17:50 +08:00
Yang Luo
f3d4b45a0f Add label and placeholder to app's signup table 2023-10-15 17:24:38 +08:00
Yang Luo
2ee4aebd96 Fix error handling in GetSamlMeta() 2023-10-15 17:02:40 +08:00
Yang Luo
150e3e30d5 Support app user in API authentication 2023-10-15 15:20:57 +08:00
Yang Luo
1055d7781b Improve error handling in AutoSigninFilter 2023-10-15 12:43:36 +08:00
Yang Luo
1c296e9b6f feat: activate enableGzip by default in app.conf 2023-10-15 01:27:42 +08:00
haiwu
3d80ec721f fix: use user.UpdatedTime as scim.Meta.Version instead of user.Id (#2406)
* 111

* fix: use user.UpdatedTime as scim.Meta.Version instead of user.Id

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-10-14 11:03:58 +08:00
Yang Luo
43d849086f Fix 127.0.0.1 bug in isHostIntranet() 2023-10-13 23:29:37 +08:00
Yang Luo
69b144d80f feat: change back to running RecordMessage() filter before API handling, because the logged-out user info is missing after session is cleared. Revert: https://github.com/casdoor/casdoor/pull/2369 2023-10-13 16:53:30 +08:00
Yang Luo
52a66ef044 Fix webhook not triggered issue in SendWebhooks() 2023-10-13 16:47:09 +08:00
Yang Luo
ec0a8e16f7 feat: fix CheckLoginPermission() logic 2023-10-13 15:41:23 +08:00
Yang Luo
80a8000057 Add GetModelEx() 2023-10-13 13:45:13 +08:00
Yang Luo
77091a3ae5 Fix null model issue in UpdatePermission() 2023-10-13 12:55:11 +08:00
Pedro Padron
983da685a2 feat: support calling get-user API by only email, phone or userId without owner (#2398) 2023-10-13 02:48:55 +08:00
UsherFall
3d567c3d45 feat: update go-sms-sender to fix Twilio template error (#2395) 2023-10-12 01:53:31 +08:00
haiwu
440d87d70c feat: support SCIM protocol (#2393)
* 111

* feat: support scim/Users GET and POST request

* feat: support scim/Users DELETE/PATCH/PUT request

* feat: better support scim/Users PATCH request

* feat: fix scim/Users logic

* feat: gofumpt

* feat: fix bug in scim/Users

* feat: fix typo

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-10-12 00:13:16 +08:00
Yaodong Yu
e4208d7fd9 feat: restrict the model of application type resource permission (#2394) 2023-10-12 00:05:53 +08:00
Yang Luo
4de716fef3 Improve UploadResource() 2023-10-11 01:27:29 +08:00
Yang Luo
070aa8a65f Show 404 error for index.html not found 2023-10-10 22:57:39 +08:00
wxy
684cbdb951 fix: replace the wrong param name willExist (#2389) 2023-10-10 21:47:38 +08:00
QingKai Hao
9aec69ef47 feat: stop building docker image of linux/arm64 (#2390) 2023-10-10 21:19:54 +08:00
Yang Luo
98411ef67b feat: remove db migrate CI 2023-10-10 19:22:41 +08:00
Yang Luo
71279f548d Show cert.Certificate empty error 2023-10-10 19:19:20 +08:00
Yang Luo
0096e47351 feat: fix 403 error in CorsFilter 2023-10-10 18:39:25 +08:00
Yang Luo
814d3f749b Fix Syncer.getKey() 2023-10-09 02:47:42 +08:00
Yang Luo
ec0f457c7f Fix syncer.updateUser() bug 2023-10-09 01:14:35 +08:00
Yang Luo
0033ae1ff1 Improve syncer code 2023-10-08 20:50:28 +08:00
Yang Luo
d06d7c5c09 Fix batch methods like AddUsersInBatch() 2023-10-08 19:33:28 +08:00
Yang Luo
23c4fd8183 Fix go-reddit v2.0.1 doesn't exist issue 2023-10-08 19:29:26 +08:00
Yang Luo
e3558894c3 Add isHostIntranet to CORS filter 2023-10-08 19:29:19 +08:00
Yang Luo
2fd2d88d20 Return 403 in filter's responseError() 2023-10-05 00:12:02 +08:00
Yang Luo
d0c424db0a Don't panic in AddRecord() 2023-10-05 00:11:13 +08:00
Yang Luo
6a9d1e0fe5 Add frontendBaseDir 2023-10-04 12:19:56 +08:00
Yang Luo
938e8e2699 Improve code 2023-09-30 10:49:10 +08:00
Yang Luo
620383cf33 Allow CORS for https://localhost 2023-09-30 09:11:47 +08:00
Yang Luo
de6cd380eb Set OPTIONS status in setCorsHeaders() 2023-09-30 01:13:29 +08:00
Ilya Sulimanov
7e0bce2d0f feat: run RecordMessage() filter after API handling (#2369)
* feat: write records after exec (#2368)

* add returnOnOutput params
2023-09-29 10:12:00 +08:00
Yang Luo
1461268a51 Allow redirect URL for casdoor-app 2023-09-27 22:37:57 +08:00
Yang Luo
5ec49dc883 feat: fix claims.tag and UserWithoutThirdIdp missing fields, fix for Rust SDK 2023-09-27 18:07:57 +08:00
Yang Luo
5c89705d9e feat: allow CORS for 127.0.0.1 2023-09-27 14:10:59 +08:00
Yang Luo
06e3b8481f Improve adapter error handling 2023-09-27 01:11:58 +08:00
Yang Luo
81a8b91e3f Fix enforcer policy add and delete 2023-09-27 00:18:21 +08:00
Yang Luo
56787fab90 Improve adapter.UseSameDb 2023-09-26 23:41:09 +08:00
Yang Luo
1319216625 Add adapter.UseSameDb 2023-09-26 23:41:08 +08:00
haiwu
6fe5c44c1c feat: support radius accounting request (#2362)
* feat: add radius server

* feat: parse org from packet

* feat: add comment

* feat: support radius accounting

* feat: change log

* feat: add copyright
2023-09-26 22:48:00 +08:00
Yang Luo
981908b0b6 Fix crash in LDAP's sync: GenerateIdForNewUser() 2023-09-26 19:12:28 +08:00
Yang Luo
03a281cb5d Improve CorsFilter code 2023-09-26 14:51:38 +08:00
Yang Luo
a8e541159b Allow localhost in CorsFilter 2023-09-26 00:03:26 +08:00
Yang Luo
577bf91d25 Refactor out setCorsHeaders() 2023-09-26 00:02:31 +08:00
Yang Luo
329a6a8132 Fix get-pricing and get-plan API null error handling 2023-09-25 22:11:08 +08:00
Yang Luo
fba0866cd6 Fix error handling in StartRadiusServer() 2023-09-25 20:55:02 +08:00
UsherFall
aab6a799fe fix: use client secret field for providers (#2355)
* feat: fix key exposure problem

* fix display bug
2023-09-24 18:35:58 +08:00
haiwu
b94d06fb07 feat: add some Radius protocol code (#2351)
* feat: add radius server

* feat: parse org from packet

* feat: add comment

* Update main.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-09-24 16:50:31 +08:00
Yang Luo
f9cc6ed064 Add groups to role 2023-09-24 10:17:18 +08:00
Yang Luo
4cc9137637 Improve permission, adapter page UI 2023-09-24 09:56:06 +08:00
Yang Luo
d145ab780c feat: fix wrong elements in getPermissionsByUser() related functions 2023-09-24 09:13:54 +08:00
Yang Luo
687830697e Refactor getPermissionsAndRolesByUser() related code 2023-09-24 08:08:32 +08:00
Yang Luo
111d1a5786 Use UserInfo's ID in OAuth login 2023-09-23 00:13:13 +08:00
Yang Luo
775dd9eb57 Improve email provider error handling and fix bug 2023-09-21 23:11:58 +08:00
Mario Fischer
8f6c295c40 fix: empty AzureAD tenant id (#2349) 2023-09-21 08:34:23 +08:00
Dmitry Buryanov
2f31e35315 feat: update casbin to 2.77.2 (#2345)
* fix: make redirect_uri really optional in logout route

* feat: update casbin to 2.77.2
2023-09-20 23:37:55 +08:00
Yang Luo
b6d6aa9d04 Use GenerateIdForNewUser() in add-user API 2023-09-20 22:50:17 +08:00
Yang Luo
f40d44fa1c Refactor out GenerateIdForNewUser() 2023-09-20 22:45:00 +08:00
Dmitry Buryanov
3b2820cbe3 feat: make redirect_uri really optional in logout route (#2342) 2023-09-18 21:47:49 +08:00
Yang Luo
764e88f603 Change MFA issuer 2023-09-18 17:40:11 +08:00
UsherFall
7f298efebc feat: fix Apple OAuth issue (#2338)
* feat: fix sign in with apple bug

* fix username
2023-09-18 17:04:03 +08:00
Yang Luo
0fc48bb6cd Remove escapePath() to fix Unicode resource filenames 2023-09-17 21:31:22 +08:00
ZhiKai
c3b3840994 fix: fix update score permission check (#2335)
* fix: Fixed the missing permission check when updating the score field.
* Update object/user_util.go
2023-09-16 21:06:20 +08:00
Yang Luo
eacc3fae5a fix: handle more errors in downloadImage() 2023-09-15 22:53:09 +08:00
Yang Luo
ce7a2e924b feat: fix XML format issue in GenerateCasToken() 2023-09-15 22:38:04 +08:00
Yang Luo
ece060d03d feat: fix XML bug in GenerateCasToken() 2023-09-15 18:57:59 +08:00
Yang Luo
1276da4daa Check old password for normal user in SetPassword() 2023-09-15 10:21:02 +08:00
Yang Luo
616629ef99 Refactor CheckLoginPermission() code 2023-09-15 02:47:53 +08:00
Yang Luo
b633ecdcf2 Fix bug that cannot access application's public certificate for non "admin" owner 2023-09-15 00:56:40 +08:00
Yaodong Yu
a12ba7fb85 feat: allow CORS for UserInfo API in OIDC (#2313) 2023-09-13 18:11:13 +08:00
haiwu
08a0092974 feat: fix alipay payment provider (#2330)
* feat: support alipay payment provider

* feat: update notify params

* feat: update root cert

* feat: update ProviderEditPage.js

* feat: gofumpt
2023-09-13 17:30:51 +08:00
Yang Luo
bb04b10e8b Fix JSON issue in GenerateCasToken() 2023-09-13 16:45:11 +08:00
Yang Luo
ea1414dfd0 Fix typo 2023-09-13 00:19:32 +08:00
Yang Luo
32a8a028d5 Set TOTP issuer to Casdoor 2023-09-12 23:56:39 +08:00
Yang Luo
0fe34c2f53 Fix the issue that database syncer can't work with null-fields on source table 2023-09-12 16:06:44 +08:00
UsherFall
dc57c476b7 feat: support acs email provider (#2323)
* feat: support acs email provider

* feat: support acs email provider

* hide Test SMTP Connection button

* fix name acs
2023-09-12 02:13:37 +08:00
Cattī Crūdēlēs
a7cb202ee9 feat: fix JSON tag of EmailVerified (#2322)
Signed-off-by: Cattī Crūdēlēs <17695588+wzy9607@users.noreply.github.com>
2023-09-11 18:33:24 +08:00
Yang Luo
e5e264628e Remove "RUN mkdir tempFiles" 2023-09-09 20:24:18 +08:00
Palp1tate
8d4127f744 feat: improve dashboard UI for mobile devices (#2320) 2023-09-09 16:17:24 +08:00
Yang Luo
1305899060 Fix "app" user API denied issue 2023-09-09 15:44:36 +08:00
Yang Luo
411a85c7ab Remove useless GetMaxLenStr() 2023-09-09 15:40:35 +08:00
Yang Luo
f39358e122 Improve SMS Test's initial value 2023-09-09 02:38:15 +08:00
Yang Luo
a84752bbb5 Update go-sms-sender to v0.14.0 2023-09-09 02:15:38 +08:00
Baihhh
e9d8ab8cdb fix: hide tour component for mobile (#2317) 2023-09-08 22:53:46 +08:00
haiwu
d12088e8e7 feat: fix bug in pricing when signup by phone (#2316)
* fix: fix bug in pricing

* fix: remove log
2023-09-08 21:03:30 +08:00
Yang Luo
c62588f9bc Add EmailVerified to UserInfo 2023-09-08 18:27:14 +08:00
haiwu
16cd09d175 feat: support wechat pay (#2312)
* feat: support wechat pay

* feat: support wechat pay

* feat: update wechatpay.go

* feat: add router /qrcode
2023-09-07 15:45:54 +08:00
Yang Luo
7318ee6e3a Improve LocalFileSystemProvider's error handling 2023-09-07 10:49:39 +08:00
Yang Luo
3459ef1479 Improve termsOfUse UI and error handling 2023-09-07 10:33:20 +08:00
UsherFall
ca6b27f922 feat: fix notification provider frontend bug and twitter error (#2310) 2023-09-06 23:41:34 +08:00
Yang Luo
e528e8883b Add "localhost" to IsRedirectUriValid() 2023-09-06 21:14:58 +08:00
Yang Luo
b7cd604e56 Mask user in GenerateCasToken() 2023-09-06 18:36:55 +08:00
Yang Luo
3c2fd574a6 Refactor GenerateCasToken() 2023-09-06 18:35:13 +08:00
Yang Luo
a9de7d3aef Add groups to permission 2023-09-06 00:10:33 +08:00
Yang Luo
9820801634 Make Product's Providers longer (255) 2023-09-05 20:24:24 +08:00
UsherFall
c6e422c3a8 feat: add multiple notification providers (#2302)
* feat: support dingtalk notification provider

* feat: support lark notification provider

* feat: support microsoft teams notification provider

* feat: support bark notification provider

* feat: support pushover notification provider

* feat: support pushbullet notification provider

* feat: support slack notification provider

* feat: support webpush notification provider

* fix go-test error

* update notify repository

* feat: support discord notification provider

* feat: support google chat notification provider

* feat: support Line notification provider

* feat: support matrix notification provider

* feat: support twitter notification provider

* fix lint

* add no proxy provider

* update setting.js

* update social_teams
2023-09-05 17:05:34 +08:00
UsherFall
bc8e9cfd64 feat: storage provider's domain initial value bug (#2303) 2023-09-05 14:53:32 +08:00
Yang Luo
c1eae9fcd8 Fix TotpMfa's Verify() 2023-09-04 19:21:26 +08:00
YunShu
6dae6e4954 docs: fix all dead links (#2297)
https://github.com/Selflocking/linkchecker/actions/runs/6058177987
2023-09-03 21:19:23 +08:00
YunShu
559a91e8ee feat: fix bug that failed to set password after changing username (#2296)
* fix: failed to set password after changing username

When we add a new member to an organization using Casdoor, Casdoor will automatically generate a member with a random username, such as "user_qvducc". When we change the username, for example, to "yunshu", an issue arises where we are unable to successfully edit the password. This is because Casdoor searches for a user based on `owner/username`, and before any changes are saved, the username in the database remains "user_qvducc". However, the frontend uses `orgName/yunshu` instead of `orgName/user_qvducc` to send the request to change the password. As a result, the backend cannot find the user and the password change fails.

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-09-03 00:04:48 +08:00
Yang Luo
b0aaf09ef1 Add 7 new i18n languages 2023-09-02 18:49:43 +08:00
Yang Luo
7e2f67c49a Fix i18n error 2023-09-02 18:33:19 +08:00
Yang Luo
e584a6a111 Support using "?allowEmpty=1" to bypass empty displayName check in update-user API 2023-09-02 11:59:07 +08:00
YunShu
6700d2e244 fix: show error when frontend HTML entry does not exist (#2289)
* fix: add response when web file not found

The error flow is as follows:

Assuming my directory structure is as follows:

```tree
├── GitHub
│   ├── casdoor  # code repository
              ├── casdoor # compiled binary file
```

Execute the program in the `GitHub` directory:

```bash
./casdoor/casdoor
```

The working directory at this time is `GitHub`.

According to the code:

```go
func StaticFilter(ctx *context.Context) {
	urlPath := ctx.Request.URL.Path

   /// omitted

	path := "web/build"
	if urlPath == "/" {
		path += "/index.html"
	} else {
		path += urlPath
	}

	if !util.FileExist(path) {
		path = "web/build/index.html"
	}
	if !util.FileExist(path) {
		return
	}

    /// omitted
}
```

If the user accesses `/`, according to this code, the returned value is actually `web/build/index.html`. But the current directory is GitHub, and there is no `web/build/index.html` file. According to the following code, it will directly return:

```go
	if !util.FileExist(path) {
		return
	}
```

Then in `main.go`:

```go
	beego.InsertFilter("*", beego.BeforeRouter, routers.StaticFilter)
	beego.InsertFilter("*", beego.BeforeRouter, routers.AutoSigninFilter)
	beego.InsertFilter("*", beego.BeforeRouter, routers.CorsFilter)
	beego.InsertFilter("*", beego.BeforeRouter, routers.ApiFilter)
	beego.InsertFilter("*", beego.BeforeRouter, routers.PrometheusFilter)
	beego.InsertFilter("*", beego.BeforeRouter, routers.RecordMessage)
```

The introduction of `beego.InsertFilter` is as follows:

```
func InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) *App

InsertFilter adds a FilterFunc with pattern condition and action constant. The pos means action constant including beego.BeforeStatic, beego.BeforeRouter, beego.BeforeExec, beego.AfterExec and beego.FinishRouter. The bool params is for setting the returnOnOutput value (false allows multiple filters to execute)
```

When the `params` parameter is `false`, it runs multiple filters. The default is `true`.

So normally, if

```go
beego.InsertFilter("*", beego.BeforeRouter, routers.StaticFilter)
```

response something, the following filters will not be executed. But because the file does not exist, the function directly returns, causing the subsequent filters to continue executing. When it reaches

```go
beego.InsertFilter("*", beego.BeforeRouter, routers.ApiFilter)
```

it will start to check permissions:

```
subOwner = anonymous, subName = anonymous, method = GET, urlPath = /login, obj.Owner = , obj.Name = , result = deny
```

Then it will report this error:

```json
{
    "status": "error",
    "msg": "Unauthorized operation",
    "data": null,
    "data2": null
}
```

The solution should be:

```go
func StaticFilter(ctx *context.Context) {
	urlPath := ctx.Request.URL.Path

   /// omitted

	path := "web/build"
	if urlPath == "/" {
		path += "/index.html"
	} else {
		path += urlPath
	}

	if !util.FileExist(path) {
		// todo: response error: page not found
		return
	}

    /// omitted
}
```

* Update static_filter.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-09-02 00:06:04 +08:00
Cattī Crūdēlēs
0c5c308071 fix: sendCasAuthenticationResponseErr when pgtUrlObj if not valid url (#2287)
* fix: sendCasAuthenticationResponseErr when pgtUrlObj if not valid url

check pgtUrlObj.Scheme first will cause panic if url.Parse returns error.

* Update cas.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-09-01 22:26:57 +08:00
Yang Luo
0b859197da Fix CAS "/proxyValidate" API 2023-09-01 21:47:26 +08:00
Yang Luo
3078409343 Add CertPublicKey to Application 2023-09-01 21:16:51 +08:00
Tower He
bbf2db2e00 feat: support to use a different db schema for pg (#2281) 2023-09-01 18:02:13 +08:00
Yang Luo
0c7b911ce7 Fix enforcer edit page logic 2023-09-01 01:30:50 +08:00
Yang Luo
2cc55715ac Add app.conf existence check 2023-09-01 01:25:45 +08:00
Yang Luo
c829bf1769 Fix DummyPaymentProvider's return URL 2023-09-01 01:25:15 +08:00
Yang Luo
ec956c12ca Fix Email duplicated issue in update-user 2023-08-31 23:44:40 +08:00
Tower He
d3d4646c56 feat: fix can not create db when using pg with a dbname in DSN (#2280)
* fix: can not create db when using pg with a dbname in DSN

* Update ormer.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-31 18:05:38 +08:00
Yang Luo
669ac7c618 Don't encrypt user pass when user.PasswordType is non-empty when adding users 2023-08-31 17:49:36 +08:00
Yang Luo
6715efd781 Fix enforcer edit page 2023-08-31 17:32:36 +08:00
haiwu
953be4a7b6 feat: support subscription periods (yearly/monthly) (#2265)
* feat: support year/month subscription

* feat: add GetPrice() for plan

* feat: add GetDuration

* feat: gofumpt

* feat: add subscription mode for pricing

* feat: restrict auto create product operation

* fix: format code

* feat: add period for plan,remove period from pricing

* feat: format code

* feat: remove space

* feat: remove period in signup page
2023-08-30 17:13:45 +08:00
Yang Luo
943cc43427 Fix payment list and product edit actions 2023-08-28 21:01:23 +08:00
Yang Luo
1e5ce7a045 Fix crash in syncUsersNoError() 2023-08-28 01:51:06 +08:00
Baihhh
7a85b74573 fix: fix tour disabled state (#2264)
* fix: distinguish between pages that can tour or not

* Update OpenTour.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-27 23:18:14 +08:00
Yang Luo
7e349c1768 feat: fix crash bug in getSteps() 2023-08-27 21:58:58 +08:00
Baihhh
b19be2df88 fix: change the id to key in syncer (#2263) 2023-08-27 20:57:27 +08:00
Yang Luo
fc3866db1c Use XORM grammar in syncer 2023-08-27 18:15:23 +08:00
Yang Luo
bf2bb31e41 Add sslMode for syncer 2023-08-27 17:07:19 +08:00
Baihhh
ec8bd6f01d feat: add tour for list pages (#2243) 2023-08-27 16:40:31 +08:00
Yang Luo
98722fd681 Fix crash in app list page for normal user 2023-08-27 11:31:48 +08:00
Yang Luo
221c55aa93 Fix yarn build cmd 2023-08-27 11:17:18 +08:00
Yang Luo
988b26b3c2 Return error for RunSyncer() 2023-08-27 02:22:37 +08:00
Yang Luo
7e3c361ce7 Add all webhook events 2023-08-26 23:50:24 +08:00
Yang Luo
a637707e77 Fix null bug in IsAdminOrSelf() 2023-08-26 10:39:46 +08:00
Yaodong Yu
7970edeaa7 feat: password and invitation code verification rules (#2258) 2023-08-25 21:16:21 +08:00
haiwu
9da2f0775f fix: fix bug in Pricing (#2255) 2023-08-25 19:27:46 +08:00
Yang Luo
739a9bcd0d feat: add CasvisorUrl 2023-08-25 11:56:12 +08:00
Yang Luo
fb0949b9ed Fix docker cannot get version bug 2023-08-25 11:49:47 +08:00
Yang Luo
27ed901167 Restrict sysinfo page to global admin 2023-08-25 11:20:11 +08:00
Yang Luo
ceab662b88 Remove dup swagger page 2023-08-25 11:09:59 +08:00
haiwu
05b2f00057 feat: support Pricings flow (#2250)
* feat: fix price display

* feat: support subscription

* feat: fix select-plan-> signup -> buy-plan -> login flow

* feat: support paid-user to login and jump to the pricing page

* feat: support more subscription state

* feat: add payment providers for plan

* feat: format code

* feat: gofumpt

* feat: redirect to buy-plan-result page when user have pending subscription

* feat: response err when pricing don't exit

* Update PricingListPage.js

* Update ProductBuyPage.js

* Update LoginPage.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-24 23:20:50 +08:00
Yang Luo
8073dfa88c Remove tmpFiles folder usage 2023-08-24 22:03:36 +08:00
Yang Luo
1eeeb64a0c Add checkModel() for UserGroupEnforcer 2023-08-24 18:22:23 +08:00
Yaodong Yu
f5e0461cae feat: add invitation code for signup feature (#2249)
* feat: add invitation code for signup feature

* feat: add invitation code for signup feature
2023-08-24 13:42:17 +08:00
Andrey
a0c5eb241f feat: add fields to syncer (PreferredMfaType, TotpSecret, SignupApplication) #2239 (#2245) 2023-08-23 21:40:00 +08:00
Lars Lehtonen
4d8edcc446 fix: dropped controllers err (#2244)
Signed-off-by: Lars Lehtonen <lars.lehtonen@gmail.com>
2023-08-23 21:37:51 +08:00
Yaodong Yu
2b23c04f49 fix: add SignupApplication and type for user synced from LDAP (#2240) 2023-08-21 22:52:35 +08:00
Cattī Crūdēlēs
e60ee52d91 feat: replace satori/go.uuid with google/uuid (#2238) 2023-08-21 13:58:15 +08:00
UsherFall
c54b54ca19 fix: Adjust custom http to notification provider (#2237)
* feat: Adjust custom http to notification provider

* fix go linter

* update ProviderEditPage

* update ProviderEditPage
2023-08-20 21:04:30 +08:00
Yaodong Yu
f0e097e138 feat: fix home page (#2236)
* fix: home page

* fix: home page
2023-08-20 00:58:39 +08:00
Yang Luo
25ec1bdfa8 Fix bug in getUserOrganization() 2023-08-20 00:53:51 +08:00
Yang Luo
ea7718d7b7 Use Casvisor for records 2023-08-20 00:44:01 +08:00
Yang Luo
463fa8b636 Add ormer_session.go 2023-08-19 18:41:08 +08:00
Yang Luo
11895902f4 Move getCreateDatabaseFlag() to ormer 2023-08-19 16:44:34 +08:00
Yang Luo
15269d3315 Refactor out conf_quota.go 2023-08-19 16:39:21 +08:00
Yang Luo
4468859795 Improve sendTest msg 2023-08-19 12:47:51 +08:00
UsherFall
914128a78a fix: Support Telegram Notification provider (#2225)
* fear: support telegram provider

* fix: fix telegram logo

* fix: fix telegram bot package

* Update telegram.go

* Update notification.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-19 12:33:00 +08:00
Yaodong Yu
e5a189e0f4 fix: remove isGlobalAdmin field in user (#2235)
* refactor: remove isGlobalAdmin field in user

* fix: upload xlsx

* fix: remove field in account table
2023-08-19 12:23:15 +08:00
Yang Luo
a07216d0e1 Improve contentType parsing in downloadImage() 2023-08-19 02:35:45 +08:00
haiwu
fec54944dd feat: fix CAS login bug (#2230)
* fix: cas login

* fix: cas login

* feat: rollback get-default-app change

* fix : move cas restrict logic to GetApplicationLogin()

* fix: format code

* fix: fix getOAuthGetParameters for cas

* fix: fix getOAuthGetParameters for cas

* fix: cas login
2023-08-19 01:15:41 +08:00
hsluoyz
a2db61cc1a chore: Revert "feat: restrict redirectUrls for CAS login" (#2234)
This reverts commit b7a37126ad.
2023-08-19 00:30:35 +08:00
Yaodong Yu
134541acde chore: put some dev dependency package to right place (#2232) 2023-08-18 22:17:16 +08:00
Yaodong Yu
59fca0342e chore: fix yarn build warning (#2231) 2023-08-18 21:25:57 +08:00
Yang Luo
abfc464155 Remove isEnabled for model, adapter and enforcer, improve UI 2023-08-18 19:22:47 +08:00
Yaodong Yu
a41f6880a2 feat: move policy table from adapter to enforcer and improve it (#2228)
* feat: improve policiy table

* feat: add connection test in AdapterEditPage.js

* feat: update button style
2023-08-18 19:00:21 +08:00
Yaodong Yu
d12117324c feat: support admin to enable MFA for other users (#2221)
* feat: support admin enable user sms and email mfa

* chore: update ci

* chore: update ci
2023-08-17 17:19:24 +08:00
hsluoyz
1a6c9fbf69 Fix typo in README 2023-08-17 14:47:09 +08:00
hsluoyz
dd60d79af9 Fix typo in README 2023-08-17 14:46:10 +08:00
Yang Luo
73d314c7fe Add MfaTotpPeriodInSeconds param 2023-08-16 21:48:54 +08:00
Yaodong Yu
27959e0f6f fix: fix crash in UserEditPage.js 2023-08-16 15:57:48 +08:00
Baihhh
47f40c5b24 feat: support 3 more UI languages (#2218)
Signed-off-by: baihhh <2542274498@qq.com>
2023-08-16 15:54:34 +08:00
haiwu
2ff9020884 feat: support Stripe payment provider (#2204)
* feat: add stripe payment provider

* feat: support stripe payment

* feat: delete todo comment

* feat: remove description struct

* feat: change outOrderId->orderId
2023-08-15 00:16:30 +08:00
Yang Luo
abaf4ca8d9 Make GetDashboard() faster 2023-08-14 15:43:09 +08:00
8ff0cfd6ec feat: support dashboard in homepage (#2207)
* feat: support dashboard

* feat: support dashboard
2023-08-14 15:31:29 +08:00
Yang Luo
7a2a40edcc Improve table columns 2023-08-14 12:19:02 +08:00
Yang Luo
b7a001ea39 Fix property empty issue 2023-08-14 12:09:50 +08:00
haiwu
891e8e21d8 feat: support Web3-Onboard provider (#2209)
* feat: add Web3-Onboard idp

* feat: update Web3-Onboard logo

* feat: update package.json

* feat: remove unused package

* feat: add yarn build param --max_old_space_size=4096

* feat: remove log

* feat: add Wallet configure

* feat: remove hardware wallets
2023-08-13 23:58:57 +08:00
Baihhh
80b0d26813 fix: synchronize update the syncers (#2201)
Signed-off-by: baihhh <2542274498@qq.com>
2023-08-13 22:30:57 +08:00
Yaodong Yu
db4ac60bb6 feat: fix LDAP mobile field incorrect mapped (#2206) 2023-08-12 13:45:26 +08:00
Yang Luo
33a922f026 Add custom HTTP SMS provider 2023-08-12 12:52:53 +08:00
Yang Luo
9f65053d04 Improve i18n 2023-08-12 02:44:38 +08:00
Yang Luo
be969e5efa Fix typo 2023-08-11 22:18:35 +08:00
Yang Luo
9156bd426b ci: Show provider.displayName in signin button 2023-08-11 16:29:52 +08:00
Yang Luo
fe4a4328aa feat: refactor code in InitApi() 2023-08-11 16:17:29 +08:00
Yaodong Yu
9899022bcd fix: check enforcer should not be nil (#2199)
* fix: check enforcer should not be nil

* fix: check enforcer should not be nil

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-11 12:31:49 +08:00
Yaodong Yu
1a9d02be46 feat: use the casbin model to store relationships between users and groups (#2178)
* fix:reslove conflict

* fix: remove interface
2023-08-11 10:59:18 +08:00
Yang Luo
eafaa135b4 Change builtInAvailableField back to 5 2023-08-11 02:45:11 +08:00
Yang Luo
6746551447 Improve error message in InitEnforcer() 2023-08-11 02:36:29 +08:00
Yang Luo
3cb46c3628 Add isKey to syncer's table 2023-08-09 00:33:04 +08:00
Yaodong Yu
558bcf95d6 feat: save policy in adapter edit page (#2190)
* fix: save policy in adapter

* fix: disable edit for builtin adapter
2023-08-09 00:12:53 +08:00
Yang Luo
bb937c30c1 Fix empty cert in getPaymentProvider() 2023-08-08 22:37:48 +08:00
Baihhh
8dfdf7f767 ci: add GoogleCloud and QiNiu in Storage (#2188)
* feat: add GoogleCloud and QiNiu in Storage

Signed-off-by: baihhh <2542274498@qq.com>

* Update qiniu_cloud.go

* Update storage.go

---------

Signed-off-by: baihhh <2542274498@qq.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-08 22:34:55 +08:00
Yang Luo
62b2082e82 Add getUserOrganization() to user edit page 2023-08-08 21:58:27 +08:00
Yang Luo
a1806439f8 Add UserPrincipalName and MemberOf to get-ldap-users API 2023-08-08 20:18:47 +08:00
Yang Luo
01e58158b7 feat: Remove useless code 2023-08-08 19:16:55 +08:00
Yaodong Yu
15427ad9d6 fix: fix add provider error (#2184) 2023-08-07 17:22:32 +08:00
YunShu
d058f78dc6 fix: fix broken links (#2181) 2023-08-07 01:02:03 +08:00
UsherFall
fd9dbf8251 feat: add multiple SMS providers (#2182)
* feat: add amazon sns and azure acs provider

* feat: add msg91 sms provider

* feat: add infobip sms provider

* feat: add ucloud sms provider

* feat: add baidu cloud sms provider

* fix: fix logo and azure acs
2023-08-07 00:59:17 +08:00
Yaodong Yu
3220a04fa9 fix: use org/groupName replace groupName (#2180) 2023-08-06 20:16:44 +08:00
Yaodong Yu
f06a4990bd fix: rename in init.go (#2179)
* fix: rename in init.go

* fix: remove blank line

* fix: remove blank line

* Update init.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-08-06 13:07:30 +08:00
Yang Luo
9df7de5f27 Improve menu icons 2023-08-05 18:00:24 +08:00
Yang Luo
56c808c091 Improve menu 2023-08-05 17:41:35 +08:00
Yang Luo
9fd2421564 Update @ant-design/cssinjs dependency to avoid build error 2023-08-04 01:22:57 +08:00
Yang Luo
689d45c7fa feat: fix org name cannot be changed bug 2023-08-03 18:48:37 +08:00
Yang Luo
c24343bd53 Fix XxxChangeTrigger() doesn't return error bug 2023-08-03 18:45:49 +08:00
Yang Luo
979f43638d Change builtInAvailableField to 10 2023-08-03 18:17:15 +08:00
Yaodong Yu
685a4514cd fix: revert adapter port vartype to int (#2174) 2023-08-03 09:35:16 +08:00
Yaodong Yu
a05ca3af24 feat: use role ID to search in GetPermissionsAndRolesByUser() (#2170) 2023-08-02 20:58:06 +08:00
Yang Luo
c6f301ff9e Support svg in downloadImage() 2023-07-31 20:23:28 +08:00
haiwu
d7b2bcf288 feat: support payment cancel state (#2165) 2023-07-31 15:24:13 +08:00
Yang Luo
67ac3d6d21 Fix typo 2023-07-31 15:23:44 +08:00
Yaodong Yu
912d5c6a7f fix: support enforcerId parameter in Enforce API (#2164) 2023-07-31 00:20:53 +08:00
Yang Luo
32fbb5b534 Support custom provider for storage API 2023-07-30 23:19:45 +08:00
Yang Luo
21004f3009 Fix GetResources() missing items bug 2023-07-30 22:47:14 +08:00
Yang Luo
463bacd53b Add GetDirectResources() 2023-07-30 22:01:10 +08:00
Baihhh
78dc660041 feat: support 3 more language (#2163)
Signed-off-by: baihhh <2542274498@qq.com>
2023-07-30 20:45:47 +08:00
Yang Luo
2fb9674171 Fix file not exist panic in StaticFilter() 2023-07-30 19:03:21 +08:00
Yang Luo
55c522d3b7 Improve provider type input box 2023-07-30 17:31:36 +08:00
Yang Luo
f879170663 Remove AI related code 2023-07-30 14:39:27 +08:00
Yang Luo
12e5d9b583 Remove adapter.file 2023-07-30 12:08:05 +08:00
haiwu
eefa1e6df4 fix: fix paypal payment provider and refactor payment code (#2159)
* feat: support paypal payment provider

* feat: support paypal flow

* feat: use owner replace org for payment

* feat: update paypal logic

* feat: gofumpt

* feat: update payment

* fix: fix notify

* feat: delete log
2023-07-30 11:54:42 +08:00
Yaodong Yu
026fb207b3 fix: remove model in adapter page (#2161) 2023-07-29 23:42:08 +08:00
Yaodong Yu
ea10f8e615 feat: make hard-coded authz adapter editable, rename adapter to ormer (#2149)
* refactor: rename casbinAdapter to casdoorAdapter

* feat: add initEnforcer

* fix: router

* refactor: make hard-coded code configurable

* fix: data type

* feat: support sqlite3

* feat: disable delete and edit name for built in resources

* feat: optimize code

* fix: init

* fix: e2e

* fix: remove datasourcename

* fix: revert rename

* refactor: change all ORM's Adatper to Ormer

* refactor: name
2023-07-29 15:07:04 +08:00
Yang Luo
74b058aa3f Fix sync-ldap-users() bug, brought by: 666ff48837 2023-07-29 13:14:55 +08:00
Yang Luo
6c628d7893 Fix static path not changed bug in makeGzipResponse() 2023-07-29 12:23:48 +08:00
Yang Luo
a38896e4d8 Improve swagger docs 2023-07-29 11:35:03 +08:00
Yang Luo
5f054c4989 Fix product links 2023-07-28 15:08:45 +08:00
Tower He
fb16d8cee6 fix: not set count of enforcers to the response (#2155) 2023-07-28 14:46:11 +08:00
Baihhh
5e4ba4f338 feat: add authorize button and defaultValue (#2152)
Signed-off-by: baihhh <2542274498@qq.com>
2023-07-27 23:55:35 +08:00
Yang Luo
ca47af2ee1 Make post_logout_redirect_uri optional for logout 2023-07-27 23:26:30 +08:00
Ilya Sulimanov
59da104463 fix: update ldap admin pwd only if changed (#2146)
* fix ldap pwd update

* fix: linter

* fix: simplify check
2023-07-27 17:49:15 +08:00
Yaodong Yu
c5bb916651 fix: fix response data in PricingPage.js (#2143) 2023-07-27 10:46:31 +08:00
WintBit
e98264f957 fix: application fails to call /api/get-resources (#2139)
just like other apis, resource.go.GetResources() no longer calls ApiController.RequireSignedInUser() to auth or check
2023-07-26 17:19:00 +08:00
June
6a952952a8 fix: unmask application for org admin (#2138)
* feat: unmask application with user admin

* Update application.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-26 17:17:49 +08:00
Yang Luo
ba8a0f36be Support custom actions in permission edit page 2023-07-26 14:49:45 +08:00
June
b5e9084e5d feat: en/decodeURI in permission/role name (#2137) 2023-07-26 13:08:35 +08:00
June
55d5ae10f2 fix: fix infinite loop in containsRole() (#2136) 2023-07-25 20:53:08 +08:00
Yang Luo
6986dad295 Use arg to control createDatabaseForPostgres() 2023-07-25 18:36:15 +08:00
Yaodong Yu
949feb18af feat: add basic enforcer manager (#2130)
* feat: add basic enforcer manager

* chore: generate swagger
2023-07-25 17:17:59 +08:00
haiwu
d1f88ca9b8 feat: support google one tap signin (#2131)
* feat: add google one tap support

* feat: gofumpt

* feat: add google provider rule conf

* feat: update i18n
2023-07-25 15:49:15 +08:00
Yaodong Yu
bfe8e5f3e7 fix: fix response data assignment error (#2129) 2023-07-25 13:52:31 +08:00
Yang Luo
702ee6acd0 Print log for StartLdapServer()'s error 2023-07-25 01:49:43 +08:00
Yaodong Yu
0a9587901a fix: fix response data assignment error in ApplicationEditPage.js (#2126) 2023-07-24 20:09:09 +08:00
Yaodong Yu
577bd6ce58 feat: fix response data assignment error (#2123) 2023-07-24 14:52:30 +08:00
Yaodong Yu
3c4112dd44 refactor: optimize the code to getEnforcer (#2120) 2023-07-24 14:02:34 +08:00
haiwu
b7a37126ad feat: restrict redirectUrls for CAS login (#2118)
* feat: support cas restricted login

* feat: add cas login i18n

* feat: add CheckCasService for all cas api

* feat: gofumpt

* feat: replace 404

* feat: reuse i18n

* feat: delete CheckCasService

* Update token_cas.go

* Update LoginPage.js

* Update token_cas.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-24 11:47:31 +08:00
UsherFall
8669d5bb0d chore: hide field of IntranetEndpoint in Tencent COS storage provider (#2117) 2023-07-23 19:02:42 +08:00
Baihhh
aee3ea4981 feat: improve TermsOfUse UI in mobile (#2106)
* style: Mobile interface adaptation

Signed-off-by: baihhh <2542274498@qq.com>

* Update index.css

---------

Signed-off-by: baihhh <2542274498@qq.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-23 15:28:13 +08:00
Yang Luo
516f4b7569 Fix response of /api/get-sorted-users and /api/get-user-count 2023-07-23 14:46:38 +08:00
UsherFall
7d7ca10481 fix: hide fields of minio storage provider (#2115)
* feat: hide field of minio storage provider

* feat: hide field of domain in minio storage provider
2023-07-23 14:40:30 +08:00
UsherFall
a9d4978a0f chore: hide fields of local file system storage provider (#2109)
* style: adjust local file system storage

* style: disable domain when use local file system
2023-07-23 11:48:15 +08:00
Yang Luo
09f40bb5ce Fix id of "/api/get-resource" API 2023-07-23 11:33:48 +08:00
Yaodong Yu
a6f803aff1 feat: refactor code to use responseOK everywhere (#2111)
* refactor: use responseOK return frontend format json data

* revert handle error

* revert handle error
2023-07-23 09:49:16 +08:00
Yang Luo
fc9528be43 Add createDatabaseForPostgres() 2023-07-22 16:19:13 +08:00
imp2002
58e8f9f90b feat: fix Effect in Casbin rule (#2103)
* fix: Add `Effect` to Casbin rule of role

fix: https://github.com/casdoor/casdoor/issues/2102

* Update permission_enforcer.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-21 18:01:37 +08:00
Yang Luo
e850e33f37 Fix error message of missing cert when login 2023-07-20 19:45:22 +08:00
haiwu
d7110ff8bf feat: support MetaMask provider (#2084)
* feat: add metamask provider

* feat: add eth login

* feat: check eth sign

* feat: finish metamask signin/signup

* feat: support MetaMask provider link/unlink

* feat: update web/craco.config.js to handle polyfill

* feat: gofumpt idp/metamask.go

* feat: update MetaMask logo path

* feat: support MetaMask avatar
2023-07-20 17:51:36 +08:00
f923a8f0d7 fix: provide detailed description of ldap in swagger (#2094)
* provide detailed description of ldap in swagger

* modify the directory of swagger

fix: provide detailed description of ldap in swagger
2023-07-20 12:32:48 +08:00
Yang Luo
7bfb74ba18 Fix typo 2023-07-19 19:34:43 +08:00
Yang Luo
38f031bc86 Show access secret if isAdminOrSelf is true in get-user and get-account APIs 2023-07-19 19:14:53 +08:00
Yang Luo
5c441d195c Add Effect to Casbin rule of add-permission 2023-07-19 18:52:22 +08:00
Yaodong Yu
0639564d27 fix: check group name cannot be same as organization name (#2090) 2023-07-19 11:37:28 +08:00
Yang Luo
6c647818ca feat: add "Sender number" input for Twilio SMS provider 2023-07-18 22:46:56 +08:00
Yaodong Yu
8bc73d17aa feat: fix bug that themeEditor can not load saved theme data (#2085) 2023-07-17 22:57:55 +08:00
Yang Luo
1f37c80177 feat: refactor code to add getStorageProvider() 2023-07-17 15:59:37 +08:00
Yaodong Yu
7924fca403 fix: hidden bug of "like" query (#2082) 2023-07-16 17:11:32 +08:00
Yang Luo
bd06996bab Improve CorsFilter for login API 2023-07-15 19:29:48 +08:00
Yang Luo
19ab168b12 Fix panic in func (c *ApiController) GetUser() if no user exists in DB 2023-07-14 20:57:59 +08:00
UsherFall
854a74b73e feat: fix the error when user uploads avatar to minio (https) (#2078)
* fix: Error reported when user uploads avatar to minio (https)

* Update provider.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-14 15:58:30 +08:00
yehong
beefb0b432 fix: fix event-stream streaming output in prod mode (#2076) 2023-07-14 11:59:26 +08:00
Yang Luo
d8969e6652 Support EnableSigninSession after SAML login 2023-07-14 11:27:18 +08:00
Yang Luo
666ff48837 Use id param in /sync-ldap-users API 2023-07-13 00:14:18 +08:00
Yang Luo
0a0c1b4788 Fix "Groups is immutable" bug when updating a user 2023-07-13 00:03:18 +08:00
Yang Luo
438c999e11 Add password mask to /get-ldaps and /get-ldap APIs 2023-07-12 23:21:47 +08:00
Yang Luo
a193ceb33d Fix bug in TestDeployStaticFiles() 2023-07-12 23:11:02 +08:00
Yang Luo
caec1d1bac Only consider x509 certs in /.well-known/jwks API 2023-07-12 22:39:39 +08:00
Denis Plynskiy
0d48da24dc feat: fix wrong rowKey for tables (#2070) 2023-07-12 21:12:36 +08:00
Yaodong Yu
de9eeaa1ef fix: init groups modify rule with admin (#2054) 2023-07-11 09:49:49 +08:00
Baihhh
ae6e35ee73 feat: fix bug that the password input disappears in login window (#2051)
Signed-off-by: baihhh <2542274498@qq.com>
2023-07-08 23:46:31 +08:00
Yaodong Yu
a58df645bf fix: fix state after mfa is enabled (#2050) 2023-07-08 22:35:31 +08:00
WintBit
68417a2d7a fix: /api/upload-resource panics when parsing file_type (#2046) 2023-07-07 16:18:25 +08:00
WintBit
9511fae9d9 docs: add swagger docs for Resource-API (#2044)
swagger files are all auto generated.
2023-07-07 14:28:10 +08:00
Yaodong Yu
347d3d2b53 feat: fix bugs in MFA (#2033)
* fix: prompt mfa binding

* fix: clean session when leave promptpage

* fix: css

* fix: force enable mfa

* fix: add prompt rule

* fix: refactor directory structure

* fix: prompt notification

* fix: fix some bug and clean code

* fix: rebase

* fix: improve notification

* fix: i18n

* fix: router

* fix: prompt

* fix: remove localStorage
2023-07-07 12:30:07 +08:00
Gucheng Wang
6edfc08b28 Refactor the code 2023-07-07 00:13:05 +08:00
Baihhh
bc1c4d32f0 feat: user can upload ID card info (#2040)
* feat:user can upload ID card(#1999)

Signed-off-by: baihhh <2542274498@qq.com>

* feat: user can upload ID card, add diff languages

Signed-off-by: baihhh <2542274498@qq.com>

---------

Signed-off-by: baihhh <2542274498@qq.com>
2023-07-06 20:36:32 +08:00
YunShu
96250aa70a docs: replace gitter links with discord (#2041) 2023-07-06 18:16:16 +08:00
Yaodong Yu
3d4ca1adb1 feat: support custom user mapping (#2029)
* feat: support custom user mapping

* fix: parse id to string

* Update data.json

* Update data.json

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-07-05 20:35:02 +08:00
Yang Luo
ba97458edd feat: fix StaticFilter issue 2023-07-05 17:54:39 +08:00
Yang Luo
855259c6e7 feat: improve getOriginFromHost() for local machine name 2023-07-05 09:51:08 +08:00
June
28297e06f7 feat: IntrospectToken return the right Jti (JWT ID instead of User Id) (#2035) 2023-07-03 19:01:06 +08:00
Yang Luo
f3aed0b6a8 Fix null panic in GetOrganizationByUser() 2023-07-03 14:56:14 +08:00
haiwu
35e1f8538e feat: fix panic when url.Parse() fails to parse URL (#2034) 2023-07-03 12:35:22 +08:00
Yang Luo
30a14ff54a Fix null issue in getDefaultApplication() 2023-07-02 09:44:48 +08:00
Yang Luo
1ab7a54133 Add DefaultApplication to conf 2023-07-02 09:15:22 +08:00
Yang Luo
0e2dad35f3 Improve OrganizationSelect width 2023-06-30 02:04:44 +08:00
Yang Luo
d31077a510 Remove conf values 2023-06-30 01:38:48 +08:00
Denis Plynskiy
eee9b8b9fe feat: add organization context select box for admin (#2013)
* feat: organization as context

* feat: organization as context with backend filtration

* Update app.conf

* update app.conf and hide organization select for mobile.

---------

Co-authored-by: dplynsky <dplynsky@ptsecurity.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-30 01:32:34 +08:00
Baihhh
91cb5f393a fix: fix Swagger docs page (#2025)
Signed-off-by: baihhh <2542274498@qq.com>
2023-06-30 00:48:39 +08:00
haiwu
807aea5ec7 feat: add tags to application (#2027)
* feat: add tags to application

* fix: fix for merge master

* feat: update i18n(backend&frontend) for application tags
2023-06-30 00:04:12 +08:00
Yaodong Yu
1c42b6e395 fix: refactor the idp and regex code (#2030)
* refactor: validate util and idp

* chore: clean code

* chore: clean code
2023-06-29 21:44:14 +08:00
Ilya Sulimanov
49a73f8138 fix: getOrganization without pagination for global admin (#2028)
* fix: getOrganization without pagination for global admin return only built-in org

* fix gofumpt
2023-06-29 18:56:19 +08:00
Yang Luo
55784c68a3 Fix bug in /get-organizations API for org admin 2023-06-28 09:19:39 +08:00
June
8080b10b3b feat: show code signin page with password disabled (#2021) 2023-06-28 00:38:48 +08:00
Trần Thanh Tịnh
cd7589775c feat: replace all panic by response err (#1993)
* fix: missing return after response error

* feat: handle error in frontend

* feat: disable loading and catch org edit error

* chore: i18 for error message

* chore: remove break line

* feat: application catching error
2023-06-27 21:33:47 +08:00
Yaodong Yu
0a8c2a35fe feat: add TOTP multi-factor authentication (#2014)
* feat: add totp multi-factor authentication

* feat: add license

* feat:i18n and update yarn.lock

* feat:i18n

* fix: i18n
2023-06-24 18:39:54 +08:00
XDTD
d1e734e4ce fix: set the default value of user.Groups for syncer (#2016)
fix: set the default value of user.Groups for syncer
2023-06-24 18:29:50 +08:00
XDTD
68f032b54d fix: add isReadOnly for syncer (#2015)
* feat: add read only mod for syncer

* feat: change readOnlyEnable to isReadOnly
2023-06-24 17:56:41 +08:00
June
1780620ef4 feat: handle error when permission not found (#2012) 2023-06-24 00:30:43 +08:00
Yang Luo
5c968ed1ce Fix avatar cannot show issue 2023-06-23 15:53:41 +08:00
Yang Luo
4016fc0f65 Add EnableChatPages to Conf 2023-06-23 11:35:34 +08:00
June
463b3ad976 fix: refactor and optimize Enforce() API (#2009) 2023-06-22 17:45:24 +08:00
Yang Luo
b817a55f9f Fix error handling in SetPassword() 2023-06-22 14:51:56 +08:00
June
2c2ddfbb92 feat: optimize batch-enforce (#1997) 2023-06-22 14:40:09 +08:00
Alex OvsInc
cadb533595 fix: unsafe verification username in CheckUsername (#2006)
* Customization of the initialization file

* Unsafe verification username in CheckUsername
2023-06-21 23:20:23 +08:00
Yang Luo
a3b0f1fc74 feat: add owner to getUserByWechatId() 2023-06-21 21:29:53 +08:00
Yaodong Yu
c391af4552 feat: improve MFA by using user's own Email and Phone (#2002)
* refactor: mfa

* fix: clean code

* fix: clean code

* fix: fix crash and improve robot
2023-06-21 18:56:37 +08:00
Alex OvsInc
6ebca6dbe7 fix: Gosec/sec fixes (#2004)
* Customization of the initialization file

* fix: G601 (CWE-118): Implicit memory aliasing in for loop

* fix: G304 (CWE-22): Potential file inclusion via variable

* fix: G110 (CWE-409): Potential DoS vulnerability via decompression bomb
2023-06-21 18:55:20 +08:00
Yang Luo
d505a4bf2d Remove org API calls in PasswordModal page 2023-06-21 00:49:03 +08:00
Yang Luo
812bc5f6b2 Fix "nu" bug in GetLanguage() 2023-06-20 21:16:01 +08:00
Xinhao Yuan
f6f4d44444 feat: remove url.JoinPath() to be compatible with Go 1.17 (#1995) 2023-06-20 17:44:40 +08:00
StevenLei
926e73ed1b fix: fix "Accept-Language" parsing in request (#1996) 2023-06-20 17:43:48 +08:00
Yaodong Yu
65716af89e feat: deprecate the user group relation table (#1990)
* fix: deprecate the user group relation table

* fix: clean code

* fix: fix trigger

* Update group.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-19 19:08:45 +08:00
Yang Luo
d9c4f401e3 Fix error in downloadImage() 2023-06-19 17:52:01 +08:00
Yang Luo
58aa7dba6a Fix groups in GetUserInfo() 2023-06-19 11:06:55 +08:00
Yang Luo
29fc820578 Set User.groups to [] 2023-06-19 09:42:17 +08:00
Yaodong Yu
d0ac265c91 fix: Deprecate the id field in group (#1987) 2023-06-18 23:33:13 +08:00
hsluoyz
3562c36817 feat: Revert "fix: fix URL path in MinIO storage provider" (#1988)
This reverts commit 3699177837.
2023-06-18 23:08:40 +08:00
Yang Luo
7884e10ca3 Refactor adapter's owner and organization 2023-06-18 00:22:12 +08:00
Yang Luo
12dee8afd3 Fix null options in checkPasswordComplexity() 2023-06-17 22:38:02 +08:00
Yang Luo
ac4b870309 Improve getFaviconFileBuffer() 2023-06-17 12:50:01 +08:00
Yang Luo
b9140e2d5a Refactor refreshAvatar() 2023-06-17 11:43:46 +08:00
Yang Luo
501f0dc74f Add user_avatar.go 2023-06-17 01:25:15 +08:00
Yang Luo
a932b76fba Remove useless check in SetPassword() 2023-06-17 00:58:31 +08:00
leoil
0f57ac297b ci: add password complexity options to organization edit page (#1949)
* Support uploading roles and permissions via xlsx file.

* Template xlsx file for uploading users and permissions.

* reformat according to gofumpt.

* fix typo.

* add password complexity options to organization edit page.

* add password complexity options to organization edit page.

* Fixed Typos.

* Fixed Typos.

* feat:add password complexity options to organization edit page

* Auto generate i18n fields.

* Refactor code according to instructions

* Support autocheck passwd complexity in frontend when setting passwd in user edit page.

* feat:Backend Support for password validation in signup and forget page.

* feat:Frontend Support for password validation in signup and forget page.

* Add default password complex option & Update historical empty filed with default option.

* Migrator for field `password_complex_options` in org table.

* feat: support frontend password complex option check in user_edit/forget/signup page.

* frontend update for user edit page

* update i18n file

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-17 00:07:36 +08:00
June
edc6aa0d50 feat: get all role/permission of an user (#1978) 2023-06-16 22:44:21 +08:00
Yang Luo
ebc0e0f2c9 Update i18n words 2023-06-16 22:06:54 +08:00
Yang Luo
63dd2e781e Update backend i18n files 2023-06-16 21:55:08 +08:00
Yang Luo
b01ba792bb Rename to accessSecret 2023-06-16 20:42:15 +08:00
Yaodong Yu
98fb9f25b0 feat: fix bug that users in role don't work for permissions (#1977)
* feat: fix check login permission

* feat: fix check login permission
2023-06-16 20:14:27 +08:00
XDTD
cc456f265f feat: fix LDAP user password checking logic in GetOAuthToken() (#1975) 2023-06-15 21:04:09 +08:00
Yaodong Yu
7058a34f87 feat: complete group tree (#1967)
* feat: complete group tree

* feat: ui

* fix: i18n

* refactor code

* fix: support remove user from group

* fix: format code

* Update organization.go

* Update organization.go

* Update user_group.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-14 23:27:46 +08:00
UsherFall
8e6755845f ci: fix bug in PaypalPaymentProvider (#1972) 2023-06-13 23:33:03 +08:00
XDTD
967fa4be68 feat: add access key and secret key for user (#1971) 2023-06-13 22:18:17 +08:00
Yaodong Yu
805cf20d04 feat: fix incorrect VerifyTypePhone value (#1968) 2023-06-13 17:26:37 +08:00
907997375
2a8001f490 fix: clean timeout when componentWillUnmount in PaymentResult page (#1962) 2023-06-13 02:00:52 +08:00
UsherFall
451fc9034f fix: fix bug in PayPal payment provider (#1959) 2023-06-12 13:43:37 +08:00
Yaodong Yu
0e14a2597e feat: Add tree structure to organization page (#1910)
* rebase master

* feat: add group in userEditPage

* feat: use id as the pk

* feat: add groups item in user

* feat: add tree component

* rebase

* feat: ui

* fix: fix some bug

* fix: route

* fix: ui

* fix: improve ui
2023-06-12 09:27:16 +08:00
Yang Luo
ff87c4ea33 feat: fix createDatabase arg not recognized bug 2023-06-12 01:57:58 +08:00
Yang Luo
4f5396c70e Check error for CreateDatabase() 2023-06-12 01:47:26 +08:00
Yang Luo
3c30222fce Fix payment owner issue 2023-06-12 00:34:41 +08:00
Yang Luo
2d04731622 Provide default value for logConfig 2023-06-10 15:59:56 +08:00
Yang Luo
e0d2bc3dc9 Return error in GetProviderFromContext() 2023-06-10 15:51:26 +08:00
Jiawei Chen
0bda29f143 feat: show 404 error for non-existent objects in edit pages 2023-06-10 01:56:15 +08:00
Yang Luo
05703720c5 Add Custom to resourceType 2023-06-09 21:52:30 +08:00
hsluoyz
cc566bf31f Move DoMigration() after CreateTables() 2023-06-09 09:36:20 +08:00
XDTD
e93d8c19d9 feat: resolve user pages malfunction after using tableNamePrefix (#1945) 2023-06-08 00:43:05 +08:00
Yang Luo
f2e3182a69 Fix null value in backend Translate() 2023-06-07 02:17:48 +08:00
Yang Luo
f934531083 Fix organization search in some pages 2023-06-06 20:53:45 +08:00
XDTD
e1c0af345f feat: resolve casdoor as SAML SP with keycloak login not work bug (#1937)
* fix: resolve casdoor as SAML SP with keycloak login not work

* Update provider.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-06 15:19:00 +08:00
Yang Luo
3b3bfe39f9 Fix user field bug 2023-06-06 14:59:50 +08:00
Alex OvsInc
18cc952f8e feat: Customization of the initialization file (#1936) 2023-06-05 21:00:28 +08:00
Yang Luo
43439bc8c6 Apply tableNamePrefix before migration 2023-06-05 00:30:48 +08:00
Yang Luo
9a2800e3b3 Add error to Enforce() 2023-06-04 17:29:34 +08:00
Yaodong Yu
fdaad2b608 chore: refactor enforce() handler and update Swagger docs (#1931)
* chore: add swaggerof enforce api

* Update enforcer.go

* Update string.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-06-04 17:19:58 +08:00
Yang Luo
2d43fe0b39 Fix cert empty issue in GetSamlMeta() 2023-06-04 01:25:18 +08:00
Yaodong Yu
5d776a3ce6 fix: handle error of list in frontend (#1930) 2023-06-04 01:21:24 +08:00
Yang Luo
5ec7a54bf8 Add description fields to objects 2023-06-04 01:21:17 +08:00
Yang Luo
0c118477e8 Add groups to UserInfo 2023-06-04 01:21:10 +08:00
Yang Luo
c858d0e0b0 Fix model page bug 2023-06-03 10:35:58 +08:00
Yang Luo
9cffb43265 Fix subscription page bugs 2023-06-03 10:15:29 +08:00
Yang Luo
51a76518ad Init adapter in getEnabledSyncerForOrganization() 2023-06-03 09:23:36 +08:00
hsluoyz
08dbbab70e feat: revert "feat: fix the bug that sycner does not initialize" (#1926)
This reverts commit ec3c24ba68.
2023-06-03 09:17:34 +08:00
Yang Luo
0ec22ae6ff Fix null bug in getLanguage() 2023-06-03 00:29:08 +08:00
Yaodong Yu
ec3c24ba68 feat: fix the bug that sycner does not initialize (#1924) 2023-06-03 00:15:28 +08:00
Yang Luo
ed688efdbb Fix bug in org user list page 2023-06-02 22:09:18 +08:00
Yang Luo
06543a01d3 Add organization to /userinfo 2023-06-02 21:51:05 +08:00
Yang Luo
70c372c3f7 Fix Provider API responses 2023-06-02 11:49:38 +08:00
Yang Luo
b1b3184e75 Speed up user pagination query 2023-06-01 22:55:44 +08:00
Yang Luo
5349fa7ff3 Speed up object.DoMigration() 2023-06-01 22:25:19 +08:00
907997375
9147225956 feat: fix table sticky columns on chat and message pages (#1917) 2023-06-01 21:02:21 +08:00
Yang Luo
11f3af1ede Improve Select modes 2023-05-31 17:36:11 +08:00
Yang Luo
0aa4df40c6 Fix i18n 2023-05-31 11:46:03 +08:00
Yang Luo
7caa885131 Fix subscription bugs 2023-05-31 11:33:01 +08:00
Yang Luo
f4b69cad9b Add owner to select-plan page 2023-05-31 00:29:54 +08:00
Yang Luo
fb1db7823b Add DummyPaymentProvider 2023-05-30 23:25:58 +08:00
Sergey Zabodalov
10e66f8020 fix: Get logger configuration from app.conf file (#1907)
* feat: Get logger configuration from file

* feat: Get logger configuration from file

* Remove GetConfigLogs()
2023-05-30 21:30:09 +08:00
Yang Luo
4c8648d323 Add PaypalPaymentProvider 2023-05-30 20:32:05 +08:00
yehong
02e692a300 feat: return most backend API errors to frontend (#1836)
* feat: return most backend API errros to frontend

Signed-off-by: yehong <239859435@qq.com>

* refactor: reduce int type change

Signed-off-by: yehong <239859435@qq.com>

* feat: return err backend in token.go

Signed-off-by: yehong <239859435@qq.com>

---------

Signed-off-by: yehong <239859435@qq.com>
2023-05-30 15:49:39 +08:00
leoil
34151c0095 feat: Support uploading roles and permssions via xlsx files. (#1899)
* Support uploading roles and permissions via xlsx file.

* Template xlsx file for uploading users and permissions.

* reformat according to gofumpt.

* fix typo.
2023-05-28 11:29:43 +08:00
Yang Luo
c7cea331e2 Improve NewWechatPaymentProvider() arg 2023-05-27 19:28:24 +08:00
Yaodong Yu
8ede4993af feat: specify login organization 2023-05-27 19:02:54 +08:00
Crowdin Bot
d04dd33d8b refactor: New Crowdin Backend translations by Github Action 2023-05-27 09:52:47 +00:00
Crowdin Bot
8cb21253f6 refactor: New Crowdin translations by Github Action 2023-05-27 09:52:19 +00:00
UsherFall
7fc697b711 ci: fix bug in WeChat payment provider 2023-05-27 17:50:56 +08:00
Yaodong Yu
80e6e7f0a7 fix: fix bug about updating parent component value in CountryCodeSelect (#1891) 2023-05-25 10:45:13 +08:00
Yang Luo
d29fc88d68 Add getRawGetParameter() 2023-05-25 09:47:39 +08:00
Yaodong Yu
225e9cf70a fix: set initial value in CountryCodeSelect (#1890) 2023-05-24 23:27:04 +08:00
Yang Luo
c57c6e37dd Fix bug in getRedirectUri() 2023-05-24 23:22:25 +08:00
Yaodong Yu
4d860525bf feat: fix MFA page bug in OAuth login (#1889) 2023-05-24 21:31:03 +08:00
Yang Luo
a64263f812 Support "#" in redirectUri 2023-05-24 21:29:45 +08:00
Yang Luo
95ab2472ce Make logo length to 200 2023-05-23 21:57:35 +08:00
guangwu
54e4747dbc refactor: code-optimization (#1885)
* refactor: code-optimization

* fix: restoring code style

* fix: gofmt
2023-05-23 17:54:51 +08:00
Yang Luo
2389d47c34 Fix getFormattedDate() 2023-05-23 15:09:53 +08:00
guangwu
9c4f0f042e fix: update Go dependencies (#1880)
* Vulnerability fix : CVE-2021-30080  CVE-2021-39391 CVE-2022-41723 CVE-2022-21698  CVE-2023-26483 etc.

* fix: CVE-2021-30080  CVE-2021-39391 CVE-2022-41723 CVE-2022-21698  CVE-2023-26483 etc.
2023-05-23 14:43:18 +08:00
Yang Luo
e25e210b06 Improve upload resource page 2023-05-23 10:07:59 +08:00
jump2cn
df61a536c1 feat: add gzip support for static filter (#1875)
* feat: add gzip support for static filter

* Update static_filter.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-22 22:40:46 +08:00
XDTD
47da3cdaa0 fix: resolve get resource list problem (#1877) 2023-05-22 22:35:12 +08:00
hsluoyz
8d246f2d98 ci: revert "feat: fix UI in IE11" (#1879)
This reverts commit 44cd55e55f.
2023-05-22 22:21:56 +08:00
Yaodong Yu
44cd55e55f feat: fix UI in IE11 (#1878) 2023-05-22 16:59:37 +08:00
Yang Luo
6b42d35223 Fix state encoding for Moodle 2023-05-21 15:47:18 +08:00
Yang Luo
c84150cede Fix getObject() bug for some API 2023-05-21 11:07:01 +08:00
hsluoyz
de2689ac39 fix: revert "feat: fix UI in IE11" (#1873)
* Revert "feat: fix UI in IE11 (#1871)"

This reverts commit 319031da28.

* Update MfaVerifyForm.js
2023-05-21 00:43:42 +08:00
Ilya Sulimanov
88c0856d17 feat: add subscription managment (#1858)
* feat: subscription managment

* fix: remove console log

* fix: webhooks

* fix linter

* fix: fix via gofumpt

* fix: review changes

* fix: Copyright 2023

* Update account.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-20 15:56:21 +08:00
Yaodong Yu
319031da28 feat: fix UI in IE11 (#1871) 2023-05-19 21:47:02 +08:00
June
d20f3eb039 feat: support get user by userId and owner (#1870)
* feat: support get user by userId and owner

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-19 21:46:44 +08:00
Yaodong Yu
3e13e61d8f fix: sdk user is not Global Admin (#1868) 2023-05-19 21:24:55 +08:00
Yaodong Yu
1260354b36 fix: add sAMAccountName for AD search (#1869) 2023-05-19 21:16:59 +08:00
Jadson Santos
af79fdedf2 feat: add new language: "pt" (#1837)
* feat: Added new locales pt-br

* fix: Changed pt-br to pt

* feat: Updated app.conf

* feat: Updated Setting.js

* feat: Changed folder locales pt-br to pt

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-19 16:57:44 +08:00
Yang Luo
02333f2f0c Add "pt" language to backend 2023-05-19 16:42:31 +08:00
Yang Luo
79bd58e0e6 Use util.GetId() 2023-05-19 14:26:32 +08:00
Yang Luo
de73ff0e60 Add IsMaskedEnabled to provider API 2023-05-19 13:09:53 +08:00
Yang Luo
a9d662f1bd Improve Migrator_1_314_0_PR_1841 speed 2023-05-19 02:55:36 +08:00
Yaodong Yu
65dcbd2236 feat: compatible different uid of LDAP server (#1860)
* feat: compatible different uid of LDAP server

* Update organization.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-19 02:34:25 +08:00
Yaodong Yu
6455734807 fix: fix incorrect LDAP sync status (#1859) 2023-05-18 22:03:53 +08:00
Trần Thanh Tịnh
2eefeaffa7 feat: enforce by using resourceId (#1855)
* feat: enforce by using resourceId

* Update permission.go

* chore: fix cilint for enforcer.go

---------

Co-authored-by: tinhtt4 <tinhtt4@vng.com.vn>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-18 16:36:03 +08:00
Yang Luo
04eaad1c80 Fix getCertByApplication() 2023-05-18 16:32:43 +08:00
Yang Luo
9f084a0799 Can update user with OAuth values 2023-05-18 15:58:41 +08:00
Yang Luo
293b9f1036 Remove languages in app.conf 2023-05-18 15:44:11 +08:00
Yang Luo
437376c472 Fix CheckAccessPermission() 2023-05-18 13:36:16 +08:00
Yang Luo
cc528c5d8c Add object to webhook 2023-05-17 23:57:14 +08:00
Yang Luo
54e2055ffb Fix Beego filter: RecordMessage 2023-05-17 23:01:59 +08:00
Yang Luo
983a30a2e0 Dingtalk now supports linking with corpMobile 2023-05-17 22:14:57 +08:00
Yang Luo
37d0157d41 Fix application.EnableSignUp bug 2023-05-17 21:56:36 +08:00
Yang Luo
d4dc236770 Fix refreshExpireInHours zero value issue 2023-05-17 20:47:59 +08:00
Yang Luo
596742d782 Show org column better for admin (shared) 2023-05-17 17:30:47 +08:00
XDTD
ce921c00cd fix: resolve the problem of cert being unable to be accessed properly (#1850)
* fix: resolve the problem of cert being unable to be accessed properly

* Update CertEditPage.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-17 17:17:58 +08:00
Yang Luo
3830e443b0 Put webhook's RecordMessage() to FinishRouter stage 2023-05-17 16:32:12 +08:00
Yaodong Yu
9092cad631 feat: support forced binding MFA after login (#1845) 2023-05-17 01:13:13 +08:00
Yang Luo
0b5ecca5c8 Support empty application in page 2023-05-16 22:17:39 +08:00
Yang Luo
3d9b305bbb Add /api/health API 2023-05-16 21:47:34 +08:00
Yang Luo
0217e359e7 Update to Go 1.19.9 and Node 16.18.0 in Dockerfile 2023-05-16 20:33:31 +08:00
Yang Luo
695a612e77 Improve passwordType in CheckPassword() 2023-05-16 20:14:05 +08:00
Alexander Egorov
645d53e2c6 feat: User should have PasswordType like Organization (#1841)
* fixes #1840: [backend] User should have PasswordType like Organization is

* Update migrator.go

* Update and rename migrator_1_314_0_PR_1838.go to migrator_1_314_0_PR_1841.go

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-16 20:11:19 +08:00
Yang Luo
73b9d73f64 Add CustomFooter to Conf.js 2023-05-15 16:49:45 +08:00
1307
c6675ee4e6 feat: AI responses support streaming (#1826)
Is an AI response that supports streaming return
2023-05-13 11:31:20 +08:00
Yang Luo
6f0b7f3f24 Support modelId arg in Enforce() API 2023-05-12 21:39:57 +08:00
Yang Luo
776a682fae Improve args of Enforce() API 2023-05-12 21:32:48 +08:00
Yang Luo
96a3db21a1 Support LDAP search by user tag 2023-05-12 13:03:43 +08:00
Yang Luo
c33d537ac1 Add formCssMobile to application 2023-05-12 12:16:03 +08:00
Yang Luo
5214d48486 Fix authorized issue of UploadResource() API 2023-05-12 01:00:06 +08:00
Yang Luo
e360b06d12 Fix termsOfUse upload in application edit page 2023-05-10 23:57:03 +08:00
Yang Luo
3c871c38df Fix message and chat owner bug 2023-05-10 22:32:32 +08:00
jakiuncle
7df043fb15 fix: fix cypress error (#1817)
* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error

* fix: fix cypress error
2023-05-09 20:51:07 +08:00
XDTD
cb542ae46a feat: fix org admin permissions (#1822) 2023-05-09 00:06:52 +08:00
imp2002
3699177837 fix: fix URL path in MinIO storage provider(#1818) 2023-05-08 16:48:56 +08:00
helayzhang
3a6846b32c feat: fix bug that logging in with account/password cannot redirect successfully (When Casdoor working as a OAuth server) (#1819) 2023-05-08 16:37:56 +08:00
Yaodong Yu
50586a9716 feat: improve determination about whether dest is mail or phone and mask props (#1814) 2023-05-07 21:19:51 +08:00
Yang Luo
9201992140 Fix LDAP server bugs 2023-05-06 23:31:46 +08:00
Yaodong Yu
eb39e9e044 feat: add multi-factor authentication (MFA) feature (#1800)
* feat: add two-factor authentication interface and api

* merge

* feat: add Two-factor authentication accountItem and two-factor api in frontend

* feat: add basic 2fa setup UI

* rebase

* feat: finish the two-factor authentication

* rebase

* feat: support recover code

* chore: fix eslint error

* feat: support multiple sms account

* fix: client application login

* fix: lint

* Update authz.go

* Update mfa.go

* fix: support phone

* fix: i18n

* fix: i18n

* fix: support preferred mfa methods

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-05-05 21:23:59 +08:00
Yang Luo
5b27f939b8 Improve add model initialization 2023-05-05 01:51:34 +08:00
Yang Luo
69ee6a6f7e Move result page into entry page 2023-05-05 01:08:56 +08:00
Yang Luo
bf6d5e529b Add "from" to Email provider 2023-05-04 23:41:37 +08:00
Yang Luo
55fd31f575 Disable built-in/admin's unexpected change 2023-05-04 22:12:57 +08:00
Yang Luo
05c063ac24 Set email's SkipUsernameCheck to true 2023-05-04 00:29:12 +08:00
Yang Luo
38da63e73c Improve answer text 2023-05-02 23:33:09 +08:00
Yang Luo
cb13d693e6 Add getTokenSize() 2023-05-02 10:04:11 +08:00
Yang Luo
d699774179 Improve i18n.Translate() 2023-05-02 01:30:32 +08:00
Yang Luo
84a7fdcd07 Handle message answer 2023-05-02 01:30:06 +08:00
Yang Luo
2cd6f9df8e Add /api/get-message-answer API 2023-05-01 23:15:51 +08:00
Yang Luo
eea2e1d271 Add ai package 2023-05-01 17:19:45 +08:00
Yang Luo
48c5bd942c Fix chat UI 2023-05-01 16:23:48 +08:00
Yang Luo
d01d63d82a Improve chat menu height 2023-05-01 14:11:17 +08:00
Yang Luo
e4fd9cca92 Fix new chat button 2023-05-01 13:27:49 +08:00
Yang Luo
8d531b8880 Fix getStateFromQueryParams() crash when provider name is non-latin 2023-05-01 10:32:08 +08:00
Yang Luo
b1589e11eb Fix signin preview when there's no redirectUris 2023-05-01 10:31:21 +08:00
Yang Luo
b32a772a77 Add jobNumber to dingtalk provider 2023-04-29 21:48:52 +08:00
Yang Luo
7e4562efe1 Change org.defaultAvatar to 200 length 2023-04-29 08:33:04 +08:00
Yang Luo
3a6ab4cfc6 Support mobile in DingTalk userinfo 2023-04-29 01:24:45 +08:00
Joe Zhang
fba4801a41 feat: make redirectUri token param follow OAuth2 standard (#1796)
* fix: rename token to access_token in implicit flow; change ? in the redirect uri to &

* fix typo
2023-04-28 23:54:48 +08:00
June
da21c92815 feat: support sub role synced update (#1794) 2023-04-28 22:14:37 +08:00
OutOfEastGate
66c15578b1 feat: fix the order of Method and Name in System Info (#1797)
* fix: fixed the order of Method and Name in System Info

* fix: add i18n for System Info
2023-04-28 22:11:10 +08:00
Yang Luo
f272be67ab Improve i18n 2023-04-28 18:43:41 +08:00
OutOfEastGate
e4c36d407f feat: fix prometheus filter bugs (#1792)
* fix: fix prometheus

* fix: count latency with prefix api

* fix: latency should not be counted when startTime is nil
2023-04-26 22:18:48 +08:00
June
4c1915b014 fix: make query with like more precise (#1791) 2023-04-26 18:21:13 +08:00
Yaodong Yu
6c2b172aae feat: fix function CheckAccountItemModifyRule (#1789)
* feat: fix function CheckAccountItemModifyRule

* fix: admin changes its own username

* fix: current user changes its own username

* Update user.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-04-26 16:21:58 +08:00
Yaodong Yu
95f4f4cb6d feat: refactor out form package and optimize verification code module (#1787)
* refactor: add forms package and optimize verification code module

* chore: add license

* chore: fix lint

* chore: fix lint

* chore: fix lint

* chore: swagger
2023-04-25 23:05:53 +08:00
Yang Luo
511aefb706 Disable faulty Beego filter 2023-04-25 20:02:13 +08:00
OutOfEastGate
1003639e5b feat: support for prometheus (#1784) 2023-04-25 16:06:09 +08:00
Yaodong Yu
fe53e90d37 fix: signup page of the app-built-in failed to load (#1785) 2023-04-25 16:00:24 +08:00
OutOfEastGate
8c73cb5395 fix: fix golangci-lint (#1775) 2023-04-23 17:02:29 +08:00
Yang Luo
06ebc04032 Can add/delete chat 2023-04-23 01:19:44 +08:00
Yang Luo
0ee98e2582 Add loading to chat box 2023-04-23 00:25:09 +08:00
Yang Luo
d25508fa56 Improve chat UI 2023-04-22 23:20:40 +08:00
OutOfEastGate
916a55b633 fix: fixed failed to update information when name duplicate (#1773)
* fix: fixed failed to update information when name duplicate

* fix: Use GetOwnerAndNameFromId and GetId functions instead of split

* Update organization.go

* Update role.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-04-22 21:15:06 +08:00
OutOfEastGate
a6c7b95f97 fix: fixed rows duplicates after sort by column (#1772) 2023-04-22 20:18:38 +08:00
Yaodong Yu
4f8dd771bc feat: fix bug that can not get application in signup/oauth/ router (#1766) 2023-04-22 18:20:45 +08:00
UsherFall
e0028f5eed fix: add more events to webhooks (#1771) 2023-04-22 17:11:28 +08:00
XDTD
6d6cbc7e6f feat: add dynamic mode for provider to enable verification code when the login password is wrong (#1753)
* fix: update webAuthnBufferDecode to support Base64URL for WebAuthn updates

* feat: enable verification code when the login password is wrong

* fix: only enable captcha when login in password

* fix: disable login error limits when captcha on

* fix: pass "enableCaptcha" as an optional param

* fix: change enbleCapctah to optional bool param
2023-04-22 16:16:25 +08:00
Yang Luo
ee8c2650c3 Remove useless "/api/login/oauth/code" API and update Swagger 2023-04-22 09:47:52 +08:00
Yang Luo
f3ea39d20c Fix result page button link 2023-04-21 23:56:33 +08:00
Yang Luo
e78d9e5d2b Fix local file system storage provider path error 2023-04-21 10:12:09 +08:00
Yaodong Yu
19209718ea feat: fix wrong CAS login mode (#1762) 2023-04-20 22:18:02 +08:00
Yang Luo
e75d26260a Fix table name in getEnforcer() 2023-04-20 01:33:47 +08:00
Wenpeng Chen
6572ab69ce fix: fix pemContent decode error bug for WeChat Pay provider (#1751) 2023-04-19 22:13:13 +08:00
Jinhongyu
8db87a7559 fix: function comments (#1757)
Modify the function annotation so that the swagger can parse correctly
2023-04-19 21:19:48 +08:00
Yaodong Yu
0dcccfc19c feat: rollback anted to v5.2.3 (#1755) 2023-04-19 11:30:49 +08:00
imp2002
96219442f5 feat: fix Tencent Cloud OSS storage connect incorrect issue (#1752)
* fix: fix Tencent Cloud OSS storage connect incorrect

* Update provider.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-04-18 21:30:46 +08:00
Yaodong Yu
903745c540 fix: improve LDAP page UI (#1749)
* refactor: improve LDAP sync page

* refactor: update anted version

* chore: i18
2023-04-17 22:03:05 +08:00
Yang Luo
df741805cd Fix chat send 2023-04-17 20:50:03 +08:00
OutOfEastGate
ee5c3f3f39 feat: fix display name null error during 3rd-party binding (#1747) 2023-04-17 15:39:33 +08:00
Yang Luo
714f69be7b Use HTTP for IP host in getOriginFromHost() 2023-04-17 00:55:40 +08:00
Yang Luo
0d12972e92 Fix "auto single OAuth signin doesn't work" bug 2023-04-17 00:38:48 +08:00
Yang Luo
78b62c28ab Fix the wrong order of g policy in enforce() API 2023-04-16 22:26:22 +08:00
wht
5c26335fd6 feat: add rule option for phone in application's signup page (#1745) 2023-04-16 20:34:06 +08:00
Yang Luo
7edaeafea5 Call refreshAvatar() in addUser() 2023-04-16 01:00:02 +08:00
Yang Luo
336f3f7a7b Add user.refreshAvatar() 2023-04-16 01:00:02 +08:00
Yaodong Yu
47dc3715f9 feat: handle error when parsing samlResponse (#1744)
* fix: handle err from parse samlResponse

* fix: lint
2023-04-16 00:36:25 +08:00
Yang Luo
7503e05a4a Improve menu style 2023-04-15 18:08:21 +08:00
Yang Luo
b89cf1de07 Add karma to account items 2023-04-15 16:05:33 +08:00
Yang Luo
be87078c25 Fix vi i18n 2023-04-15 14:16:49 +08:00
Yang Luo
faf352acc5 Fix i18n 2023-04-15 11:17:31 +08:00
Yang Luo
0db61dd658 Add empty list item and expand menu by default 2023-04-15 10:54:56 +08:00
Yang Luo
ebe8ad8669 Improve UI effect 2023-04-15 10:54:56 +08:00
Yang Luo
2e01f0d10e Add input box 2023-04-15 10:54:55 +08:00
Yang Luo
754fa1e745 Add chat box 2023-04-15 10:54:55 +08:00
Yang Luo
8b9e0ba96b Add chat page 2023-04-15 10:54:55 +08:00
Yang Luo
b0656aca36 Add chat and message pages 2023-04-15 10:54:54 +08:00
erguotou
623b4fee17 feat: pre-ensure tempFiles folder exists before uploading files (#1739)
When deployed with docker, the user `casdoor` has no permission to mkdir `tempFiles`, so let's create the folder first.
2023-04-14 19:14:59 +08:00
Yaodong Yu
1b1de1dd01 feat: add LDAP custom filter support (#1719)
* refactor: improve ldap server code

* feat: custom filter

* fix: fix displayName mapping

* feat: add custom filter search fields

* chore: add license

* chore: i18n

* chore: i18n

* chore: update init field
2023-04-13 14:12:31 +08:00
XDTD
968d8646b2 fix: update webAuthnBufferDecode to support Base64URL for WebAuthn updates (#1734) 2023-04-12 21:33:54 +08:00
imp2002
94eef7dceb feat: fix adapter set organizations invalid bug (#1729) 2023-04-11 22:38:00 +08:00
rune
fe647939ce fix: fix CAS callback url not match bug (#1728)
Co-authored-by: mfk <mfk@hengwei.com.cn>
2023-04-11 19:26:57 +08:00
Dzung Do
984a69cb4b feat: fix wrong Vietnamese flag (#1724)
* fix wrong Vietnam country code

* fix wrong Vietnam country code

* fix wrong Vietnam country code

* fix wrong Vietnam country code
2023-04-10 22:42:12 +08:00
XDTD
098a1ece68 fix: rollback the version of webauthn in go mod to fix "atob" bug (#1721) 2023-04-10 20:14:27 +08:00
Wenpeng Chen
ad6f2ad2e1 feat: add wechatpay support. (#1710)
* feat: add wechatpay support.

* feat: add wechatpay support.

* Update wechatv3pay.go

* fix: update format.

* Update wechatv3pay.go

* Update wechatv3pay.go

* Update wechatv3pay.go

* fix: update file format.

* fix: improve the front of wechat payment.

* fix: change clientId2 to clientId.

* fix: fix the code format.

* fix: return backend error information to frontend.
2023-04-10 18:04:10 +08:00
Yang Luo
2d55252261 Add chat and message pages 2023-04-09 15:54:22 +08:00
Yang Luo
30ea3a1335 Improve getTags() 2023-04-09 15:54:21 +08:00
Yaodong Yu
b7d78d1e27 fix: validate parameter and nil in func updateUser (#1714)
* fix: validate parameter and nil in func updateUser

* fix: delete blank line
2023-04-09 10:35:30 +08:00
jivfly
3d5a645a3b feat: fix field name error of termsOfUse (#1715) 2023-04-09 01:01:04 +08:00
Gucheng Wang
4ad21e7781 fix: fix WeCom provider method 2023-04-07 01:10:46 +08:00
Yaodong Yu
b99a0c3ca2 feat: optimize the "forget password" page (#1709) 2023-04-06 23:06:18 +08:00
Yaodong Yu
e1842f6b80 feat: fix LDAP server handle filter without CN field as * (#1705)
* fix: set ldap server default filter name as *

* fix: default use built-in organization to bind

* chore: use cache reduce the ci test time
2023-04-04 20:51:28 +08:00
Max Baier
0781a3835d feat: improve i18n to have proper German translation in web/ (#1702) 2023-04-02 10:52:30 +08:00
Yang Luo
98a99f0215 Fix bug in getMemoryUsage() 2023-04-02 10:50:41 +08:00
Yang Luo
681b086de0 Fix session page highlight 2023-04-01 17:36:50 +08:00
Yaodong Yu
cdcc0b39e2 feat: filter not selected provider item (#1701) 2023-04-01 10:22:18 +08:00
Gucheng Wang
8eb68ba817 fix: fix AAD single-tenant mode bug 2023-03-31 19:24:03 +08:00
Yang Luo
8d1ae4ea08 Fix organization page bug 2023-03-31 18:35:57 +08:00
zzjin
9c8ea027ef feat: add the missing userId param docs for get-user API (#1698)
* Add roles to SAML response

* Fix: Add back missing get-user userId param doc.

Signed-off-by: zzjin <tczzjin@gmail.com>

* Update user.go

---------

Signed-off-by: zzjin <tczzjin@gmail.com>
Co-authored-by: Yang Luo <hsluoyz@qq.com>
2023-03-30 18:39:14 +08:00
Yang Luo
aaa56d3354 Add roles to SAML response 2023-03-30 14:43:34 +08:00
Yaodong Yu
b45c49d3a4 feat: fix incorrect preferred_username field mapping in OIDC (#1697) 2023-03-29 22:18:12 +08:00
Yaodong Yu
5b3202cc89 feat: fix phone validation bug in signup page (#1693) 2023-03-27 22:52:49 +08:00
Gucheng Wang
5280f872dc Speed up GetOAuthToken() 2023-03-27 14:05:44 +08:00
Yaodong Yu
fd61b963d5 feat: [SAML + long button crash] fix Disabling "Enable password" leads to white app page when SAML provider is active (#1691)
* fix: saml long button crush

* fix: sue svg

* Update Setting.js

* Update LoginButton.js

* Update ProviderButton.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-26 23:56:43 +08:00
Yaodong Yu
a8937d3046 feat: refactor agreement modal and create folders to classify components (#1686)
* refactor: refactor agreement modal and create folders to classify components

* fix: i18

* fix: i18

* fix: i18n
2023-03-26 18:44:47 +08:00
Yang Luo
32b05047dc Update system info API swagger 2023-03-26 10:19:59 +08:00
hsluoyz
117ee509cf feat: fix name format in application login: GetClientCredentialsToken() (#1639) 2023-03-25 23:02:08 +08:00
Yaodong Yu
daf3d374b5 fix: adjust error result position (#1683) 2023-03-25 09:36:23 +08:00
Yaodong Yu
337ee2faef feat: fix the bug that autoSignin generates two callback AJAX calls (#1682) 2023-03-24 23:17:54 +08:00
Gucheng Wang
989fec72bf Add /api/user API for Flarum's FoF Passport plugin 2023-03-24 01:02:04 +08:00
Gucheng Wang
76eb606335 Support AAD tenant auth URL 2023-03-23 22:37:53 +08:00
Yaodong Yu
c6146a9149 feat: fix bug that login by saml provider can not find application (#1676) 2023-03-23 21:38:33 +08:00
imp2002
f191488338 feat: support popup mode in OAuth (#1668)
* feat: support `popup` mode in OAuth

* feat: sendMessage when popup window closed

* fix: fix param name error
2023-03-22 00:15:17 +08:00
longxu0509
da7336a9a4 feat: support getting versionInfo in docker (#1673)
* feat: support getting versionInfo in docker

* fix: fix build

* fix: fix build

* fix: fix system
2023-03-21 20:46:17 +08:00
Gucheng Wang
b3806070ac Finish Go i18n texts 2023-03-20 01:10:48 +08:00
Gucheng Wang
c7b9a77b4a Remove Go i18n duplicates 2023-03-19 22:09:19 +08:00
June
4c4ad8320d feat: optimize getEnforcer, only load filtered polices (#1669) 2023-03-19 20:13:48 +08:00
Gucheng Wang
89d29c2519 Add "empty" to i18n 2023-03-19 20:13:07 +08:00
Gucheng Wang
98f962f818 Support i18n of id 2023-03-19 19:56:56 +08:00
Gucheng Wang
5989c4ff34 Remove i18n duplicates 2023-03-19 01:03:12 +08:00
Gucheng Wang
1de76e4da9 Finish i18n of vi 2023-03-19 00:13:16 +08:00
Gucheng Wang
4e62c255b3 Finish i18n of ru 2023-03-18 23:05:37 +08:00
Gucheng Wang
7ee54cb089 Finish i18n of ko 2023-03-18 22:24:06 +08:00
Gucheng Wang
bea03635a1 Finish i18n of ja 2023-03-18 21:46:17 +08:00
Gucheng Wang
2bc4cd9337 Fix i18n issue 2023-03-18 20:42:02 +08:00
Gucheng Wang
ed9ceaefe1 Finish i18n of de 2023-03-18 20:31:31 +08:00
Gucheng Wang
3dec2fdc18 Fix i18n issue 2023-03-18 19:05:58 +08:00
Gucheng Wang
31e4813df9 Finish i18n of fr 2023-03-18 18:54:05 +08:00
Gucheng Wang
263f804ab8 Finish i18n of es 2023-03-18 17:24:31 +08:00
Gucheng Wang
d383de256b Refactor to parseAllWords() 2023-03-18 14:16:15 +08:00
Gucheng Wang
28d24cc913 Improve i18n 2023-03-18 12:18:42 +08:00
Gucheng Wang
bd5c706317 Fix i18n code 2023-03-18 00:17:07 +08:00
Gucheng Wang
fba0021e22 Fix enableLinkWithEmail UI 2023-03-17 23:47:13 +08:00
hsluoyz
aba17e2bc1 feat: revert PR: "fix: disable cookie for static files" (#1666)
This reverts commit 312412ffe4.
2023-03-17 17:27:12 +08:00
wht
dd939b5c7e feat: improve tooltips and i18n for frontend (#1645)
* feat: Add english tooltips

* fix: add untranslated tooltips
2023-03-16 14:53:58 +08:00
Gucheng Wang
eeba21bf0d Support acme-challenge 2023-03-16 00:25:03 +08:00
Gucheng Wang
5e47406e09 Enable CORS for "OPTIONS" request 2023-03-16 00:24:18 +08:00
Yaodong Yu
fd883a3211 feat: improve verification error translation (#1660) 2023-03-15 23:44:38 +08:00
mos
312412ffe4 fix: disable cookie for static files (#1656)
Co-authored-by: chenjpu <bing.chen@hgcitech.com>
2023-03-15 22:09:10 +08:00
Yaodong Yu
295a69c5f7 feat: support LDAP with SSL/TLS enabled (#1655) 2023-03-15 11:12:31 +08:00
Yaodong Yu
a8a8f39963 feat: use GetUserCount to optimize login performance (#1653) 2023-03-14 14:38:39 +08:00
Yaodong Yu
90f8eba02d feat: can send Aliyun test SMS now (#1651) 2023-03-13 17:48:58 +08:00
Yaodong Yu
2cca1c9136 feat: refactor LDAP backend code and improve frontend operation (#1640)
* refactor: simplify ldap backend code and improve frontend operation

* chore: add skipCi tag in sync_test.go

* fix: ui
2023-03-12 11:12:51 +08:00
Gucheng Wang
c2eebd61a1 Add TestStartSyncJob() 2023-03-12 05:38:39 +08:00
Gucheng Wang
59566f61d7 Refactor sync code 2023-03-12 05:10:23 +08:00
Gucheng Wang
7e4c9c91cd improve sending text 2023-03-10 22:35:47 +08:00
Gucheng Wang
430ee616db fix user list shows all users bug 2023-03-10 21:59:57 +08:00
aiden
2e3a323528 feat: Dingtalk provider supports fetching organization email (#1636)
* feat(dingtalk): try to get email from corp app

* chore: format codes

* chore: format codes (#1)

* Delete .fleet directory

* fix: fix syntax errors

* Update dingtalk.go

* style: fmt codes with gofumpt

---------

Co-authored-by: aidenlu <aiden_lu@wochacha.com>
2023-03-10 21:47:54 +08:00
Gucheng Wang
09e8408a3d Fix Popconfirm text 2023-03-10 19:17:53 +08:00
陈温鹏
2998bbf4b9 fix: Put Popconfirm into a React component. (#1638)
* add "Sure to delete" to i18n(#1569)

* fix: add sure to delete to i18n

* fix: Put Popconfirm into a React component.
2023-03-10 19:16:08 +08:00
imp2002
404382f2e0 feat: fix incompatibility css inset when Safari version <=14.1 (#1635) 2023-03-09 22:01:39 +08:00
Gucheng Wang
71db1f62a9 Fix DingTalk oauth link 2023-03-09 21:11:16 +08:00
Gucheng Wang
07dc6bf7cd Refactor sysinfo page 2023-03-09 17:17:12 +08:00
longxu0509
2de3f6772d fix: add aheadCnt in sysinfo (#1632)
* feat: add sync module to bi-sync mysql

* feat: fix the delay problem

* feat: fix go mod

* feat: fix the varchar(100) parse error

* fix: fix go.mod space inconsistency

* fix: fix go.mod space inconsistency

* fix: use sql builder instead of concatenation

* fix: remove serverId

* fix: fix file is not `gofumpt`-ed (gofumpt) error

* feat: add mysql bi-sync

* feat: fix some data inconsistency problems

* feat: add function atuo get server uuid

* fix: encapsulate the struct to optimize the code

* fix: fix incorrect Casdoor version in system info page

* fix: fix incorrect root path

* Update sysytem_test.go

* feat: add aheadCnt means that the commit is ahead of version several times

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-09 16:07:13 +08:00
longxu0509
3f623570fd feat: fix incorrect Casdoor version in system info page (#1631)
* feat: add sync module to bi-sync mysql

* feat: fix the delay problem

* feat: fix go mod

* feat: fix the varchar(100) parse error

* fix: fix go.mod space inconsistency

* fix: fix go.mod space inconsistency

* fix: use sql builder instead of concatenation

* fix: remove serverId

* fix: fix file is not `gofumpt`-ed (gofumpt) error

* feat: add mysql bi-sync

* feat: fix some data inconsistency problems

* feat: add function atuo get server uuid

* fix: encapsulate the struct to optimize the code

* fix: fix incorrect Casdoor version in system info page

* fix: fix incorrect root path

* Update sysytem_test.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-09 13:28:23 +08:00
Yaodong Yu
a5dfe54a33 feat: fix LDAP page crash (#1630) 2023-03-08 21:31:55 +08:00
陈温鹏
7c4a6fea02 fix: add "sure to delete" to i18n (#1627)
* add "Sure to delete" to i18n(#1569)

* fix: add sure to delete to i18n
2023-03-07 22:38:48 +08:00
imp2002
ff4af6bb4e feat: remove ID field in enforcement (#1623) 2023-03-07 16:04:07 +08:00
Gucheng Wang
5bdede5596 Use go-webauthn/webauthn 2023-03-07 13:49:04 +08:00
wht
ed052b0e6a feat: add support for SUBMAIL sms (#1621)
* feat: add support for SUBMAIL sms

* fix: add SUBMAIL SMS icon
2023-03-06 21:23:45 +08:00
Yaodong Yu
16b1d0e1f0 fix: handle aliyun captcha error (#1624) 2023-03-06 21:23:03 +08:00
longxu0509
fea2a8cdbe feat: add bi-sync module (#1617)
* feat: add sync module to bi-sync mysql

* feat: fix the delay problem

* feat: fix go mod

* feat: fix the varchar(100) parse error

* fix: fix go.mod space inconsistency

* fix: fix go.mod space inconsistency

* fix: use sql builder instead of concatenation

* fix: remove serverId

* fix: fix file is not `gofumpt`-ed (gofumpt) error

* feat: add mysql bi-sync

* feat: fix some data inconsistency problems

* feat: add function atuo get server uuid

* fix: encapsulate the struct to optimize the code
2023-03-06 11:39:41 +08:00
Gucheng Wang
9d55238cef Fix code issue 2023-03-06 00:33:26 +08:00
Yaodong Yu
8427d63872 feat: fix empty value of countryCode for signup (#1620) 2023-03-05 21:52:40 +08:00
Yaodong Yu
e8a7b7ee9c feat: support all captcha for login (#1619)
* refactor: captcha modal

* feat: support all captcha when login

* chore: improve i18 in loginPage.js
2023-03-05 20:31:46 +08:00
Gucheng Wang
f8bc87eb4e Fix i18n error 2023-03-04 00:13:29 +08:00
Gucheng Wang
3e6ef9e666 Fix forget page i18n 2023-03-03 23:55:48 +08:00
Gucheng Wang
ef3d323f63 Improve SMS code 2023-03-03 22:44:22 +08:00
wht
aad9201b24 feat: add SMS test feature (#1606)
* feat: add SMS test

* fix: Add missing translation

* fix: Delete redundant information

* fix: remove unnecessary field

* Update sms.go

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-03 22:15:02 +08:00
Gucheng Wang
46f090361e Improve init_data json 2023-03-03 21:32:06 +08:00
fengxsong
1ae6adff8e fix(secure): remove user list from roles and permissions field to avoid leaking userlist (#1614)
* fix(secure): remove user list from roles and permissions field to avoid leaking userlist

Signed-off-by: fengxsong <fengxsong@outlook.com>

* Update permission.go

* Update role.go

---------

Signed-off-by: fengxsong <fengxsong@outlook.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-03 18:18:41 +08:00
Zayn Xie
59c95ca8a0 feat: fix ID parsing bug when calling api/logout (#1611)
Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>
2023-03-03 14:26:31 +08:00
Gucheng Wang
ca1b5feb78 Improve default captcha UI 2023-03-02 22:04:37 +08:00
Gucheng Wang
e50c832ff9 Fix login width 2023-03-02 20:49:13 +08:00
Yaodong Yu
8696b08db2 fix: empty countryCode of current account causes crash (#1603)
* fix: empty countryCode of current account cause crush

* Update UserEditPage.js

---------

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-03-01 22:09:48 +08:00
fengxsong
d21ae8a478 feat: support making configs in values.yaml (#1595)
Signed-off-by: fengxsong <fengxsong@outlook.com>
2023-03-01 20:17:04 +08:00
Zayn Xie
db401b2046 ci: add migration ci test (#1600)
* feat: add migration ci test

* feat: add migration ci test

* feat: add migration ci test

---------

Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>
2023-03-01 17:30:08 +08:00
Shenyz
7181489da0 fix: OIDC Userinfo API response for scope profile (#1598) 2023-03-01 16:56:39 +08:00
Yaodong Yu
e21087aa50 feat: refactor reset password api and forgetPage.js (#1601) 2023-03-01 15:57:42 +08:00
longxu0509
b38f2218a3 feat: add basic MySQL sync functionality (#1575)
* feat: add sync module to bi-sync mysql

* feat: fix the delay problem

* feat: fix go mod

* feat: fix the varchar(100) parse error

* fix: fix go.mod space inconsistency

* fix: fix go.mod space inconsistency

* fix: use sql builder instead of concatenation

* fix: remove serverId

* fix: fix file is not `gofumpt`-ed (gofumpt) error
2023-02-28 16:48:06 +08:00
Yaodong Yu
afd3c4ed25 fix: fix bug form country code init error (#1591) 2023-02-27 22:07:28 +08:00
Yaodong Yu
5caceb4ae2 feat: fix bug that signup country code is undefined (#1590)
* feat: fix signup country code is undefined

* refactor: valid phone number in CN
2023-02-27 20:10:59 +08:00
Gucheng Wang
f5672357e6 fix resetting phone bug 2023-02-25 15:46:54 +08:00
Gucheng Wang
181e7c8c7d Refactor out getCountryCodeOption() 2023-02-25 15:25:47 +08:00
Gucheng Wang
36c5a9d09b Sort country list 2023-02-25 15:08:08 +08:00
Gucheng Wang
9acb3c499e Can search country code 2023-02-25 14:57:23 +08:00
Gucheng Wang
0e9a3b0f30 don't update provider in preview 2023-02-25 12:31:08 +08:00
Gucheng Wang
d104a292e7 fix normal user phone edit control 2023-02-25 11:47:34 +08:00
Gucheng Wang
8fbd5b1a74 disable demo prompt for get-organizations API 2023-02-25 11:01:48 +08:00
Gucheng Wang
f5a05ac534 improve application homepage 2023-02-25 10:50:50 +08:00
Gucheng Wang
05fade1d05 fix role list link error 2023-02-25 09:39:19 +08:00
Gucheng Wang
8aefa02036 fix message length 2023-02-25 08:36:24 +08:00
Yaodong Yu
3b6ec3e7c4 feat: improve saml idp err message (#1584) 2023-02-24 21:20:57 +08:00
Yang Luo
910816c7a3 Fix bug in GetLanguage() 2023-02-24 20:17:23 +08:00
Yaodong Yu
412a8b5da7 fix: init name is inconsistent with frontend (#1583) 2023-02-24 14:28:34 +08:00
Yaodong Yu
8ebd16a14e feat: fix resetting email and phone bug (#1579) 2023-02-23 18:06:13 +08:00
Gucheng Wang
44ec854465 Refactor getClientIdLabel() and getClientSecretLabel() 2023-02-23 17:57:46 +08:00
imp2002
26e87b0d98 feat: fix compatibility with lower version browsers like Chrome 87 (#1578) 2023-02-22 20:57:57 +08:00
Gucheng Wang
7e0ea0b8d9 Fix missing accountItem crash bug 2023-02-22 12:16:05 +08:00
Gucheng Wang
ace8e9da06 Refactor getAppIdRow() 2023-02-22 12:10:55 +08:00
Yaodong Yu
aac8714d72 feat: handle aliyun SMS response error (#1577) 2023-02-21 20:08:23 +08:00
Yaodong Yu
e71e41b343 feat: fix captcha none type bug (#1572) 2023-02-19 16:56:51 +08:00
Yang Luo
6131286cbd Add getBuiltInAccountItems() 2023-02-19 09:45:06 +08:00
Yang Luo
3bda8fb9dc Remove Migrator_1_245_0_PR_1557 2023-02-19 09:38:57 +08:00
github-actions[bot]
11f55a474c refactor: New Crowdin translations (#1440)
* refactor: New Crowdin translations by Github Action

* refactor: New Crowdin Backend translations by Github Action

---------

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2023-02-18 23:46:44 +08:00
Yang Luo
4806e76cf6 Fix demo mode default login 2023-02-18 23:43:22 +08:00
Yang Luo
edbd3d4018 Add i18n banner 2023-02-18 18:09:43 +08:00
Yang Luo
3f0a741e6c Improve i18n languages 2023-02-18 17:35:36 +08:00
Yang Luo
d273fdd670 Use username as saml:NameID 2023-02-18 16:42:45 +08:00
Yang Luo
3ae81716b9 Fix getLdaps() GET 2023-02-18 16:27:47 +08:00
Yang Luo
3a70f4e788 Add Setting.isResponseDenied() 2023-02-18 16:21:12 +08:00
Yang Luo
842d4865b2 Fix router error message's i18n 2023-02-18 16:11:23 +08:00
imp2002
19fb7273bb fix: detect access denied by response message for demo mode (#1565)
fix: detect access denied by response message for demo mode
2023-02-18 12:12:54 +08:00
Yaodong Yu
943bd82731 feat: fix migrator_1_245_0_PR_1557.go (#1564) 2023-02-18 10:58:14 +08:00
Yaodong Yu
f2f962b893 fix: refactor functions and code (#1559) 2023-02-18 09:31:58 +08:00
Yaodong Yu
eb72c9f273 feat: support multiple country codes for sending SMS (#1557)
* feat: support multiple country code

* feat: improve UI

* feat: migrate accountItem

* fix: Aliyun compatible

* fix: phone validate

* fix: typo
2023-02-16 22:53:28 +08:00
Yang Luo
4605938f8e Refactor FetchFilter.js code 2023-02-16 22:50:08 +08:00
imp2002
14fa914e6f feat: add IsDemoMode for frontend (#1555)
* feat: add `IsDemoMode` for frontend

* fix: add i18n

* fix: support autologin and go same page

* fix: use i18n for button text
2023-02-16 20:36:30 +08:00
Yaodong Yu
e877045671 feat: fix CAS login crash bug (#1549) 2023-02-14 16:52:15 +08:00
jakiuncle
29f1ec08a2 fix: fix CI error by auto waiting for localhost:7001 to start up (#1548) 2023-02-14 14:50:58 +08:00
June
389744a27d feat: change claims to claimsWithoutThirdIdp when gen token (#1552) 2023-02-14 09:33:46 +08:00
June
dc7b66822d feat: change token ExpiresIn to second (#1550) 2023-02-14 09:18:30 +08:00
Yaodong Yu
efacf8226c fix: session Id error (#1554) 2023-02-13 22:58:26 +08:00
Zayn Xie
6beb68dcce fix: some bugs in session module when testing single-log-in (#1547)
Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>
2023-02-13 18:16:31 +08:00
Yang Luo
c9b990a319 Add removeExtraSessionIds() 2023-02-12 21:11:16 +08:00
Yang Luo
eedcde3aa5 Refactor session.go 2023-02-12 21:06:08 +08:00
Yaodong Yu
950a274b23 fix: region don't display in userEditPage (#1544) 2023-02-12 18:56:56 +08:00
Yang Luo
478bd05db4 Improve error handling in migrator 2023-02-12 10:39:20 +08:00
Zayn Xie
9256791420 feat: app session control and db migrate (#1539)
* feat: integrate application session management into Casdoor's session management (#774) && standardized the database migration process (#1533)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774)

* feat: integrate application session management into Casdoor's session management (#774) && standardized the database migration process

* feat: integrate application session management into Casdoor's session management (#774) && standardized the database migration process

* feat: integrate application session management into Casdoor's session management (#774) && standardized the database migration process

---------

Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>

* fix: migrate err

* fix: migrate err

* feat: app session control and db migrate

* feat: app session control and db migrate

* feat: app session control and db migrate

---------

Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>
2023-02-12 09:33:24 +08:00
Yang Luo
6f2ef32d02 Update xorm.io/core to v0.7.3 2023-02-11 17:46:34 +08:00
hsluoyz
8b8c866fd2 feat: replace gomail and disable the Email username check for Mailtrap (#1538) 2023-02-11 15:59:23 +08:00
June
6f7230e949 feat: support refresh token on GetOAuthToken (#1536) 2023-02-10 23:52:13 +08:00
wht
9558bb4167 feat: fix file name length problem (#1534) 2023-02-10 20:27:20 +08:00
imp2002
04567babf8 feat: fix click MenuItem blank part invalid bug (#1535) 2023-02-10 18:11:15 +08:00
Yaodong Yu
543b316942 feat: update swagger parameter id description (#1532) 2023-02-10 10:42:16 +08:00
Yaodong Yu
e2b6e8ee6e chore: unify migrate database way (#1530) 2023-02-09 19:28:15 +08:00
wht
e7e0518517 feat: fix the upload file name contains space problem (#1527) 2023-02-07 23:26:17 +08:00
LilithHC
943aa61869 feat: add provider icons and menus (#1522)
* fix: add provider icons(email and captcha) and menus

* fix: add provider icons and menus
2023-02-06 20:28:40 +08:00
wht
fcc75dd3be feat: fix the Unicode filename encoding bug in storage provider (#1518) 2023-02-04 18:09:18 +08:00
WangGuan
8698f4111a feat: add all remaining Goth providers to Casdoor OAuth login (#1484)
* feat: add Amazon support as OAuth 3rd-party login

* refactor: comebine the same URLs

* refactor: use hyper component to create login button

* feat: add all remaining Goth providers to Casdoor OAuth login

* refactor: remove redundant props

* fix: check provider auth url and params
2023-02-04 12:20:18 +08:00
jakiuncle
fdccb8b22b feat: Test whether the page can be accessed (#1517)
* feat: add new line

* feat: Test whether the page can be accessed

* feat: Change the e2e order

* feat: add Test Retries

* feat: change yarn.lock

* feat: add new line
2023-02-03 19:59:28 +08:00
Yaodong Yu
19e7d0b0bd refactor: improve code reuse rate (#1515) 2023-02-02 16:43:51 +08:00
Shenyz
f6a502f7ff feat: add user password in ldap server search result (#1513)
* fix: ldap server search return inconsistent cn attribute

* feat: add user password in ldap server search result
2023-02-02 15:33:44 +08:00
Yaodong Yu
b34e16b145 fix: table do not have unique key (#1512) 2023-02-02 13:53:18 +08:00
Gucheng Wang
11b56c340f Add refineUser() in generateJwtToken() 2023-02-02 00:34:56 +08:00
Yaodong Yu
cc6ea1b60e feat: fix application edit page crash and language icon position (#1511)
* fix: widget position and color

* feat: fix applicationEdit crush
2023-02-01 23:11:48 +08:00
Yaodong Yu
95b32d5ebf feat: support customize theme (#1500)
* refactor: simplify functions and improve variable naming

* feat: add themeEditor component

* feat: support customize theme

* chore: resolve conflict and add LICENCE

* chore: format code

* refactor: use icon replace background url

* feat: improve organization and application theme editor
2023-02-01 22:06:40 +08:00
imp2002
b47baa06e1 fix: remove "Agreement" in edit application error (#1506) 2023-01-31 22:56:19 +08:00
wht
24a824d394 feat: return the correct error message in the Edit Model (#1504) 2023-01-30 22:19:42 +08:00
Gucheng Wang
75b8357de8 Add properties to UserWithoutThirdIdp 2023-01-29 21:51:01 +08:00
Gucheng Wang
087405dad2 Fix isAllowedInDemoMode() 2023-01-26 17:56:29 +08:00
1307
6a6a1fa920 feat: fix missing phone number prefix in login screen (#1492)
fix: #1489
2023-01-24 23:19:44 +08:00
Gucheng Wang
907d18d2e9 Fix missing roles and permissions in user table 2023-01-23 00:36:55 +08:00
Zayn Xie
a728e083eb feat: reduce the size of token's user object (#1487)
* fix: Reduce the size of token, especially the user object (#1170)

* fix: Reduce the size of token, especially the user object (#1170)

* fix: Reduce the size of token, especially the user object (#1170)

Co-authored-by: Zayn Xie <84443886+xiaoniuren99@users.noreply.github.com>
2023-01-21 09:30:23 +08:00
Chell
457e6208ad feat: terms of use auto selected (#1485) 2023-01-19 20:31:21 +08:00
Chell
d10b1347a8 feat: add terms of use in signin page (#1476)
* feat: extract terms of use renderer

* fix: layout

* fix: form styling

* fix: required state

* feat: application terms of use setting

* fix: refactor getTermsOfUseContent

* fix: refactor renderers
2023-01-19 18:39:24 +08:00
qwqcode
f5b7f8cb45 chore(frontend): remove import of the third-party js script (#1436)
Signed-off-by: qwqcode <qwqcode@gmail.com>

Signed-off-by: qwqcode <qwqcode@gmail.com>
2023-01-19 11:31:27 +08:00
Yaodong Yu
5d9b17542f feat: end-user log out (#1356) 2023-01-17 22:57:05 +08:00
buptxxb65
0021226a60 fix: check the duplicated Application ClientId (#1481)
* fix: Check the duplicate ClientId and ClientSecret of Application.

* Bug fix
2023-01-17 17:37:20 +08:00
June
79fc0516dd feat: check username if it's changed (#1482) 2023-01-17 17:08:37 +08:00
June
a73be11990 feat: update permission when role deleted (#1480) 2023-01-17 17:04:58 +08:00
June
eddd8acbf4 feat: update permission rule when role updated (#1477) 2023-01-17 10:27:02 +08:00
Yaodong Yu
d0741e3705 feat: fix compatibility issue between Casbin request and model (#1478) 2023-01-15 12:06:10 +08:00
Liu
c66561dc9a feat: support sqlite database without cgo by using the modernc.org/sqlite driver (#1474)
* Refactor: update sqlite go driver to modernc.org/sqlite without cgo

* fix: update sqlite driver to modernc.org/sqlite

* fix: sqlite driver to modernc.org/sqlite

* Update adapter.go

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-01-14 20:11:23 +08:00
Yaodong Yu
fcdf1e8dd2 feat: improve Select component performance (#1472) 2023-01-12 23:11:11 +08:00
June
6d4f94986e feat: fix the bug that "app - global" admin is not allowed to update user (#1468) 2023-01-12 12:29:11 +08:00
Yaodong Yu
9ca686b240 feat: disable role and permission update and checks when updating user (#1466) 2023-01-12 11:40:32 +08:00
jakiuncle
c93bc0dda2 fix: add e2e cypress screenshots and videos if failed (#1465)
* feat: location error

* feat: location error

* feat: test error

* feat add e2e

* feat: delete cypress dependency

* feat: Add e2e error feedback
2023-01-11 23:56:09 +08:00
Yaodong Yu
7d25b9cdd8 feat: auto link accounts with the same email (#1464) 2023-01-11 23:19:16 +08:00
Yaodong Yu
ead844131e feat: improve user edit page to fix missing fields and page crash (#1463) 2023-01-11 16:15:06 +08:00
Yaodong Yu
ce2a4bbf6e feat: check uniqueness for email and phone when updating user (#1461)
* fix: check unique field when update user

* Update data.json

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2023-01-10 22:34:08 +08:00
疯魔慕薇
fcb80b800f feat: add refresh token to token login response (#1458)
Signed-off-by: 疯魔慕薇 <kfanjian@gmail.com>

Signed-off-by: 疯魔慕薇 <kfanjian@gmail.com>
2023-01-09 23:33:03 +08:00
jakiuncle
6daadf8d3c feat: add e2e test (#1445)
* add cypress

* feat: add crypress ci
2023-01-09 00:16:32 +08:00
Gucheng Wang
090389b86a Fix bug in CheckAccountItemModifyRule() 2023-01-07 13:49:06 +08:00
Gucheng Wang
b566af8e11 Improve i18n 2023-01-06 20:32:18 +08:00
Gucheng Wang
57028c2059 Remove duplicated i18n words 2023-01-06 20:24:14 +08:00
Gucheng Wang
a6e9084973 Remove duplicated i18n words 2023-01-06 20:12:32 +08:00
Gucheng Wang
6fb3e2cd7f Remove check_util i18n words 2023-01-06 19:57:13 +08:00
Gucheng Wang
8b6bde6d82 Remove generate_backend.go 2023-01-06 19:42:47 +08:00
Gucheng Wang
fb2b03f00f Add category to applyToOtherLanguage() 2023-01-06 19:26:00 +08:00
Gucheng Wang
1681138729 Add getAllFilePathsInFolder() 2023-01-06 19:04:38 +08:00
Ngọc Long
1d8b0a264e feat(login): add code login limit (#1442) 2023-01-06 18:51:43 +08:00
Yaodong Yu
b525210835 feat: destroy session after delete user (#1441)
* fix: destroy session after delete user

* feat: visual session

* fix: go lint

* feat: add translation

* feat: auto flush after offline

* fix: delete one session

* fix: move 403 page to baseListPage
2023-01-06 15:04:13 +08:00
imp2002
4ab2ca7a25 feat: fix checkPermissionForUpdateUser() logic (#1454)
* fix: fix `checkPermissionForUpdateUser()` logic

* fix: fix `checkPermissionForUpdateUser()` logic
2023-01-06 00:03:40 +08:00
June
dcf148fb7f fix: add GetMaskedRoles and GetMaskedPermissions when GetAccount (#1456) 2023-01-06 00:02:52 +08:00
Mr Forest
c8846f1a2d feat: fix translate bug in UpdateUser() (#1451)
* fix: fix translate error

* fix translate bug in UpdateUser()

* Delete DiscordLoginButton.js
2023-01-04 22:54:50 +08:00
June
0559298d6c feat: extend user with roles and permissions in GetAccount (#1449) 2023-01-04 20:23:57 +08:00
June
ddb5e26fcd fix: mask user in get-account response (#1450) 2023-01-04 18:40:36 +08:00
Liu
1f39027b78 fix: convert line endings to LF on checkout for all envs (#1448)
* Convert line endings to LF on checkout for all envs

* fix: convert line endings to LF on checkout for all envs
2023-01-04 18:36:38 +08:00
Yaodong Yu
eae3b0d367 feat: fix saml login failed by using oauth (#1443) 2023-01-03 19:42:12 +08:00
imp2002
186f0ac97b feat: check permission when update user (#1438)
* feat: check permission when update user

* feat: check permission when update user

* fix: fix organization accountItem modifyRule

* fix: fix organization accountItem modifyRule
2023-01-02 09:27:25 +08:00
imp2002
308f305c53 feat: add query and fragment response mode declare in OIDC (#1439) 2023-01-01 21:46:12 +08:00
Yaodong Yu
d498bc60ce feat: edit user properties (#1435) 2022-12-31 15:27:53 +08:00
Mr Forest
7bbe1e38c1 fix: fix translate error (#1432)
* fix:fix translate error

* Delete TelegramLoginButton.js

* Update data.json

* Update data.json

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-12-30 12:10:18 +08:00
Chell
f465fc6ce0 feat: support changing theme in antd 5 (#1430)
* feat: add global theme change function

* feat: add icons

* feat: in app theme changer

* feat: use antd built-in themes

* fix: multiple styling problem

* fix: theme init from localstorage

* feat: dark mode footer

* feat: casdoor logo color theme

* feat: select theme box icon adaptive to theme

* fix: menu bar style

* fix: language box style

* feat: translation

* feat: update translation of select theme box without reloading

* fix: mobile view

* fix: better structured select theme box

* feat: add compact icon

* fix: redundant theme fetch

* fix: redundant theme fetch

* fix: various styling problems
2022-12-29 22:30:37 +08:00
June
c952c2f2f4 feat: fix login with password bug when feature is disabled (#1428) 2022-12-27 14:46:57 +08:00
Yaodong Yu
86ae97d1e5 feat: fix the bug that spin is always showing when response error (#1424) 2022-12-24 17:55:36 +08:00
Yaodong Yu
6ea73e3eca fix: show background image in preview (#1425) 2022-12-24 17:47:05 +08:00
Chell
a71a190db5 feat: fix bug in redirectToLoginPage() (#1422) 2022-12-24 01:10:02 +08:00
Yaodong Yu
da69d94445 feat: fix the bug that spin in oauth is always showing (#1421) 2022-12-23 15:06:51 +08:00
imp2002
b8b915abe1 feat: check AccessPermission in multiple permissions (#1420) 2022-12-23 14:06:02 +08:00
Chell
5d1548e989 feat: fix absolute URL redirection (#1419)
* fix: redirect to absolute url

* fix: original jump
2022-12-23 11:05:15 +08:00
Yaodong Yu
a0dc6e06cd feat: add EntryPage for login, signup pages to fix background flashing issue (#1416)
* feat: fix flush in login Pages

* fix: code format

* fix: improve code

* Update App.js

* Update EntryPage.js

* fix: optimize api request

* Update App.js

* Update App.js

* fix: fix css

* fix: css and getApllicationObj

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-12-22 23:39:02 +08:00
WangGuan
ae130788ec feat: add Line support as OAuth 3rd-party login (#1413) 2022-12-21 02:25:58 +08:00
Gucheng Wang
f075d0fd74 Refactor out application.IsRedirectUriValid() 2022-12-21 00:35:33 +08:00
Alena Poliakova
65d4946042 feat: add valid key for creating token (#1411) 2022-12-20 22:05:00 +08:00
Liu
26acece8af feat: add all other missing objects to init_data (#1407)
* Add all other missing objects to init_data.json

* Format golang code

* feat: add all other missing objects to init_data

* feat: add all other missing objects to init_data
2022-12-18 01:49:42 +08:00
Gucheng Wang
48a0c8473f Improve README 2022-12-18 01:41:12 +08:00
Yaodong Yu
082ae3c91e fix: fix undefined owner bug in AdapterEditPage (#1406) 2022-12-17 21:21:39 +08:00
Yaodong Yu
1ee2ff1d30 feat: now dingtalk OAuth returns all error messages to frontend (#1405) 2022-12-17 21:10:20 +08:00
Gucheng Wang
c0d9969013 Add description to product 2022-12-16 23:35:30 +08:00
Gucheng Wang
1bdee13150 Fix bug in renderQrCodeModal() 2022-12-16 23:28:43 +08:00
imp2002
d668022af0 feat: fix length of policy and [policy_define] in model inconsistent (#1400) 2022-12-15 20:42:55 +08:00
Yaodong Yu
e227875c2b feat: add post methed for saml response (#1399) 2022-12-13 22:32:45 +08:00
Mr Forest
e473de3162 feat: fix sign in error via webauthn (#1398)
* fix: fix sign in error via webauthn

* fix review problems
2022-12-13 16:57:42 +08:00
Gucheng Wang
c5ef841d3f Disable isValidIdCard() 2022-12-12 01:07:31 +08:00
Gucheng Wang
d46288b591 Add renderQrCodeModal() 2022-12-12 00:42:45 +08:00
Chell
b968bf033c fix: case insensitive country name and country abbreviation search in region selection (#1394) 2022-12-11 18:14:25 +08:00
Mr Forest
eca2527bc0 feat: fix bug in signup and reset phone and email (#1396)
* fix: fix bug in signup and reset phone and email

* delete useless addition
2022-12-11 15:52:36 +08:00
Chell
ef836acfe9 fix: login page flag icon preload (#1393) 2022-12-11 11:22:58 +08:00
Yaodong Yu
a51f0d7c08 feat: init score in organization (#1388)
* feat: init score in organization

* Update OrganizationEditPage.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-12-10 22:27:12 +08:00
Yaodong Yu
e3c36beaf4 fix: the link button with disabled style but can click (#1390) 2022-12-10 22:14:20 +08:00
imp2002
19dce838d1 fix: fix invalid url in applications page (#1389) 2022-12-10 22:06:21 +08:00
Yaodong Yu
b41d8652f0 feat: fix showing wrong error messages (#1385) 2022-12-09 15:11:13 +08:00
imp2002
e705eecffe feat: response with status in casbin_adapter.go (#1384)
* fix: response standardized information with status in `casbin_adapter.go`

* fix: remove redundant statements
2022-12-08 10:22:59 +08:00
Mr Forest
2bb2c36f22 fix: add crowdin action env (#1381) 2022-12-07 14:05:21 +08:00
Mr Forest
1bb3d2dea9 feat: refactor backend i18n (#1373)
* fix: handle the dataSourceName when DB changes

* reduce duplication of code

* feat: refactor translation error message

* feat: use json intsead of ini file

* remove useless translation

* fix translate problems

* remove useless addition

* fix pr problems

* fix pr problems

* fix split problem

* use gofumpt to fmt code

* use crowdin to execute backend translation

* fix pr problems

* refactor: change translation file structure same as frontend

* delete useless output

* update go.mod
2022-12-07 13:13:23 +08:00
Gucheng Wang
96566a626b Increase Detail field size 2022-12-07 01:53:03 +08:00
Yaodong Yu
042e52bd16 feat: replace casdoor/goth with markbates/goth (#1374) 2022-12-06 17:18:29 +08:00
Yaodong Yu
e207fd243b feat: fix CSS issue that login error pages are not centered (#1371) 2022-12-06 14:00:17 +08:00
Gucheng Wang
30b7fd963f Reduce Resource key size 2022-12-06 11:30:42 +08:00
Yaodong Yu
ca314bbfb5 feat: refactor layout and fix footer CSS (#1370) 2022-12-06 00:50:17 +08:00
imp2002
812c44e070 feat: add and load policy within a specific permission (#1357)
* fix: add and load policy with a specific permission

* fix: use a clear variable name
2022-12-05 17:07:10 +08:00
imp2002
78e45d07cf fix: support RBAC With Domains/Tenants (#1333)
* feat: support RBAC With Domains/Tenants

* fix: add verify for `UpdatePermission`

* Update permission.go

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-12-05 16:08:17 +08:00
Yaodong Yu
0856977b92 feat: update to antd 5.0 (#1362)
* feat: update to ant5.X

* fix: incompatible styles

* fix: adjust the style
2022-12-04 23:05:30 +08:00
Chell
a44a4b0300 feat: fix React incorrect usage to fix issue that verification code must be submitted twice to succeed (#1348)
* fix: synchronized user login fields saving

* fix: synchronized user login fields saving

* recover changes

* fix: save username in step 2

* fix: format
2022-12-04 20:58:07 +08:00
Chell
4b29dd8c41 fix: responsive certs page editor (#1360)
* fix: responsive editor width

* fix: format
2022-12-04 16:04:04 +08:00
Yaodong Yu
165e2e33e3 fix: disable formcss in mobile (#1359) 2022-12-04 15:53:46 +08:00
Yang Luo
d13a307ad5 Allow org admin to access GetResources() 2022-12-03 01:10:45 +08:00
Mr Forest
27bd771fed feat: handle the dataSourceName when DB changes (#1352)
* fix: handle the dataSourceName when DB changes

* reduce duplication of code
2022-12-02 22:20:18 +08:00
Yaodong Yu
9f3ee275a8 feat: reformat frontend alert texts with correct i18n (#1341)
* fix: add i18

* fix: standard prompt message
2022-12-02 00:06:28 +08:00
Chell
fcda64ad7d fix: provider sort alphabetical order (#1347) 2022-12-01 22:51:10 +08:00
Yaodong Yu
d815bf92bd fix: handle add message in frontend (#1340) 2022-11-29 20:32:47 +08:00
WangGuan
7867060b71 feat: add quota limitation to organizations, users, providers and applications (#1339) 2022-11-29 11:01:41 +08:00
Mr Forest
8890d1d7c7 fix: check credential existence when signing via WebAuthn (#1336)
* fix: check credential existence when signing via WebAuthn

* fix review problem
2022-11-28 21:47:17 +08:00
Chell
6e6a0a074a fix: application edit mobile view (#1331)
* fix: application edit mobile view

* fix: decompose elements

* fix: decomposition

* fix: remove space component

* Update ApplicationEditPage.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-28 21:10:49 +08:00
Thai
cff3007992 feat: add get-permissions-by-role API (#1335) 2022-11-28 15:30:46 +08:00
Mr Forest
fe448cbcf4 feat: check user existence when signing in via verification code (#1334)
* fix:check user existence when logining by verification code

* fix review problems

* Update verification.go

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-28 00:11:33 +08:00
Chell
2ab25df950 fix: prompt page translation (#1330)
* fix: prompt page translation

* add multiple translations

* fix: translation consistency

* fix: translation consistency

* fix: add translation

* fix: add translation

* Update data.json

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-27 21:04:45 +08:00
WangGuan
b895926754 feat: use another filename when uploading a duplicated file instead of replacing it (#1329)
* fix: upload a file with the same name, not replace

* Update resource.go

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-27 17:32:15 +08:00
YiNN
5bb7a4153f feat: add cloudflare turnstile captcha (#1327)
* feat: add cloudflare turnstile captcha

* fix: rename turnstile to cloudflare turnstile
2022-11-26 17:17:49 +08:00
Yaodong Yu
b7cd598ee8 fix: fail to return after flush the page (#1325)
* fix: fail to return after flush the page 

Old methed just get the url path parameter when click the butten. But when the page flushed, the returnUrl will disappear, so can not return to the specified page.

* Update UserEditPage.js

* Update UserEditPage.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-25 23:08:45 +08:00
Yaodong Yu
b10fb97c92 feat: finish policy list management (#1317) 2022-11-25 16:02:20 +08:00
Yaodong Yu
b337b908ea feat: fix the bug that admin cannot upload avatar for other users (#1323) 2022-11-25 09:36:47 +08:00
Mr Forest
ba9d1e2388 fix: fix bug in GetAcceptLanguage() (#1322) 2022-11-24 20:43:35 +08:00
Mr Forest
29ec1d2d9c feat: update Xorm to v1.0.5 to fix the PostgreSQL bug in Xorm (#1321)
* fix:update xorm version

* fix pr problems

* update xorm version to 1.2.0

* update xorm version to 1.0.5

* fix pr problems

* generate go.sum file
2022-11-24 19:28:51 +08:00
Mr Forest
84a03f6c8e feat: add webhook for add/update org/provider (#1316) 2022-11-24 00:29:15 +08:00
会思考的下丘脑
56ff06bbea feat: add parameter v0 for Casbin APIs (#1315) 2022-11-23 22:39:17 +08:00
Yaodong Yu
7e756b8ee2 feat: manager applications in organization scope (#1290)
* feat: manager applications in organization scope(front end)

* fix: application can use own organization and admin provider

* fix: improve methed to get provider

* fix: modify provider methods by convention
2022-11-21 01:17:55 +08:00
Yaodong Yu
19ba37e0c2 feat: can specify available UI languages for an organization (#1306) 2022-11-19 22:11:19 +08:00
Mr Forest
b98ce19211 feat: fix bug in GetDefaultApplication() that caused login error for other orgs (#1299)
* fix:fix bug in GetDefaultApplication

* fix:fix bug in GetDefaultApplication
2022-11-16 00:39:05 +08:00
会思考的下丘脑
37d1a73c0c feat: encode redirectUri (#1297) 2022-11-15 19:05:59 +08:00
Yaodong Yu
727877cf54 fix: illegal user when new a permission (#1298) 2022-11-15 14:19:20 +08:00
Mr Forest
939b416717 fix: limit only under PC can login by following Wechat Official Account (#1293) 2022-11-14 09:03:55 +08:00
imp2002
f115843fbb feat: fix verification code send time's limit logic (#1292) 2022-11-13 22:00:48 +08:00
Mr Forest
aa6a4dc74f feat: support login by following wechat official account (#1284)
* show QRcode when click WeChat Icon

* update how to show qrcode

* handle wechat scan qrcode

* fix api problems

* fix url problems

* fix problems

* modify get frequency

* remove useless print

* fix:fix PR problems

* fix: fix PR problems

* fix:fix PR problem

* fix IMG load delay problems

* fix:fix provider problems

* fix test problems

* use gofumpt to fmt code

* fix:delete useless variables

* feat:add button for follow official account

* fix:fix review problems

* use gofumpt to fmt code

* fix:fix scantype problems

* fix Response problem

* use gofumpt to format code
2022-11-13 15:05:15 +08:00
cofecatt
462a82a3d5 fix: Add distinctions between access_token and refresh_token (#1280) 2022-11-13 13:00:25 +08:00
Dinn
262aeba7e2 fix(RoleEditPage): Fix a crash when the sample role domains is null (#1268) 2022-11-13 12:28:24 +08:00
Chell
61c2fd5412 feat: fix the issue of jumping back to the login page after resetting password (#1288)
* fix: redirect to login page

* fix: front end router

* fix: front end router

* fix: signup page router

* fix: redirect to login page
2022-11-13 12:16:49 +08:00
Chell
d542208eb8 feat: fix select language box overlay (#1289)
* fix: select language box overlay

* fix: select language box position

* fix: select language box position

* fix: select language box position
2022-11-13 10:52:22 +08:00
Yaodong Yu
f818200c95 feat: fix empty organization in adapter edit page (#1274) 2022-11-08 21:03:15 +08:00
Yaodong Yu
5bc2e91344 fix: fix typo (#1264) 2022-11-06 21:14:26 +08:00
Gucheng Wang
295f732b18 Show tag in i18n 2022-11-06 20:19:31 +08:00
cofecatt
770ae47471 feat: fix memory leak problem (#1257) 2022-11-06 01:43:27 +08:00
Chell
2ce4f96355 fix: forget page mobile view (#1263) 2022-11-05 22:54:22 +08:00
Chell
07ed834b27 fix: system info mobile view (#1261) 2022-11-05 22:46:52 +08:00
Yaodong Yu
8d686411ee feat: support add providers inside the Organization scope (#1250)
* feat: support add providers inside the Organization scope

Signed-off-by: magicwind <2814461814@qq.com>

* Update ProviderListPage.js

* fix: gloabal admin can see all providers

* fix: table fixed column warning

* fix: edit application page can get all providers

Signed-off-by: magicwind <2814461814@qq.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-11-04 21:31:08 +08:00
Yaodong Yu
ce722897f1 feat: support prefix path for storage files (#1258) 2022-11-04 21:08:39 +08:00
Mr Forest
a8381e875b feat: change all occurrences when a object name is changed (#1252) 2022-11-02 00:17:38 +08:00
Ke Wang
4c81fd7d16 feat: fix generating wrong x.509 private key file header (#1253)
According to the [official x509 documentation](https://pkg.go.dev/crypto/x509#MarshalPKCS1PrivateKey), the private key generated using `x509.MarshalPKCS1PrivateKey` starts with `-----BEGIN RSA PRIVATE KEY-----` instead of `-----BEGIN PRIVATE KEY-----`. Otherwise, it will not be parsed by most tools (like OpenSSL, [jwt.io](https://jwt.io/), etc.) because it does not conform to the specification.
2022-11-01 22:19:38 +08:00
xAmast
25ee4226d3 feat: clear the session of a signin but non-existent user (#1246) 2022-10-29 20:18:02 +08:00
Bingchang Chen
9d5b019243 fix: nil error if init data is empty (#1247) 2022-10-29 20:04:43 +08:00
Mr Forest
6bb7b545b4 feat: restrict DingTalk user log in who is under the DingTalk Org(which ClientId belong) (#1241)
* feat: fix bug in GetAcceptLanguage()

* feat: add appName when logging in with DingTalk

* fix review problems

* format code

* delete useless printf

* modify display name

Co-authored-by: Gucheng Wang <nomeguy@qq.com>
2022-10-28 22:14:05 +08:00
wenxuan70
25d56ee8d5 feat: allow captcha to be enabled when logging in (#1211)
* Fix bug in GetAcceptLanguage()

* feat: allow captcha to be enabled when logging in

* feat: when the login password is wrong, enable captcha

* feat: Restrict captcha from frontend

* fix: modify CaptchaModal component

* fix: modify the words of i18n

* Update data.json

Co-authored-by: Gucheng Wang <nomeguy@qq.com>
Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-10-28 13:38:14 +08:00
Chell
7e5952c804 fix: login / signin frontend router (#1244)
* fix: go to link

* fix: remove gotologin

* fix: redirect to login page

* fix: redirect to login page

* remove comments

* fix: formats

* fix: formats

* Update Setting.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-10-28 02:23:57 +08:00
Yaodong Yu
80bf29d79a feat: fix showing wrong error message: "Please sign in first" (#1245) 2022-10-27 23:50:45 +08:00
Yaodong Yu
971e53dfd8 fix: fix duplicated user bug in user list page (#1243)
* fix: user list repititon errer

* Update UserListPage.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-10-27 22:51:05 +08:00
Bingchang Chen
654b903d7a feat: fix multi-platform docker image (#1242) 2022-10-26 23:31:00 +08:00
jakiuncle
2f72e6971b fix: make the app list in homepage have the same height (#1239)
* fix: make the app list in homepage have the same height

* fix: make the app list in homepage have the same height

* Update SingleCard.js

Co-authored-by: hsluoyz <hsluoyz@qq.com>
2022-10-25 19:27:24 +08:00
Mr Forest
d4b587b93e feat: fix bug in GetAcceptLanguage() (#1237)
Co-authored-by: Gucheng Wang <nomeguy@qq.com>
2022-10-25 10:50:10 +08:00
Gucheng Wang
ac7a510949 Fix go.mod 2022-10-23 16:14:49 +08:00
Mr Forest
d86f3c88c7 feat: support i18n in backend err messages (#1232)
* feat: support i18n in backend err messages

* use gofumpt to fmt code

* fix review problems

* support auto generate err message

* delete beego/i18n moudle

* fix Github action test problems

* fix review problems

* use gofumpt to format code

* use gofumpt to fmt code
2022-10-23 15:16:24 +08:00
Gucheng Wang
7c77519069 Fix formPosition typo 2022-10-23 02:26:50 +08:00
Gucheng Wang
2bdf467e3a Update formCss default value 2022-10-23 01:27:01 +08:00
Gucheng Wang
52b692c8ad Refactor to renderLink() 2022-10-22 23:48:59 +08:00
Chell
304643736b fix: forget password and sign up router (#1227)
* fix: forget password and sign up router

* fix: link

* fix: jump logic

* fix: signup link

* fix: signup link

* fix: login and signup router

* remove comments

* fix: normal router

* fix: link abstraction

* rename jump component

* fix: session storage

* fix: store signin url

* fix: jumplink props

* fix: simplify link

* fix: path join

* fix: remove unused functions
2022-10-22 23:17:50 +08:00
Yaodong Yu
b0f572c51a feat: add left-side image and improve login page (#1226) 2022-10-22 21:43:41 +08:00
cofecatt
19d351d157 feat: allow non-ASCII characters in username (#1235) 2022-10-22 20:46:50 +08:00
Bingchang Chen
d0751bf2fa feat: add arm docker (#1236) 2022-10-22 11:08:29 +08:00
Bingchang Chen
290cc60f00 feat: non root user for casdoor image (#1234)
Signed-off-by: abingcbc <abingcbc626@gmail.com>

Signed-off-by: abingcbc <abingcbc626@gmail.com>
2022-10-21 17:19:58 +08:00
Yaodong Yu
6a1ec51978 feat: fix SSRF when download avatar (#1193) 2022-10-20 14:47:08 +08:00
chao
dffa68cbce feat: fix SAML login error bug (#1228)
* Update LoginPage.js

* fix saml login error
2022-10-20 01:14:38 +08:00
Gucheng Wang
fad209a7a3 Don't check username in UpdateUser() API 2022-10-19 22:50:19 +08:00
Gucheng Wang
8b222ce2e3 Use Steam ID as username 2022-10-18 22:07:20 +08:00
YunShu
c5293f428d fix: delete this accidentally added files (#1229)
* fix: delete this accidentally added files

* fix: ignore build result

* fix: remove unnecessary asterisk
2022-10-18 21:55:34 +08:00
Gucheng
146aec9ee8 feat: skip username restriction for new users coming from OAuth providers. (#1225) 2022-10-17 18:01:01 +08:00
Mr Forest
50a52de856 feat: support database version control (#1221)
* feat: support Database version control

* Update adapter.go

* fix review problems

* Update adapter.go

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2022-10-15 17:20:20 +08:00
Chell
8f7a8d7d4f fix: translation without reloading (#1215)
* fix: translation without reloading

* fix: language switch
2022-10-12 19:52:02 +08:00
cofecatt
23f3fe1e3c feat: update code format (#1214)
* feat: doc

* feat: doc

* Update model.go

Co-authored-by: Gucheng <85475922+nomeguy@users.noreply.github.com>
2022-10-12 11:42:14 +08:00
cofecatt
59ff5e02ab fix: Add support for including underscores for username (#1210)
* fix: Add support for including underscores for username

* Update check.go

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2022-10-11 19:39:19 +08:00
xxrl
8d41508d6b fix: center loading in account page (#1209)
* fix: center loading in account page

* Update UserEditPage.js

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2022-10-11 00:52:08 +08:00
Gucheng Wang
04f70cf012 Improve renderRightDropdown() 2022-10-10 22:53:47 +08:00
Chell
83724c73f9 feat: fix pad and mobile views (#1202)
* fix figure width

* fix: pad resolution menu

* feat: drawer style mobile menu

* fix: menu button i18n
2022-10-10 22:37:25 +08:00
Gucheng Wang
33e419e133 Show more items to org admin 2022-10-10 21:58:17 +08:00
Gucheng Wang
b832c304ae Can get owner in getObject() 2022-10-10 20:56:55 +08:00
cofecatt
4c7f6fda37 fix: Add restriction to username when signing up (#1203) 2022-10-10 19:58:02 +08:00
Mr Forest
e4a54fe375 fix: disable roles inputbox when model doesn't support RBAC (#1201)
* feat:Support simple ldap server

* fix:fix review problems

* fix:fix review problems

* fix: fix ldapserver crash bug

* Update ldapserver.go

* fix: fix dulpicate go routines

* fix gofumpt problems

* fix: fix UserList error

* feat:disable 'sub role' when model is incorrect

* feat:disable 'sub role' when model is incorrect

* feat:disable 'sub role' when model is incorrect

* delete useless output

* update func name

* Update PermissionEditPage.js

* Update PermissionEditPage.js

Co-authored-by: Yang Luo <hsluoyz@qq.com>
2022-10-10 00:53:55 +08:00
Gucheng Wang
87da3dad76 Remove useless file 2022-10-09 22:18:38 +08:00
Gucheng Wang
44ad88353f Add error to GetDefaultApplication() 2022-10-09 10:39:33 +08:00
Mr Forest
a955fb57d6 feat: fix UserList error (#1194)
* feat:Support simple ldap server

* fix:fix review problems

* fix:fix review problems

* fix: fix ldapserver crash bug

* Update ldapserver.go

* fix: fix dulpicate go routines

* fix gofumpt problems

* fix: fix UserList error
2022-10-08 20:00:45 +08:00
Gucheng
d2960ad66b Fix README typo 2022-10-08 16:00:08 +08:00
YunShu
5243aabf43 docs: Create SECURITY.md (#1192) 2022-10-07 19:02:35 +08:00
Gucheng Wang
d3a2c2a66e Improve org admin permissions 2022-10-07 16:27:21 +08:00
Gucheng Wang
0a9058a585 Improve user list page 2022-10-07 15:43:50 +08:00
Gucheng
225719810b Update link typo in README 2022-10-06 19:37:00 +08:00
kcfuler
c634d4a891 feat: add some css style for the custom Provider button (#1185)
* fix: add some css style for the custom button

* fix: refactor previous code

* fix: add i18 adaptation

* fix: modifiy the saml codition
2022-10-06 19:28:02 +08:00
Yaodong Yu
3dc01ec85d fix: language widget poisition without border css (#1188) 2022-10-06 17:26:12 +08:00
Gucheng Wang
a7324f1da1 Improve className 2022-10-03 22:45:36 +08:00
Yaodong Yu
6da452d7e0 feat: show language widget in signup and signin pages (#1180) 2022-10-03 22:40:19 +08:00
Gucheng Wang
5abcf913e6 Fix language menu 2022-10-03 22:39:10 +08:00
Gucheng Wang
58455e688e Improve WebAuthnCredentialTable and border radius 2022-10-03 18:46:40 +08:00
Gucheng Wang
4d6f68eddc Improve footer and color 2022-10-03 17:43:19 +08:00
Gucheng Wang
67f3c5a489 Add verificationCode to login method 2022-10-03 15:41:20 +08:00
Товарищ программист
9c48582e0c feat: fix bugs in webauthn (#1173) 2022-10-01 11:10:55 +08:00
q1anx1
645c631db9 fix: fix the delete file vulnerability issue (#1174) 2022-10-01 00:33:27 +08:00
Gucheng Wang
3128e68df4 Add sendSilentSigninData() 2022-09-30 01:51:58 +08:00
Gucheng Wang
2247c6a883 Add isSelf() in user edit page 2022-09-29 22:24:05 +08:00
Gucheng Wang
04709f731b Update beego to v1.12.11 2022-09-29 19:45:17 +08:00
Yixiang Zhao
ebe1887e8b feat: add saml provider error (#1168)
* fix: add saml provider error

Signed-off-by: Yixiang Zhao <seriouszyx@foxmail.com>

* fix: search

Signed-off-by: Yixiang Zhao <seriouszyx@foxmail.com>

Signed-off-by: Yixiang Zhao <seriouszyx@foxmail.com>
2022-09-28 21:09:39 +08:00
Mr Forest
a7a8805713 feat: fix dulpicate go routines (#1167)
* feat:Support simple ldap server

* fix:fix review problems

* fix:fix review problems

* fix: fix ldapserver crash bug

* Update ldapserver.go

* fix: fix dulpicate go routines

* fix gofumpt problems
2022-09-28 20:28:00 +08:00
WangGuan
ceabbe27b4 feat: remove p_type in table permission_rule (#1165) 2022-09-27 22:50:27 +08:00
Gucheng Wang
7393b90155 Add enableAutoSignin to application 2022-09-27 20:06:46 +08:00
Taoning Ge
0098c05fb3 feat: add support for smsbao sms (#1164) 2022-09-27 08:37:55 +08:00
Mr Forest
34324d9f72 fix: fix ldapserver crash bug (#1161)
* feat:Support simple ldap server

* fix:fix review problems

* fix:fix review problems

* fix: fix ldapserver crash bug

* Update ldapserver.go
2022-09-26 18:27:17 +08:00
Товарищ программист
28b381e01e fix: fix webauthn redirection (#1148) 2022-09-25 21:41:52 +08:00
811 changed files with 154123 additions and 23796 deletions

0
$env
View File

7
.gitattributes vendored
View File

@@ -1,2 +1,5 @@
*.go linguist-detectable=true
*.js linguist-detectable=false
*.go linguist-detectable=true
*.js linguist-detectable=false
# Declare files that will always have LF line endings on checkout.
# Git will always convert line endings to LF on checkout. You should use this for files that must keep LF endings, even on Windows.
*.sh text eol=lf

View File

@@ -0,0 +1,31 @@
name: Build & Push Docker Image
on:
push:
branches:
- custom
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Login to Container Registry
uses: docker/login-action@v3
with:
registry: gromlab.ru
username: ${{ secrets.CR_USER }}
password: ${{ secrets.CR_TOKEN }}
- name: Build and Push
uses: docker/build-push-action@v5
with:
context: .
target: STANDARD
push: true
tags: |
gromlab.ru/gromov/casdoor:latest
gromlab.ru/gromov/casdoor:${{ github.sha }}

View File

@@ -1,26 +1,33 @@
name: Build
on: [push, pull_request]
env:
GO_VERSION: "1.25.8"
on:
push:
branches:
- master
pull_request:
jobs:
go-tests:
name: Running Go tests
runs-on: ubuntu-latest
services:
mysql:
image: mysql:5.7
env:
MYSQL_DATABASE: casdoor
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3306:3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
image: mysql:5.7
env:
MYSQL_DATABASE: casdoor
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3306:3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '^1.16.5'
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ./go.mod
- name: Tests
run: |
go test -v $(go list ./...) -tags skipCi
@@ -29,28 +36,33 @@ jobs:
frontend:
name: Front-end
runs-on: ubuntu-latest
needs: [ go-tests ]
needs: [go-tests]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
# cache
- uses: c-hive/gha-yarn-cache@v2
with:
directory: ./web
node-version: 20
cache: "yarn"
cache-dependency-path: ./web/yarn.lock
- run: yarn install && CI=false yarn run build
working-directory: ./web
- name: Upload build artifacts
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push'
uses: actions/upload-artifact@v4
with:
name: frontend-build-${{ github.run_id }}
path: ./web/build
backend:
name: Back-end
runs-on: ubuntu-latest
needs: [ go-tests ]
needs: [go-tests]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: '^1.16.5'
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ./go.mod
- run: go version
- name: Build
run: |
@@ -60,55 +72,183 @@ jobs:
linter:
name: Go-Linter
runs-on: ubuntu-latest
needs: [ go-tests ]
needs: [go-tests]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
- uses: actions/setup-go@v4
with:
go-version: '^1.16.5'
go-version: ${{ env.GO_VERSION }}
cache: false
# gen a dummy config file
- run: touch dummy.yml
- name: Sync vendor tree
run: go mod vendor
# CI and local `make lint` both use the repo's gofumpt-only golangci-lint config.
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
uses: golangci/golangci-lint-action@v9.2.0
with:
version: latest
args: --disable-all -c dummy.yml -E=gofumpt --max-same-issues=0 --timeout 5m --modules-download-mode=mod
version: v2.11.4
args: --config .golangci.yml ./...
release-and-push:
name: Release And Push
e2e:
name: e2e-test
runs-on: ubuntu-latest
needs: [go-tests]
services:
mysql:
image: mysql:5.7
env:
MYSQL_DATABASE: casdoor
MYSQL_ROOT_PASSWORD: 123456
ports:
- 3306:3306
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ./go.mod
- name: start backend
run: nohup go run ./main.go > /tmp/backend.log 2>&1 &
working-directory: ./
- name: Wait for backend to be ready
run: |
echo "Waiting for backend server to start on port 8000..."
for i in {1..60}; do
if curl -s http://localhost:8000 > /dev/null 2>&1; then
echo "Backend is ready!"
break
fi
if [ $i -eq 60 ]; then
echo "Backend failed to start within 60 seconds"
echo "Backend logs:"
cat /tmp/backend.log || echo "No backend logs available"
exit 1
fi
echo "Waiting... ($i/60)"
sleep 1
done
- uses: actions/setup-node@v3
with:
node-version: 20
cache: "yarn"
cache-dependency-path: ./web/yarn.lock
- run: yarn install
working-directory: ./web
- uses: cypress-io/github-action@v5
with:
browser: chrome
start: yarn start
wait-on: "http://localhost:7001"
wait-on-timeout: 210
working-directory: ./web
- uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-screenshots
path: ./web/cypress/screenshots
- uses: actions/upload-artifact@v4
if: always()
with:
name: cypress-videos
path: ./web/cypress/videos
tag-release:
name: Create Tag
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push'
needs: [ frontend, backend, linter ]
needs: [frontend, backend, linter, e2e]
outputs:
new-release-published: ${{ steps.semantic.outputs.new_release_published }}
new-release-version: ${{ steps.semantic.outputs.new_release_version }}
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Create Tag with Semantic Release
id: semantic
uses: cycjimmy/semantic-release-action@v4
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
github-release:
name: GitHub Release
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' && needs.tag-release.outputs.new-release-published == 'true'
needs: [tag-release]
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v2
- uses: actions/setup-go@v4
with:
node-version: 16
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ./go.mod
- name: Free disk space
uses: jlumbroso/free-disk-space@v1.3.1
with:
tool-cache: false
android: true
dotnet: true
haskell: true
large-packages: true
swap-storage: true
- name: Download frontend build artifacts
uses: actions/download-artifact@v4
with:
name: frontend-build-${{ github.run_id }}
path: ./web/build
- name: Prepare Go caches
run: |
echo "GOMODCACHE=$RUNNER_TEMP/gomod" >> $GITHUB_ENV
echo "GOCACHE=$RUNNER_TEMP/gocache" >> $GITHUB_ENV
go clean -cache -modcache -testcache -fuzzcache
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: "~> v2"
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
docker-release:
name: Docker Release
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' && needs.tag-release.outputs.new-release-published == 'true'
needs: [tag-release]
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: -1
- name: Fetch Previous version
id: get-previous-tag
uses: actions-ecosystem/action-get-latest-tag@v1.6.0
- name: Release
run: yarn global add semantic-release@17.4.4 && semantic-release
env:
GH_TOKEN: ${{ secrets.GH_BOT_TOKEN }}
- name: Fetch Current version
id: get-current-tag
uses: actions-ecosystem/action-get-latest-tag@v1.6.0
- name: Decide Should_Push Or Not
id: should_push
run: |
old_version=${{steps.get-previous-tag.outputs.tag}}
new_version=${{steps.get-current-tag.outputs.tag }}
new_version=${{ needs.tag-release.outputs.new-release-version }}
old_array=(${old_version//\./ })
new_array=(${new_version//\./ })
@@ -119,32 +259,72 @@ jobs:
elif [ ${old_array[1]} != ${new_array[1]} ]
then
echo ::set-output name=push::'true'
else
echo ::set-output name=push::'false'
fi
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up buildx
id: buildx
uses: docker/setup-buildx-action@v2
with:
version: latest
- name: Log in to Docker Hub
uses: docker/login-action@v1
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' &&steps.should_push.outputs.push=='true'
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' && steps.should_push.outputs.push=='true'
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Push to Docker Hub
uses: docker/build-push-action@v2
uses: docker/build-push-action@v3
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' && steps.should_push.outputs.push=='true'
with:
context: .
target: STANDARD
platforms: linux/amd64,linux/arm64
push: true
tags: casbin/casdoor:${{steps.get-current-tag.outputs.tag }},casbin/casdoor:latest
tags: casbin/casdoor:${{ needs.tag-release.outputs.new-release-version }},casbin/casdoor:latest
- name: Push All In One Version to Docker Hub
uses: docker/build-push-action@v2
uses: docker/build-push-action@v3
if: github.repository == 'casdoor/casdoor' && github.event_name == 'push' && steps.should_push.outputs.push=='true'
with:
context: .
target: ALLINONE
platforms: linux/amd64,linux/arm64
push: true
tags: casbin/casdoor-all-in-one:${{steps.get-current-tag.outputs.tag }},casbin/casdoor-all-in-one:latest
tags: casbin/casdoor-all-in-one:${{ needs.tag-release.outputs.new-release-version }},casbin/casdoor-all-in-one:latest
- uses: actions/checkout@v3
if: steps.should_push.outputs.push=='true'
with:
repository: casdoor/casdoor-helm
ref: "master"
token: ${{ secrets.GH_BOT_TOKEN }}
- name: Update Helm Chart
if: steps.should_push.outputs.push=='true'
run: |
# Set the appVersion and version of the chart to the current tag
sed -i "s/appVersion: .*/appVersion: ${{ needs.tag-release.outputs.new-release-version }}/g" ./charts/casdoor/Chart.yaml
sed -i "s/version: .*/version: ${{ needs.tag-release.outputs.new-release-version }}/g" ./charts/casdoor/Chart.yaml
REGISTRY=oci://registry-1.docker.io/casbin
cd charts/casdoor
helm package .
PKG_NAME=$(ls *.tgz)
helm repo index . --url $REGISTRY --merge index.yaml
helm push $PKG_NAME $REGISTRY
rm $PKG_NAME
# Commit and push the changes back to the repository
git config --global user.name "casbin-bot"
git config --global user.email "bot@casbin.org"
git add Chart.yaml index.yaml
git commit -m "chore(helm): bump helm charts appVersion to ${{ needs.tag-release.outputs.new-release-version }}"
git tag ${{ needs.tag-release.outputs.new-release-version }}
git push origin HEAD:master --follow-tags

View File

@@ -33,3 +33,24 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CROWDIN_PROJECT_ID: '463556'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
- name: crowdin backend action
uses: crowdin/github-action@1.4.8
with:
upload_translations: true
download_translations: true
push_translations: true
commit_message: 'refactor: New Crowdin Backend translations by Github Action'
localization_branch_name: l10n_crowdin_action
create_pull_request: true
pull_request_title: 'refactor: New Crowdin Backend translations'
crowdin_branch_name: l10n_branch
config: './crowdin.yml'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CROWDIN_PROJECT_ID: '463556'
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}

11
.gitignore vendored
View File

@@ -5,6 +5,7 @@
*.so
*.dylib
*.swp
server_*
# Test binary, built with `go test -c`
*.test
@@ -18,7 +19,8 @@ bin/
.idea/
*.iml
.vscode/
.vscode/settings.json
.claude
tmp/
tmpFiles/
@@ -27,3 +29,10 @@ logs/
files/
lastupdate.tmp
commentsRouter*.go
# ignore build result
casdoor
server
# include helm-chart
!manifests/casdoor

View File

@@ -1,42 +1,26 @@
linters:
disable-all: true
enable:
- deadcode
- dupl
- errcheck
- goconst
- gocyclo
- gofmt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- prealloc
- staticcheck
- structcheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- revive
- exportloopref
version: "2"
run:
deadline: 5m
skip-dirs:
- api
# skip-files:
# - ".*_test\\.go$"
modules-download-mode: mod
# all available settings of specific linters
linters-settings:
lll:
# max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 150
# tab width in spaces. Default to 1.
tab-width: 1
relative-path-mode: gomod
modules-download-mode: vendor
linters:
default: none
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofumpt
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$

55
.goreleaser.yaml Normal file
View File

@@ -0,0 +1,55 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
#- go generate ./...
- go test -v -run TestGetVersionInfo ./util/system_test.go ./util/system.go ./util/variable.go
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm64
archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip
files:
- src: 'web/build'
dst: './web/build'
- src: 'conf/app.conf'
dst: './conf/app.conf'
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"

15
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}",
"cwd": "${workspaceFolder}",
"debugAdapter": "dlv-dap",
"args": ["--createDatabase=true"]
}
]
}

View File

@@ -1,47 +1,66 @@
FROM node:16.13.0 AS FRONT
FROM --platform=$BUILDPLATFORM node:20.20.1 AS FRONT
WORKDIR /web
# Copy only dependency files first for better caching
COPY ./web/package.json ./web/yarn.lock ./
RUN yarn install --frozen-lockfile --network-timeout 1000000
# Copy source files and build
COPY ./web .
RUN yarn config set registry https://registry.npmmirror.com
RUN yarn install && yarn run build
RUN NODE_OPTIONS="--max-old-space-size=4096" yarn run build
FROM golang:1.17.5 AS BACK
FROM --platform=$BUILDPLATFORM golang:1.25.8 AS BACK
WORKDIR /go/src/casdoor
COPY . .
RUN ./build.sh
# Copy only go.mod and go.sum first for dependency caching
COPY go.mod go.sum ./
RUN go mod download
# Copy source files
COPY . .
RUN ./build.sh
FROM alpine:latest AS STANDARD
LABEL MAINTAINER="https://casdoor.org/"
ARG USER=casdoor
ARG TARGETOS
ARG TARGETARCH
ENV BUILDX_ARCH="${TARGETOS:-linux}_${TARGETARCH:-amd64}"
RUN sed -i 's/https/http/' /etc/apk/repositories
RUN apk add --update sudo
RUN apk add tzdata
RUN apk add curl
RUN apk add ca-certificates && update-ca-certificates
RUN adduser -D $USER -u 1000 \
&& echo "$USER ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/$USER \
&& chmod 0440 /etc/sudoers.d/$USER \
&& mkdir logs \
&& chown -R $USER:$USER logs
USER 1000
WORKDIR /
COPY --from=BACK /go/src/casdoor/server ./server
COPY --from=BACK /go/src/casdoor/swagger ./swagger
COPY --from=BACK /go/src/casdoor/conf/app.conf ./conf/app.conf
COPY --from=FRONT /web/build ./web/build
COPY --from=BACK --chown=$USER:$USER /go/src/casdoor/server_${BUILDX_ARCH} ./server
COPY --from=BACK --chown=$USER:$USER /go/src/casdoor/swagger ./swagger
COPY --from=BACK --chown=$USER:$USER /go/src/casdoor/conf/app.conf ./conf/app.conf
COPY --from=FRONT --chown=$USER:$USER /web/build ./web/build
ENTRYPOINT ["/server"]
FROM debian:latest AS db
RUN apt update \
&& apt install -y \
mariadb-server \
mariadb-client \
&& rm -rf /var/lib/apt/lists/*
FROM db AS ALLINONE
FROM debian:latest AS ALLINONE
LABEL MAINTAINER="https://casdoor.org/"
ARG TARGETOS
ARG TARGETARCH
ENV BUILDX_ARCH="${TARGETOS:-linux}_${TARGETARCH:-amd64}"
RUN apt update
RUN apt install -y ca-certificates && update-ca-certificates
RUN apt install -y ca-certificates lsof && update-ca-certificates
WORKDIR /
COPY --from=BACK /go/src/casdoor/server ./server
COPY --from=BACK /go/src/casdoor/server_${BUILDX_ARCH} ./server
COPY --from=BACK /go/src/casdoor/swagger ./swagger
COPY --from=BACK /go/src/casdoor/docker-entrypoint.sh /docker-entrypoint.sh
COPY --from=BACK /go/src/casdoor/conf/app.conf ./conf/app.conf

View File

@@ -86,13 +86,16 @@ docker-build: ## Build docker image with the manager.
docker-push: ## Push docker image with the manager.
docker push ${REGISTRY}/${IMG}:${IMG_TAG}
lint-install: ## Install golangci-lint
@# The following installs a specific version of golangci-lint, which is appropriate for a CI server to avoid different results from build to build
go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.40.1
deps: ## Run dependencies for local development
docker compose up -d db
lint: ## Run golangci-lint
lint-install: ## Install golangci-lint
@# Keep the local golangci-lint version aligned with CI. Both local and CI lint run the gofumpt-only ruleset from .golangci.yml.
GOTOOLCHAIN=go1.25.8 go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.4
lint: vendor ## Run golangci-lint
@echo "---lint---"
golangci-lint run --modules-download-mode=vendor ./...
golangci-lint run ./...
##@ Deployment

178
README.md
View File

@@ -1,90 +1,88 @@
<h1 align="center" style="border-bottom: none;">📦⚡️ Casdoor</h1>
<h3 align="center">A UI-first centralized authentication / Single-Sign-On (SSO) platform based on OAuth 2.0 / OIDC.</h3>
<p align="center">
<a href="#badge">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
</a>
<a href="https://hub.docker.com/r/casbin/casdoor">
<img alt="docker pull casbin/casdoor" src="https://img.shields.io/docker/pulls/casbin/casdoor.svg">
</a>
<a href="https://github.com/casdoor/casdoor/actions/workflows/build.yml">
<img alt="GitHub Workflow Status (branch)" src="https://github.com/casdoor/casdoor/workflows/Build/badge.svg?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/releases/latest">
<img alt="GitHub Release" src="https://img.shields.io/github/v/release/casbin/casdoor.svg">
</a>
<a href="https://hub.docker.com/repository/docker/casbin/casdoor">
<img alt="Docker Image Version (latest semver)" src="https://img.shields.io/badge/Docker%20Hub-latest-brightgreen">
</a>
</p>
<p align="center">
<a href="https://goreportcard.com/report/github.com/casdoor/casdoor">
<img alt="Go Report Card" src="https://goreportcard.com/badge/github.com/casdoor/casdoor?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/casbin/casdoor?style=flat-square" alt="license">
</a>
<a href="https://github.com/casdoor/casdoor/issues">
<img alt="GitHub issues" src="https://img.shields.io/github/issues/casbin/casdoor?style=flat-square">
</a>
<a href="#">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/casbin/casdoor?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/network">
<img alt="GitHub forks" src="https://img.shields.io/github/forks/casbin/casdoor?style=flat-square">
</a>
<a href="https://crowdin.com/project/casdoor-site">
<img alt="Crowdin" src="https://badges.crowdin.net/casdoor-site/localized.svg">
</a>
<a href="https://gitter.im/casbin/casdoor">
<img alt="Gitter" src="https://badges.gitter.im/casbin/casdoor.svg">
</a>
</p>
## Online demo
- International: https://door.casdoor.org (read-only)
- Asian mirror: https://door.casdoor.com (read-only)
- Asian mirror: https://demo.casdoor.com (read-write, will restore for every 5 minutes)
## Documentation
- International: https://casdoor.org
- Asian mirror: https://docs.casdoor.cn
## Install
- By source code: https://casdoor.org/docs/basic/server-installation
- By Docker: https://casdoor.org/docs/basic/try-with-docker
## How to connect to Casdoor?
https://casdoor.org/docs/how-to-connect/overview
## Casdoor Public API
- Docs: https://casdoor.org/docs/basic/public-api
- Swagger: https://door.casdoor.com/swagger
## Integrations
https://casdoor.org/docs/integration/apisix
## How to contact?
- Gitter: https://gitter.im/casbin/casdoor
- Forum: https://forum.casbin.com
- Contact: https://tawk.to/chat/623352fea34c2456412b8c51/1fuc7od6e
## Contribute
For casdoor, if you have any questions, you can give Issues, or you can also directly start Pull Requests(but we recommend giving issues first to communicate with the community).
### I18n translation
If you are contributing to casdoor, please note that we use [Crowdin](https://crowdin.com/project/casdoor-site) as translating platform and i18next as translating tool. When you add some words using i18next in the `web/` directory, please remember to add what you have added to the `web/src/locales/en/data.json` file.
## License
[Apache-2.0](https://github.com/casdoor/casdoor/blob/master/LICENSE)
<h1 align="center" style="border-bottom: none;">📦⚡️ Casdoor</h1>
<h3 align="center">An open-source AI-first Identity and Access Management (IAM) /AI MCP gateway and auth server with web UI supporting MCP, A2A, OAuth 2.1, OIDC, SAML, CAS, LDAP, SCIM, WebAuthn, TOTP, MFA, Face ID, Google Workspace, Azure AD</h3>
<p align="center">
<a href="#badge">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
</a>
<a href="https://hub.docker.com/r/casbin/casdoor">
<img alt="docker pull casbin/casdoor" src="https://img.shields.io/docker/pulls/casbin/casdoor.svg">
</a>
<a href="https://github.com/casdoor/casdoor/actions/workflows/build.yml">
<img alt="GitHub Workflow Status (branch)" src="https://github.com/casdoor/casdoor/workflows/Build/badge.svg?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/releases/latest">
<img alt="GitHub Release" src="https://img.shields.io/github/v/release/casdoor/casdoor.svg">
</a>
<a href="https://hub.docker.com/r/casbin/casdoor">
<img alt="Docker Image Version (latest semver)" src="https://img.shields.io/badge/Docker%20Hub-latest-brightgreen">
</a>
</p>
<p align="center">
<a href="https://goreportcard.com/report/github.com/casdoor/casdoor">
<img alt="Go Report Card" src="https://goreportcard.com/badge/github.com/casdoor/casdoor?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/casdoor/casdoor?style=flat-square" alt="license">
</a>
<a href="https://github.com/casdoor/casdoor/issues">
<img alt="GitHub issues" src="https://img.shields.io/github/issues/casdoor/casdoor?style=flat-square">
</a>
<a href="#">
<img alt="GitHub stars" src="https://img.shields.io/github/stars/casdoor/casdoor?style=flat-square">
</a>
<a href="https://github.com/casdoor/casdoor/network">
<img alt="GitHub forks" src="https://img.shields.io/github/forks/casdoor/casdoor?style=flat-square">
</a>
<a href="https://crowdin.com/project/casdoor-site">
<img alt="Crowdin" src="https://badges.crowdin.net/casdoor-site/localized.svg">
</a>
<a href="https://discord.gg/5rPsrAzK7S">
<img alt="Discord" src="https://img.shields.io/discord/1022748306096537660?style=flat-square&logo=discord&label=discord&color=5865F2">
</a>
</p>
## Online demo
- Read-only site: https://door.casdoor.com (any modification operation will fail)
- Writable site: https://demo.casdoor.com (original data will be restored for every 5 minutes)
## Documentation
https://casdoor.org
## Install
- By source code: https://casdoor.org/docs/basic/server-installation
- By Docker: https://casdoor.org/docs/basic/try-with-docker
- By Kubernetes Helm: https://casdoor.org/docs/basic/try-with-helm
## How to connect to Casdoor?
https://casdoor.org/docs/how-to-connect/overview
## Casdoor Public API
- Docs: https://casdoor.org/docs/basic/public-api
- Swagger: https://door.casdoor.com/swagger
## Integrations
https://casdoor.org/docs/category/integrations
## How to contact?
- Discord: https://discord.gg/5rPsrAzK7S
- Contact: https://casdoor.org/help
## Contribute
For casdoor, if you have any questions, you can give Issues, or you can also directly start Pull Requests(but we recommend giving issues first to communicate with the community).
### I18n translation
If you are contributing to casdoor, please note that we use [Crowdin](https://crowdin.com/project/casdoor-site) as translating platform and i18next as translating tool. When you add some words using i18next in the `web/` directory, please remember to add what you have added to the `web/src/locales/en/data.json` file.
## License
[Apache-2.0](https://github.com/casdoor/casdoor/blob/master/LICENSE)

9
SECURITY.md Normal file
View File

@@ -0,0 +1,9 @@
# Security Policy
## Reporting a Vulnerability
We are grateful for security researchers and users reporting a vulnerability to us first. To ensure that your request is handled in a timely manner and we can keep users safe, please follow the below guidelines.
- **Please do not report security vulnerabilities directly on GitHub.**
- To report a vulnerability, please email [admin@casdoor.org](admin@casdoor.org).

View File

@@ -18,56 +18,21 @@ import (
"strings"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
xormadapter "github.com/casbin/xorm-adapter/v2"
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
stringadapter "github.com/qiangmzsx/string-adapter/v2"
)
var Enforcer *casbin.Enforcer
func InitAuthz() {
var err error
tableNamePrefix := conf.GetConfigString("tableNamePrefix")
a, err := xormadapter.NewAdapterWithTableName(conf.GetConfigString("driverName"), conf.GetConfigDataSourceName()+conf.GetConfigString("dbName"), "casbin_rule", tableNamePrefix, true)
if err != nil {
panic(err)
}
modelText := `
[request_definition]
r = subOwner, subName, method, urlPath, objOwner, objName
[policy_definition]
p = subOwner, subName, method, urlPath, objOwner, objName
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = (r.subOwner == p.subOwner || p.subOwner == "*") && \
(r.subName == p.subName || p.subName == "*" || r.subName != "anonymous" && p.subName == "!anonymous") && \
(r.method == p.method || p.method == "*") && \
(r.urlPath == p.urlPath || p.urlPath == "*") && \
(r.objOwner == p.objOwner || p.objOwner == "*") && \
(r.objName == p.objName || p.objName == "*") || \
(r.subOwner == r.objOwner && r.subName == r.objName)
`
m, err := model.NewModelFromString(modelText)
if err != nil {
panic(err)
}
Enforcer, err = casbin.NewEnforcer(m, a)
func InitApi() {
e, err := object.GetInitializedEnforcer(util.GetId("built-in", "api-enforcer-built-in"))
if err != nil {
panic(err)
}
Enforcer = e.Enforcer
Enforcer.ClearPolicy()
// if len(Enforcer.GetPolicy()) == 0 {
@@ -76,47 +41,97 @@ m = (r.subOwner == p.subOwner || p.subOwner == "*") && \
p, built-in, *, *, *, *, *
p, app, *, *, *, *, *
p, *, *, POST, /api/signup, *, *
p, *, *, POST, /api/get-email-and-phone, *, *
p, *, *, GET, /api/get-email-and-phone, *, *
p, *, *, POST, /api/login, *, *
p, *, *, GET, /api/get-app-login, *, *
p, *, *, POST, /api/logout, *, *
p, *, *, GET, /api/logout, *, *
p, *, *, POST, /api/sso-logout, *, *
p, *, *, GET, /api/sso-logout, *, *
p, *, *, POST, /api/callback, *, *
p, *, *, POST, /api/device-auth, *, *
p, *, *, GET, /api/get-account, *, *
p, *, *, GET, /api/userinfo, *, *
p, *, *, GET, /api/user, *, *
p, *, *, GET, /api/health, *, *
p, *, *, *, /api/webhook, *, *
p, *, *, GET, /api/get-qrcode, *, *
p, *, *, GET, /api/get-webhook-event, *, *
p, *, *, GET, /api/get-captcha-status, *, *
p, *, *, *, /api/login/oauth, *, *
p, *, *, POST, /api/oauth/register, *, *
p, *, *, GET, /api/get-application, *, *
p, *, *, GET, /api/get-organization-applications, *, *
p, *, *, GET, /api/get-user, *, *
p, *, *, GET, /api/get-user-application, *, *
p, *, *, POST, /api/upload-users, *, *
p, *, *, GET, /api/get-resources, *, *
p, *, *, GET, /api/get-records, *, *
p, *, *, GET, /api/get-product, *, *
p, *, *, GET, /api/get-products, *, *
p, *, *, POST, /api/buy-product, *, *
p, *, *, GET, /api/get-order, *, *
p, *, *, GET, /api/get-orders, *, *
p, *, *, GET, /api/get-user-orders, *, *
p, *, *, GET, /api/get-payment, *, *
p, *, *, POST, /api/update-payment, *, *
p, *, *, POST, /api/invoice-payment, *, *
p, *, *, POST, /api/notify-payment, *, *
p, *, *, POST, /api/place-order, *, *
p, *, *, POST, /api/cancel-order, *, *
p, *, *, POST, /api/pay-order, *, *
p, *, *, POST, /api/unlink, *, *
p, *, *, POST, /api/set-password, *, *
p, *, *, POST, /api/send-verification-code, *, *
p, *, *, GET, /api/get-captcha, *, *
p, *, *, POST, /api/verify-captcha, *, *
p, *, *, POST, /api/verify-code, *, *
p, *, *, POST, /api/v1/traces, *, *
p, *, *, POST, /api/v1/metrics, *, *
p, *, *, POST, /api/v1/logs, *, *
p, *, *, POST, /api/reset-email-or-phone, *, *
p, *, *, POST, /api/upload-resource, *, *
p, *, *, GET, /.well-known/openid-configuration, *, *
p, *, *, GET, /.well-known/oauth-authorization-server, *, *
p, *, *, GET, /.well-known/oauth-protected-resource, *, *
p, *, *, GET, /.well-known/webfinger, *, *
p, *, *, *, /.well-known/jwks, *, *
p, *, *, GET, /.well-known/:application/openid-configuration, *, *
p, *, *, GET, /.well-known/:application/oauth-authorization-server, *, *
p, *, *, GET, /.well-known/:application/oauth-protected-resource, *, *
p, *, *, GET, /.well-known/:application/webfinger, *, *
p, *, *, *, /.well-known/:application/jwks, *, *
p, *, *, GET, /api/get-saml-login, *, *
p, *, *, POST, /api/acs, *, *
p, *, *, GET, /api/saml/metadata, *, *
p, *, *, *, /api/saml/redirect, *, *
p, *, *, *, /cas, *, *
p, *, *, *, /scim, *, *
p, *, *, *, /api/webauthn, *, *
p, *, *, GET, /api/get-release, *, *
p, *, *, GET, /api/get-default-application, *, *
p, *, *, GET, /api/get-prometheus-info, *, *
p, *, *, *, /api/metrics, *, *
p, *, *, GET, /api/get-pricing, *, *
p, *, *, GET, /api/get-plan, *, *
p, *, *, GET, /api/get-subscription, *, *
p, *, *, GET, /api/get-transactions, *, *
p, *, *, GET, /api/get-transaction, *, *
p, *, *, GET, /api/get-provider, *, *
p, *, *, GET, /api/get-organization-names, *, *
p, *, *, GET, /api/get-all-objects, *, *
p, *, *, GET, /api/get-all-actions, *, *
p, *, *, GET, /api/get-all-roles, *, *
p, *, *, GET, /api/run-casbin-command, *, *
p, *, *, POST, /api/refresh-engines, *, *
p, *, *, GET, /api/get-invitation-info, *, *
p, *, *, GET, /api/faceid-signin-begin, *, *
p, *, *, GET, /api/kerberos-login, *, *
`
sa := stringadapter.NewAdapter(ruleText)
// load all rules from string adapter to enforcer's memory
err := sa.LoadPolicy(Enforcer.GetModel())
err = sa.LoadPolicy(Enforcer.GetModel())
if err != nil {
panic(err)
}
@@ -131,28 +146,71 @@ p, *, *, GET, /api/get-default-application, *, *
}
}
func IsAllowed(subOwner string, subName string, method string, urlPath string, objOwner string, objName string) bool {
func IsAllowed(subOwner string, subName string, method string, urlPath string, objOwner string, objName string, extraInfo map[string]interface{}) bool {
if urlPath == "/api/mcp" {
if detailPath, ok := extraInfo["detailPathUrl"].(string); ok {
if detailPath == "initialize" || detailPath == "notifications/initialized" || detailPath == "ping" || detailPath == "tools/list" {
return true
}
}
}
if conf.IsDemoMode() {
if !isAllowedInDemoMode(subOwner, subName, method, urlPath, objOwner, objName) {
return false
}
}
user, err := object.GetUser(util.GetId(subOwner, subName))
if err != nil {
panic(err)
}
if subOwner == "app" {
return true
}
if user != nil {
if user.IsDeleted {
return false
}
if user.IsGlobalAdmin() {
return true
}
if user.IsAdmin && subOwner == objOwner {
return true
}
}
res, err := Enforcer.Enforce(subOwner, subName, method, urlPath, objOwner, objName)
if err != nil {
panic(err)
}
if !res {
res, err = object.CheckApiPermission(util.GetId(subOwner, subName), objOwner, urlPath, method)
if err != nil {
panic(err)
}
}
return res
}
func isAllowedInDemoMode(subOwner string, subName string, method string, urlPath string, objOwner string, objName string) bool {
if method == "POST" {
if strings.HasPrefix(urlPath, "/api/login") || urlPath == "/api/logout" || urlPath == "/api/signup" || urlPath == "/api/send-verification-code" {
if strings.HasPrefix(urlPath, "/api/login") || urlPath == "/api/logout" || urlPath == "/api/sso-logout" || urlPath == "/api/signup" || urlPath == "/api/callback" || urlPath == "/api/send-verification-code" || urlPath == "/api/send-email" || urlPath == "/api/verify-captcha" || urlPath == "/api/verify-code" || urlPath == "/api/check-user-password" || strings.HasPrefix(urlPath, "/api/mfa/") || urlPath == "/api/webhook" || urlPath == "/api/get-qrcode" || urlPath == "/api/refresh-engines" {
return true
} else if urlPath == "/api/update-user" {
// Allow ordinary users to update their own information
if subOwner == objOwner && subName == objName && !(subOwner == "built-in" && subName == "admin") {
if (subOwner == objOwner && subName == objName || subOwner == "app") && !(subOwner == "built-in" && subName == "admin") {
return true
}
return false
} else if urlPath == "/api/upload-resource" || urlPath == "/api/add-transaction" {
if subOwner == "app" && subName == "app-casibase" {
return true
}
return false

View File

@@ -8,4 +8,6 @@ else
echo "Google is blocked, Go proxy is enabled: GOPROXY=https://goproxy.cn,direct"
export GOPROXY="https://goproxy.cn,direct"
fi
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o server .
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o server_linux_amd64 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-w -s" -o server_linux_arm64 .

View File

@@ -15,22 +15,51 @@
package captcha
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/casdoor/casdoor/util"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
openapiutil "github.com/alibabacloud-go/openapi-util/service"
teaUtil "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
const AliyunCaptchaVerifyUrl = "http://afs.aliyuncs.com"
const AliyunCaptchaVerifyUrl = "captcha.cn-shanghai.aliyuncs.com"
type VerifyCaptchaRequest struct {
CaptchaVerifyParam *string `json:"CaptchaVerifyParam,omitempty" xml:"CaptchaVerifyParam,omitempty"`
SceneId *string `json:"SceneId,omitempty" xml:"SceneId,omitempty"`
}
type VerifyCaptchaResponseBodyResult struct {
VerifyResult *bool `json:"VerifyResult,omitempty" xml:"VerifyResult,omitempty"`
}
type VerifyCaptchaResponseBody struct {
Code *string `json:"Code,omitempty" xml:"Code,omitempty"`
Message *string `json:"Message,omitempty" xml:"Message,omitempty"`
// Id of the request
RequestId *string `json:"RequestId,omitempty" xml:"RequestId,omitempty"`
Result *VerifyCaptchaResponseBodyResult `json:"Result,omitempty" xml:"Result,omitempty" type:"Struct"`
Success *bool `json:"Success,omitempty" xml:"Success,omitempty"`
}
type VerifyIntelligentCaptchaResponseBodyResult struct {
VerifyCode *string `json:"VerifyCode,omitempty" xml:"VerifyCode,omitempty"`
VerifyResult *bool `json:"VerifyResult,omitempty" xml:"VerifyResult,omitempty"`
}
type VerifyIntelligentCaptchaResponseBody struct {
Code *string `json:"Code,omitempty" xml:"Code,omitempty"`
Message *string `json:"Message,omitempty" xml:"Message,omitempty"`
// Id of the request
RequestId *string `json:"RequestId,omitempty" xml:"RequestId,omitempty"`
Result *VerifyIntelligentCaptchaResponseBodyResult `json:"Result,omitempty" xml:"Result,omitempty" type:"Struct"`
Success *bool `json:"Success,omitempty" xml:"Success,omitempty"`
}
type VerifyIntelligentCaptchaResponse struct {
Headers map[string]*string `json:"headers,omitempty" xml:"headers,omitempty" require:"true"`
StatusCode *int32 `json:"statusCode,omitempty" xml:"statusCode,omitempty" require:"true"`
Body *VerifyIntelligentCaptchaResponseBody `json:"body,omitempty" xml:"body,omitempty" require:"true"`
}
type AliyunCaptchaProvider struct{}
func NewAliyunCaptchaProvider() *AliyunCaptchaProvider {
@@ -38,67 +67,69 @@ func NewAliyunCaptchaProvider() *AliyunCaptchaProvider {
return captcha
}
func contentEscape(str string) string {
str = strings.Replace(str, " ", "%20", -1)
str = url.QueryEscape(str)
return str
}
func (captcha *AliyunCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool, error) {
pathData, err := url.ParseQuery(token)
if err != nil {
return false, err
}
pathData["Action"] = []string{"AuthenticateSig"}
pathData["Format"] = []string{"json"}
pathData["SignatureMethod"] = []string{"HMAC-SHA1"}
pathData["SignatureNonce"] = []string{strconv.FormatInt(time.Now().UnixNano(), 10)}
pathData["SignatureVersion"] = []string{"1.0"}
pathData["Timestamp"] = []string{time.Now().UTC().Format("2006-01-02T15:04:05Z")}
pathData["Version"] = []string{"2018-01-12"}
var keys []string
for k := range pathData {
keys = append(keys, k)
}
sort.Strings(keys)
sortQuery := ""
for _, k := range keys {
sortQuery += k + "=" + contentEscape(pathData[k][0]) + "&"
}
sortQuery = strings.TrimSuffix(sortQuery, "&")
stringToSign := fmt.Sprintf("GET&%s&%s", url.QueryEscape("/"), url.QueryEscape(sortQuery))
signature := util.GetHmacSha1(clientSecret+"&", stringToSign)
resp, err := http.Get(fmt.Sprintf("%s?%s&Signature=%s", AliyunCaptchaVerifyUrl, sortQuery, url.QueryEscape(signature)))
if err != nil {
return false, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
type captchaResponse struct {
Code int `json:"Code"`
Msg string `json:"Msg"`
}
captchaResp := &captchaResponse{}
err = json.Unmarshal(body, captchaResp)
if err != nil {
return false, err
}
if captchaResp.Code != 100 {
return false, errors.New(captchaResp.Msg)
}
return true, nil
func (captcha *AliyunCaptchaProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
config := &openapi.Config{}
config.Endpoint = tea.String(AliyunCaptchaVerifyUrl)
config.ConnectTimeout = tea.Int(5000)
config.ReadTimeout = tea.Int(5000)
config.AccessKeyId = tea.String(clientId)
config.AccessKeySecret = tea.String(clientSecret)
client := new(openapi.Client)
err := client.Init(config)
if err != nil {
return false, err
}
request := VerifyCaptchaRequest{CaptchaVerifyParam: tea.String(token), SceneId: tea.String(clientId2)}
err = teaUtil.ValidateModel(&request)
if err != nil {
return false, err
}
runtime := &teaUtil.RuntimeOptions{}
body := map[string]interface{}{}
if !tea.BoolValue(teaUtil.IsUnset(request.CaptchaVerifyParam)) {
body["CaptchaVerifyParam"] = request.CaptchaVerifyParam
}
if !tea.BoolValue(teaUtil.IsUnset(request.SceneId)) {
body["SceneId"] = request.SceneId
}
req := &openapi.OpenApiRequest{
Body: openapiutil.ParseToMap(body),
}
params := &openapi.Params{
Action: tea.String("VerifyIntelligentCaptcha"),
Version: tea.String("2023-03-05"),
Protocol: tea.String("HTTPS"),
Pathname: tea.String("/"),
Method: tea.String("POST"),
AuthType: tea.String("AK"),
Style: tea.String("RPC"),
ReqBodyType: tea.String("formData"),
BodyType: tea.String("json"),
}
res := &VerifyIntelligentCaptchaResponse{}
resBody, err := client.CallApi(params, req, runtime)
if err != nil {
return false, err
}
err = tea.Convert(resBody, &res)
if err != nil {
return false, err
}
if res.Body.Result.VerifyResult != nil && *res.Body.Result.VerifyResult {
return true, nil
}
return false, nil
}

View File

@@ -23,6 +23,6 @@ func NewDefaultCaptchaProvider() *DefaultCaptchaProvider {
return captcha
}
func (captcha *DefaultCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool, error) {
func (captcha *DefaultCaptchaProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
return object.VerifyCaptcha(clientSecret, token), nil
}

View File

@@ -35,7 +35,7 @@ func NewGEETESTCaptchaProvider() *GEETESTCaptchaProvider {
return captcha
}
func (captcha *GEETESTCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool, error) {
func (captcha *GEETESTCaptchaProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
pathData, err := url.ParseQuery(token)
if err != nil {
return false, err

View File

@@ -32,7 +32,7 @@ func NewHCaptchaProvider() *HCaptchaProvider {
return captcha
}
func (captcha *HCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool, error) {
func (captcha *HCaptchaProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
reqData := url.Values{
"secret": {clientSecret},
"response": {token},

View File

@@ -14,21 +14,40 @@
package captcha
import "fmt"
type CaptchaProvider interface {
VerifyCaptcha(token, clientSecret string) (bool, error)
VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error)
}
func GetCaptchaProvider(captchaType string) CaptchaProvider {
if captchaType == "Default" {
switch captchaType {
case "Default":
return NewDefaultCaptchaProvider()
} else if captchaType == "reCAPTCHA" {
case "reCAPTCHA":
return NewReCaptchaProvider()
} else if captchaType == "hCaptcha" {
return NewHCaptchaProvider()
} else if captchaType == "Aliyun Captcha" {
case "reCAPTCHA v2":
return NewReCaptchaProvider()
case "reCAPTCHA v3":
return NewReCaptchaProvider()
case "Aliyun Captcha":
return NewAliyunCaptchaProvider()
} else if captchaType == "GEETEST" {
case "hCaptcha":
return NewHCaptchaProvider()
case "GEETEST":
return NewGEETESTCaptchaProvider()
case "Cloudflare Turnstile":
return NewCloudflareTurnstileProvider()
}
return nil
}
func VerifyCaptchaByCaptchaType(captchaType, token, clientId, clientSecret, clientId2 string) (bool, error) {
provider := GetCaptchaProvider(captchaType)
if provider == nil {
return false, fmt.Errorf("invalid captcha provider: %s", captchaType)
}
return provider.VerifyCaptcha(token, clientId, clientSecret, clientId2)
}

View File

@@ -32,7 +32,7 @@ func NewReCaptchaProvider() *ReCaptchaProvider {
return captcha
}
func (captcha *ReCaptchaProvider) VerifyCaptcha(token, clientSecret string) (bool, error) {
func (captcha *ReCaptchaProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
reqData := url.Values{
"secret": {clientSecret},
"response": {token},

66
captcha/turnstile.go Normal file
View File

@@ -0,0 +1,66 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package captcha
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
)
const CloudflareTurnstileVerifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
type CloudflareTurnstileProvider struct{}
func NewCloudflareTurnstileProvider() *CloudflareTurnstileProvider {
captcha := &CloudflareTurnstileProvider{}
return captcha
}
func (captcha *CloudflareTurnstileProvider) VerifyCaptcha(token, clientId, clientSecret, clientId2 string) (bool, error) {
reqData := url.Values{
"secret": {clientSecret},
"response": {token},
}
resp, err := http.PostForm(CloudflareTurnstileVerifyUrl, reqData)
if err != nil {
return false, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
type captchaResponse struct {
Success bool `json:"success"`
ErrorCodes []string `json:"error-codes"`
}
captchaResp := &captchaResponse{}
err = json.Unmarshal(body, captchaResp)
if err != nil {
return false, err
}
if len(captchaResp.ErrorCodes) > 0 {
return false, errors.New(strings.Join(captchaResp.ErrorCodes, ","))
}
return captchaResp.Success, nil
}

BIN
casdoor

Binary file not shown.

107
certificate/account.go Normal file
View File

@@ -0,0 +1,107 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certificate
import (
"crypto"
"github.com/casbin/lego/v4/acme"
"github.com/casbin/lego/v4/certcrypto"
"github.com/casbin/lego/v4/lego"
"github.com/casbin/lego/v4/registration"
"github.com/casdoor/casdoor/proxy"
)
type Account struct {
Email string
Registration *registration.Resource
Key crypto.PrivateKey
}
/** Implementation of the registration.User interface **/
// GetEmail returns the email address for the account.
func (a *Account) GetEmail() string {
return a.Email
}
// GetPrivateKey returns the private RSA account key.
func (a *Account) GetPrivateKey() crypto.PrivateKey {
return a.Key
}
// GetRegistration returns the server registration.
func (a *Account) GetRegistration() *registration.Resource {
return a.Registration
}
func getLegoClientAndAccount(email string, privateKey string, devMode bool) (*lego.Client, *Account, error) {
key, err := decodeEccKey(privateKey)
if err != nil {
return nil, nil, err
}
account := &Account{
Email: email,
Key: key,
}
config := lego.NewConfig(account)
if devMode {
config.CADirURL = lego.LEDirectoryStaging
} else {
config.CADirURL = lego.LEDirectoryProduction
}
config.Certificate.KeyType = certcrypto.RSA2048
config.HTTPClient = proxy.ProxyHttpClient
client, err := lego.NewClient(config)
if err != nil {
return nil, nil, err
}
return client, account, err
}
// GetAcmeClient Incoming an email ,a privatekey and a Boolean value that controls the opening of the test environment
// When this function is started for the first time, it will initialize the account-related configuration,
// After initializing the configuration, It will try to obtain an account based on the private key,
// if it fails, it will create an account based on the private key.
// This account will be used during the running of the program
func GetAcmeClient(email string, privateKey string, devMode bool) (*lego.Client, error) {
// Create a user. New accounts need an email and private key to start.
client, account, err := getLegoClientAndAccount(email, privateKey, devMode)
// try to obtain an account based on the private key
account.Registration, err = client.Registration.ResolveAccountByKey()
if err != nil {
acmeError, ok := err.(*acme.ProblemDetails)
if !ok {
return nil, err
}
if acmeError.Type != "urn:ietf:params:acme:error:accountDoesNotExist" {
return nil, acmeError
}
// Failed to get account, so create an account based on the private key.
account.Registration, err = client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
if err != nil {
return nil, err
}
}
return client, nil
}

View File

@@ -0,0 +1,47 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !skipCi
// +build !skipCi
package certificate
import (
"testing"
"github.com/beego/beego/v2/server/web"
"github.com/casdoor/casdoor/proxy"
"github.com/casdoor/casdoor/util"
"github.com/stretchr/testify/assert"
)
func TestGetClient(t *testing.T) {
err := web.LoadAppConfig("ini", "../conf/app.conf")
if err != nil {
panic(err)
}
proxy.InitHttpClient()
eccKey := util.ReadStringFromPath("acme_account.key")
println(eccKey)
client, err := GetAcmeClient("acme2@casbin.org", eccKey, false)
assert.Nil(t, err)
pem, key, err := ObtainCertificateAli(client, "casbin.com", accessKeyId, accessKeySecret)
assert.Nil(t, err)
println(pem)
println()
println(key)
}

20
certificate/conf.go Normal file
View File

@@ -0,0 +1,20 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certificate
var (
accessKeyId = ""
accessKeySecret = ""
)

151
certificate/dns.go Normal file
View File

@@ -0,0 +1,151 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certificate
import (
"fmt"
"time"
"github.com/casbin/lego/v4/certificate"
"github.com/casbin/lego/v4/challenge/dns01"
"github.com/casbin/lego/v4/cmd"
"github.com/casbin/lego/v4/lego"
"github.com/casbin/lego/v4/providers/dns/alidns"
"github.com/casbin/lego/v4/providers/dns/godaddy"
)
type AliConf struct {
Domains []string // The domain names for which you want to apply for a certificate
AccessKey string // Aliyun account's AccessKey, if this is not empty, Secret is required.
Secret string
RAMRole string // Use Ramrole to control aliyun account
SecurityToken string // Optional
Path string // The path to store cert file
Timeout int // Maximum waiting time for certificate application, in minutes
}
type GodaddyConf struct {
Domains []string // The domain names for which you want to apply for a certificate
APIKey string // GoDaddy account's API Key
APISecret string
Path string // The path to store cert file
Timeout int // Maximum waiting time for certificate application, in minutes
}
// getCert Verify domain ownership, then obtain a certificate, and finally store it locally.
// Need to pass in an AliConf struct, some parameters are required, other parameters can be left blank
func getAliCert(client *lego.Client, conf AliConf) (string, string, error) {
if conf.Timeout <= 0 {
conf.Timeout = 3
}
config := alidns.NewDefaultConfig()
config.PropagationTimeout = time.Duration(conf.Timeout) * time.Minute
config.APIKey = conf.AccessKey
config.SecretKey = conf.Secret
config.RAMRole = conf.RAMRole
config.SecurityToken = conf.SecurityToken
dnsProvider, err := alidns.NewDNSProvider(config)
if err != nil {
return "", "", err
}
// Choose a local DNS service provider to increase the authentication speed
servers := []string{"223.5.5.5:53"}
err = client.Challenge.SetDNS01Provider(dnsProvider, dns01.CondOption(len(servers) > 0, dns01.AddRecursiveNameservers(dns01.ParseNameservers(servers))), dns01.DisableCompletePropagationRequirement())
if err != nil {
return "", "", err
}
// Obtain the certificate
request := certificate.ObtainRequest{
Domains: conf.Domains,
Bundle: true,
}
cert, err := client.Certificate.Obtain(request)
if err != nil {
return "", "", err
}
return string(cert.Certificate), string(cert.PrivateKey), nil
}
func getGoDaddyCert(client *lego.Client, conf GodaddyConf) (string, string, error) {
if conf.Timeout <= 0 {
conf.Timeout = 3
}
config := godaddy.NewDefaultConfig()
config.PropagationTimeout = time.Duration(conf.Timeout) * time.Minute
config.PollingInterval = time.Duration(conf.Timeout) * time.Minute / 9
config.APIKey = conf.APIKey
config.APISecret = conf.APISecret
dnsProvider, err := godaddy.NewDNSProvider(config)
if err != nil {
return "", "", err
}
// Choose a local DNS service provider to increase the authentication speed
servers := []string{"223.5.5.5:53"}
err = client.Challenge.SetDNS01Provider(dnsProvider, dns01.CondOption(len(servers) > 0, dns01.AddRecursiveNameservers(dns01.ParseNameservers(servers))), dns01.DisableCompletePropagationRequirement())
if err != nil {
return "", "", err
}
// Obtain the certificate
request := certificate.ObtainRequest{
Domains: conf.Domains,
Bundle: true,
}
cert, err := client.Certificate.Obtain(request)
if err != nil {
return "", "", err
}
return string(cert.Certificate), string(cert.PrivateKey), nil
}
func ObtainCertificateAli(client *lego.Client, domain string, accessKey string, accessSecret string) (string, string, error) {
conf := AliConf{
Domains: []string{fmt.Sprintf("*.%s", domain), domain},
AccessKey: accessKey,
Secret: accessSecret,
RAMRole: "",
SecurityToken: "",
Path: "",
Timeout: 3,
}
return getAliCert(client, conf)
}
func ObtainCertificateGoDaddy(client *lego.Client, domain string, accessKey string, accessSecret string) (string, string, error) {
conf := GodaddyConf{
Domains: []string{fmt.Sprintf("*.%s", domain), domain},
APIKey: accessKey,
APISecret: accessSecret,
Path: "",
Timeout: 3,
}
return getGoDaddyCert(client, conf)
}
func SaveCert(path, filename string, cert *certificate.Resource) {
// Store the certificate file locally
certsStorage := cmd.NewCertificatesStorageLib(path, filename, true)
certsStorage.CreateRootFolder()
certsStorage.SaveResource(cert)
}

55
certificate/ecc.go Normal file
View File

@@ -0,0 +1,55 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certificate
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
)
// generateEccKey generates a public and private key pair.(NIST P-256)
func generateEccKey() (*ecdsa.PrivateKey, error) {
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}
// encodeEccKey Return the input private key object as string type private key
func encodeEccKey(privateKey *ecdsa.PrivateKey) (string, error) {
x509Encoded, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return "", err
}
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: x509Encoded})
return string(pemEncoded), nil
}
// decodeEccKey Return the entered private key string as a private key object that can be used
func decodeEccKey(pemEncoded string) (*ecdsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(pemEncoded))
if block == nil {
return nil, fmt.Errorf("invalid PEM-encoded EC private key")
}
x509Encoded := block.Bytes
privateKey, err := x509.ParseECPrivateKey(x509Encoded)
if err != nil {
return nil, err
}
return privateKey, nil
}

View File

@@ -1,4 +1,4 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -12,22 +12,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package util
//go:build !skipCi
// +build !skipCi
package certificate
import (
"testing"
"github.com/casdoor/casdoor/util"
"github.com/stretchr/testify/assert"
)
func TestGetCpuUsage(t *testing.T) {
usage, err := GetCpuUsage()
func TestGenerateEccKey(t *testing.T) {
eccKey, err := generateEccKey()
assert.Nil(t, err)
t.Log(usage)
}
func TestGetMemoryUsage(t *testing.T) {
used, total, err := GetMemoryUsage()
eccKeyStr, err := encodeEccKey(eccKey)
assert.Nil(t, err)
t.Log(used, total)
println(eccKeyStr)
util.WriteStringToPath(eccKeyStr, "acme_account.key")
}

View File

@@ -1,22 +1,37 @@
appname = casdoor
httpport = 8000
runmode = dev
copyrequestbody = true
driverName = mysql
dataSourceName = root:123456@tcp(localhost:3306)/
dbName = casdoor
tableNamePrefix =
showSql = false
redisEndpoint =
defaultStorageProvider =
isCloudIntranet = false
authState = "casdoor"
socks5Proxy = "127.0.0.1:10808"
verificationCodeTimeout = 10
initScore = 2000
logPostOnly = true
origin =
staticBaseUrl = "https://cdn.casbin.org"
isDemoMode = false
batchSize = 100
ldapServerPort = 389
appname = casdoor
httpport = 8000
runmode = dev
copyrequestbody = true
driverName = postgres
dataSourceName = "user=casdoor password=casdoor_dev host=localhost port=5434 sslmode=disable dbname=casdoor"
dbName = casdoor
tableNamePrefix =
showSql = false
redisEndpoint =
defaultStorageProvider =
isCloudIntranet = false
authState = "casdoor"
socks5Proxy = ""
verificationCodeTimeout = 10
initScore = 0
logPostOnly = true
isUsernameLowered = false
origin = "http://localhost:8000"
originFrontend = "http://localhost:7001"
staticBaseUrl = "https://cdn.casbin.org"
isDemoMode = false
batchSize = 100
showGithubCorner = false
forceLanguage = ""
defaultLanguage = "ru"
enableErrorMask = false
enableGzip = true
ldapServerPort = 389
ldapsServerPort = 636
radiusServerPort = 1812
radiusDefaultOrganization = "built-in"
radiusSecret = "secret"
quota = {"organization": -1, "user": -1, "application": -1, "provider": -1}
logConfig = {"adapter":"file", "filename": "logs/casdoor.log", "maxdays":99999, "perm":"0770"}
initDataNewOnly = false
initDataFile = "./init_data.json"

43
conf/app.conf.orig Normal file
View File

@@ -0,0 +1,43 @@
appname = casdoor
httpport = 8000
runmode = dev
copyrequestbody = true
driverName = mysql
dataSourceName = root:123456@tcp(localhost:3306)/
dbName = casdoor
tableNamePrefix =
showSql = false
redisEndpoint =
defaultStorageProvider =
isCloudIntranet = false
authState = "casdoor"
socks5Proxy = "127.0.0.1:10808"
verificationCodeTimeout = 10
initScore = 0
logPostOnly = true
isUsernameLowered = false
origin =
originFrontend =
staticBaseUrl = "https://cdn.casbin.org"
isDemoMode = false
batchSize = 100
showGithubCorner = false
forceLanguage = ""
defaultLanguage = "en"
aiAssistantUrl = "https://ai.casbin.com"
defaultApplication = "app-built-in"
maxItemsForFlatMenu = 7
enableErrorMask = false
enableGzip = true
inactiveTimeoutMinutes =
ldapServerPort = 389
ldapsCertId = ""
ldapsServerPort = 636
radiusServerPort = 1812
radiusDefaultOrganization = "built-in"
radiusSecret = "secret"
quota = {"organization": -1, "user": -1, "application": -1, "provider": -1}
logConfig = {"adapter":"file", "filename": "logs/casdoor.log", "maxdays":99999, "perm":"0770"}
initDataNewOnly = false
initDataFile = "./init_data.json"
frontendBaseDir = "../cc_0"

37
conf/app.dev.conf Normal file
View File

@@ -0,0 +1,37 @@
appname = casdoor
httpport = 8000
runmode = dev
copyrequestbody = true
driverName = postgres
dataSourceName = "user=casdoor password=casdoor_dev host=localhost port=5434 sslmode=disable dbname=casdoor"
dbName = casdoor
tableNamePrefix =
showSql = false
redisEndpoint =
defaultStorageProvider =
isCloudIntranet = false
authState = "casdoor"
socks5Proxy = ""
verificationCodeTimeout = 10
initScore = 0
logPostOnly = true
isUsernameLowered = false
origin = "http://localhost:8000"
originFrontend = "http://localhost:7001"
staticBaseUrl = "https://cdn.casbin.org"
isDemoMode = false
batchSize = 100
showGithubCorner = false
forceLanguage = ""
defaultLanguage = "ru"
enableErrorMask = false
enableGzip = true
ldapServerPort = 389
ldapsServerPort = 636
radiusServerPort = 1812
radiusDefaultOrganization = "built-in"
radiusSecret = "secret"
quota = {"organization": -1, "user": -1, "application": -1, "provider": -1}
logConfig = {"adapter":"file", "filename": "logs/casdoor.log", "maxdays":99999, "perm":"0770"}
initDataNewOnly = false
initDataFile = "./init_data.json"

View File

@@ -15,21 +15,25 @@
package conf
import (
_ "embed"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"github.com/astaxie/beego"
"github.com/beego/beego/v2/server/web"
)
//go:embed waf.conf
var WafConf string
func init() {
// this array contains the beego configuration items that may be modified via env
presetConfigItems := []string{"httpport", "appname"}
for _, key := range presetConfigItems {
if value, ok := os.LookupEnv(key); ok {
err := beego.AppConfig.Set(key, value)
err := web.AppConfig.Set(key, value)
if err != nil {
panic(err)
}
@@ -42,35 +46,44 @@ func GetConfigString(key string) string {
return value
}
res := beego.AppConfig.String(key)
res, _ := web.AppConfig.String(key)
if res == "" {
if key == "staticBaseUrl" {
res = "https://cdn.casbin.org"
} else if key == "logConfig" {
appname, _ := web.AppConfig.String("appname")
res = fmt.Sprintf("{\"filename\": \"logs/%s.log\", \"maxdays\":99999, \"perm\":\"0770\"}", appname)
}
}
return res
}
func GetConfigBool(key string) (bool, error) {
func GetConfigBool(key string) bool {
value := GetConfigString(key)
if value == "true" {
return true, nil
} else if value == "false" {
return false, nil
return true
} else {
return false
}
return false, fmt.Errorf("value %s cannot be converted into bool", value)
}
func GetConfigInt64(key string) (int64, error) {
value := GetConfigString(key)
num, err := strconv.ParseInt(value, 10, 64)
return num, err
if err != nil {
return 0, fmt.Errorf("GetConfigInt64(%s) error, %s", key, err.Error())
}
return num, nil
}
func GetConfigDataSourceName() string {
dataSourceName := GetConfigString("dataSourceName")
return ReplaceDataSourceNameByDocker(dataSourceName)
}
func ReplaceDataSourceNameByDocker(dataSourceName string) string {
runningInDocker := os.Getenv("RUNNING_IN_DOCKER")
if runningInDocker == "true" {
// https://stackoverflow.com/questions/48546124/what-is-linux-equivalent-of-host-docker-internal
@@ -80,10 +93,21 @@ func GetConfigDataSourceName() string {
dataSourceName = strings.ReplaceAll(dataSourceName, "localhost", "host.docker.internal")
}
}
return dataSourceName
}
func GetLanguage(language string) string {
if language == "" || language == "*" {
return "en"
}
if len(language) != 2 || language == "nu" {
return "en"
} else {
return language
}
}
func IsDemoMode() bool {
return strings.ToLower(GetConfigString("isDemoMode")) == "true"
}

48
conf/conf_quota.go Normal file
View File

@@ -0,0 +1,48 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package conf
import (
"encoding/json"
"github.com/beego/beego/v2/server/web"
)
type Quota struct {
Organization int `json:"organization"`
User int `json:"user"`
Application int `json:"application"`
Provider int `json:"provider"`
}
var quota = &Quota{-1, -1, -1, -1}
func init() {
initQuota()
}
func initQuota() {
res, _ := web.AppConfig.String("quota")
if res != "" {
err := json.Unmarshal([]byte(res), quota)
if err != nil {
panic(err)
}
}
}
func GetConfigQuota() *Quota {
return quota
}

View File

@@ -18,7 +18,7 @@ import (
"os"
"testing"
"github.com/astaxie/beego"
"github.com/beego/beego/v2/server/web"
"github.com/stretchr/testify/assert"
)
@@ -38,7 +38,7 @@ func TestGetConfString(t *testing.T) {
os.Setenv("appname", "casbin")
os.Setenv("key", "value")
err := beego.LoadAppConfig("ini", "app.conf")
err := web.LoadAppConfig("ini", "app.conf")
assert.Nil(t, err)
for _, scenery := range scenarios {
@@ -62,7 +62,7 @@ func TestGetConfInt(t *testing.T) {
// do some set up job
os.Setenv("httpport", "8001")
err := beego.LoadAppConfig("ini", "app.conf")
err := web.LoadAppConfig("ini", "app.conf")
assert.Nil(t, err)
for _, scenery := range scenarios {
@@ -83,13 +83,45 @@ func TestGetConfBool(t *testing.T) {
{"Should be return false", "copyrequestbody", true},
}
err := beego.LoadAppConfig("ini", "app.conf")
err := web.LoadAppConfig("ini", "app.conf")
assert.Nil(t, err)
for _, scenery := range scenarios {
t.Run(scenery.description, func(t *testing.T) {
actual, err := GetConfigBool(scenery.input)
actual := GetConfigBool(scenery.input)
assert.Nil(t, err)
assert.Equal(t, scenery.expected, actual)
})
}
}
func TestGetConfigQuota(t *testing.T) {
scenarios := []struct {
description string
expected *Quota
}{
{"default", &Quota{-1, -1, -1, -1}},
}
err := web.LoadAppConfig("ini", "app.conf")
assert.Nil(t, err)
for _, scenery := range scenarios {
quota := GetConfigQuota()
assert.Equal(t, scenery.expected, quota)
}
}
func TestGetConfigLogs(t *testing.T) {
scenarios := []struct {
description string
expected string
}{
{"Default log config", `{"adapter":"file", "filename": "logs/casdoor.log", "maxdays":99999, "perm":"0770"}`},
}
err := web.LoadAppConfig("ini", "app.conf")
assert.Nil(t, err)
for _, scenery := range scenarios {
quota := GetConfigString("logConfig")
assert.Equal(t, scenery.expected, quota)
}
}

246
conf/waf.conf Normal file
View File

@@ -0,0 +1,246 @@
# -- Rule engine initialization ----------------------------------------------
# Enable Coraza, attaching it to every transaction. Use detection
# only to start with, because that minimises the chances of post-installation
# disruption.
#
SecRuleEngine DetectionOnly
# -- Request body handling ---------------------------------------------------
# Allow Coraza to access request bodies. If you don't, Coraza
# won't be able to see any POST parameters, which opens a large security
# hole for attackers to exploit.
#
SecRequestBodyAccess On
# Enable XML request body parser.
# Initiate XML Processor in case of xml content-type
#
SecRule REQUEST_HEADERS:Content-Type "^(?:application(?:/soap\+|/)|text/)xml" \
"id:'200000',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML"
# Enable JSON request body parser.
# Initiate JSON Processor in case of JSON content-type; change accordingly
# if your application does not use 'application/json'
#
SecRule REQUEST_HEADERS:Content-Type "^application/json" \
"id:'200001',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=JSON"
# Sample rule to enable JSON request body parser for more subtypes.
# Uncomment or adapt this rule if you want to engage the JSON
# Processor for "+json" subtypes
#
#SecRule REQUEST_HEADERS:Content-Type "^application/[a-z0-9.-]+[+]json" \
# "id:'200006',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=JSON"
# Maximum request body size we will accept for buffering. If you support
# file uploads then the value given on the first line has to be as large
# as the largest file you are willing to accept. The second value refers
# to the size of data, with files excluded. You want to keep that value as
# low as practical.
#
SecRequestBodyLimit 13107200
SecRequestBodyInMemoryLimit 131072
# SecRequestBodyNoFilesLimit is currently not supported by Coraza
# SecRequestBodyNoFilesLimit 131072
# What to do if the request body size is above our configured limit.
# Keep in mind that this setting will automatically be set to ProcessPartial
# when SecRuleEngine is set to DetectionOnly mode in order to minimize
# disruptions when initially deploying Coraza.
#
SecRequestBodyLimitAction Reject
# Verify that we've correctly processed the request body.
# As a rule of thumb, when failing to process a request body
# you should reject the request (when deployed in blocking mode)
# or log a high-severity alert (when deployed in detection-only mode).
#
SecRule REQBODY_ERROR "!@eq 0" \
"id:'200002', phase:2,t:none,log,deny,status:400,msg:'Failed to parse request body.',logdata:'%{reqbody_error_msg}',severity:2"
# By default be strict with what we accept in the multipart/form-data
# request body. If the rule below proves to be too strict for your
# environment consider changing it to detection-only. You are encouraged
# _not_ to remove it altogether.
#
SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
"id:'200003',phase:2,t:none,log,deny,status:400, \
msg:'Multipart request body failed strict validation: \
PE %{REQBODY_PROCESSOR_ERROR}, \
BQ %{MULTIPART_BOUNDARY_QUOTED}, \
BW %{MULTIPART_BOUNDARY_WHITESPACE}, \
DB %{MULTIPART_DATA_BEFORE}, \
DA %{MULTIPART_DATA_AFTER}, \
HF %{MULTIPART_HEADER_FOLDING}, \
LF %{MULTIPART_LF_LINE}, \
SM %{MULTIPART_MISSING_SEMICOLON}, \
IQ %{MULTIPART_INVALID_QUOTING}, \
IP %{MULTIPART_INVALID_PART}, \
IH %{MULTIPART_INVALID_HEADER_FOLDING}, \
FL %{MULTIPART_FILE_LIMIT_EXCEEDED}'"
# Did we see anything that might be a boundary?
#
# Here is a short description about the Coraza Multipart parser: the
# parser returns with value 0, if all "boundary-like" line matches with
# the boundary string which given in MIME header. In any other cases it returns
# with different value, eg. 1 or 2.
#
# The RFC 1341 descript the multipart content-type and its syntax must contains
# only three mandatory lines (above the content):
# * Content-Type: multipart/mixed; boundary=BOUNDARY_STRING
# * --BOUNDARY_STRING
# * --BOUNDARY_STRING--
#
# First line indicates, that this is a multipart content, second shows that
# here starts a part of the multipart content, third shows the end of content.
#
# If there are any other lines, which starts with "--", then it should be
# another boundary id - or not.
#
# After 3.0.3, there are two kinds of types of boundary errors: strict and permissive.
#
# If multipart content contains the three necessary lines with correct order, but
# there are one or more lines with "--", then parser returns with value 2 (non-zero).
#
# If some of the necessary lines (usually the start or end) misses, or the order
# is wrong, then parser returns with value 1 (also a non-zero).
#
# You can choose, which one is what you need. The example below contains the
# 'strict' mode, which means if there are any lines with start of "--", then
# Coraza blocked the content. But the next, commented example contains
# the 'permissive' mode, then you check only if the necessary lines exists in
# correct order. Whit this, you can enable to upload PEM files (eg "----BEGIN.."),
# or other text files, which contains eg. HTTP headers.
#
# The difference is only the operator - in strict mode (first) the content blocked
# in case of any non-zero value. In permissive mode (second, commented) the
# content blocked only if the value is explicit 1. If it 0 or 2, the content will
# allowed.
#
#
# See #1747 and #1924 for further information on the possible values for
# MULTIPART_UNMATCHED_BOUNDARY.
#
SecRule MULTIPART_UNMATCHED_BOUNDARY "@eq 1" \
"id:'200004',phase:2,t:none,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"
# Some internal errors will set flags in TX and we will need to look for these.
# All of these are prefixed with "MSC_". The following flags currently exist:
#
# COR_PCRE_LIMITS_EXCEEDED: PCRE match limits were exceeded.
#
SecRule TX:/^COR_/ "!@streq 0" \
"id:'200005',phase:2,t:none,deny,msg:'Coraza internal error flagged: %{MATCHED_VAR_NAME}'"
# -- Response body handling --------------------------------------------------
# Allow Coraza to access response bodies.
# You should have this directive enabled in order to identify errors
# and data leakage issues.
#
# Do keep in mind that enabling this directive does increases both
# memory consumption and response latency.
#
SecResponseBodyAccess On
# Which response MIME types do you want to inspect? You should adjust the
# configuration below to catch documents but avoid static files
# (e.g., images and archives).
#
SecResponseBodyMimeType text/plain text/html text/xml
# Buffer response bodies of up to 512 KB in length.
SecResponseBodyLimit 524288
# What happens when we encounter a response body larger than the configured
# limit? By default, we process what we have and let the rest through.
# That's somewhat less secure, but does not break any legitimate pages.
#
SecResponseBodyLimitAction ProcessPartial
# -- Filesystem configuration ------------------------------------------------
# The location where Coraza will keep its persistent data. This default setting
# is chosen due to all systems have /tmp available however, it
# too should be updated to a place that other users can't access.
#
SecDataDir /tmp/
# -- File uploads handling configuration -------------------------------------
# The location where Coraza stores intercepted uploaded files. This
# location must be private to Coraza. You don't want other users on
# the server to access the files, do you?
#
#SecUploadDir /opt/coraza/var/upload/
# By default, only keep the files that were determined to be unusual
# in some way (by an external inspection script). For this to work you
# will also need at least one file inspection rule.
#
#SecUploadKeepFiles RelevantOnly
# Uploaded files are by default created with permissions that do not allow
# any other user to access them. You may need to relax that if you want to
# interface Coraza to an external program (e.g., an anti-virus).
#
#SecUploadFileMode 0600
# -- Debug log configuration -------------------------------------------------
# Default debug log path
# Debug levels:
# 0: No logging (least verbose)
# 1: Error
# 2: Warn
# 3: Info
# 4-8: Debug
# 9: Trace (most verbose)
# Most logging has not been implemented because it will be replaced with
# advanced rule profiling options
#SecDebugLog /opt/coraza/var/log/debug.log
#SecDebugLogLevel 3
# -- Audit log configuration -------------------------------------------------
# Log the transactions that are marked by a rule, as well as those that
# trigger a server error (determined by a 5xx or 4xx, excluding 404,
# level response status codes).
#
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:(5|4)(0|1)[0-9])$"
# Log everything we know about a transaction.
SecAuditLogParts ABIJDEFHZ
# Use a single file for logging. This is much easier to look at, but
# assumes that you will use the audit log only occasionally.
#
SecAuditLogType Serial
# -- Miscellaneous -----------------------------------------------------------
# Use the most commonly used application/x-www-form-urlencoded parameter
# separator. There's probably only one application somewhere that uses
# something else so don't expect to change this value.
#
SecArgumentSeparator &
# Settle on version 0 (zero) cookies, as that is what most applications
# use. Using an incorrect cookie version may open your installation to
# evasion attacks (against the rules that examine named cookies).
#
SecCookieFormat 0

49
conf/web_config.go Normal file
View File

@@ -0,0 +1,49 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package conf
type WebConfig struct {
ShowGithubCorner bool `json:"showGithubCorner"`
ForceLanguage string `json:"forceLanguage"`
DefaultLanguage string `json:"defaultLanguage"`
IsDemoMode bool `json:"isDemoMode"`
StaticBaseUrl string `json:"staticBaseUrl"`
AiAssistantUrl string `json:"aiAssistantUrl"`
DefaultApplication string `json:"defaultApplication"`
MaxItemsForFlatMenu int64 `json:"maxItemsForFlatMenu"`
}
func GetWebConfig() *WebConfig {
config := &WebConfig{}
config.ShowGithubCorner = GetConfigBool("showGithubCorner")
config.ForceLanguage = GetLanguage(GetConfigString("forceLanguage"))
config.DefaultLanguage = GetLanguage(GetConfigString("defaultLanguage"))
config.IsDemoMode = IsDemoMode()
config.StaticBaseUrl = GetConfigString("staticBaseUrl")
config.AiAssistantUrl = GetConfigString("aiAssistantUrl")
config.DefaultApplication = GetConfigString("defaultApplication")
if config.DefaultApplication == "" {
config.DefaultApplication = "app-built-in"
}
maxItemsForFlatMenu, err := GetConfigInt64("maxItemsForFlatMenu")
if err != nil {
maxItemsForFlatMenu = 7
}
config.MaxItemsForFlatMenu = maxItemsForFlatMenu
return config
}

View File

@@ -15,11 +15,14 @@
package controllers
import (
"context"
"encoding/json"
"fmt"
"strconv"
"net/http"
"strings"
"github.com/beego/beego/v2/core/logs"
"github.com/casdoor/casdoor/form"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -31,41 +34,9 @@ const (
ResponseTypeIdToken = "id_token"
ResponseTypeSaml = "saml"
ResponseTypeCas = "cas"
ResponseTypeDevice = "device"
)
type RequestForm struct {
Type string `json:"type"`
Organization string `json:"organization"`
Username string `json:"username"`
Password string `json:"password"`
Name string `json:"name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email"`
Phone string `json:"phone"`
Affiliation string `json:"affiliation"`
IdCard string `json:"idCard"`
Region string `json:"region"`
Application string `json:"application"`
Provider string `json:"provider"`
Code string `json:"code"`
State string `json:"state"`
RedirectUri string `json:"redirectUri"`
Method string `json:"method"`
EmailCode string `json:"emailCode"`
PhoneCode string `json:"phoneCode"`
PhonePrefix string `json:"phonePrefix"`
AutoSignin bool `json:"autoSignin"`
RelayState string `json:"relayState"`
SamlRequest string `json:"samlRequest"`
SamlResponse string `json:"samlResponse"`
}
type Response struct {
Status string `json:"status"`
Msg string `json:"msg"`
@@ -73,9 +44,12 @@ type Response struct {
Name string `json:"name"`
Data interface{} `json:"data"`
Data2 interface{} `json:"data2"`
Data3 interface{} `json:"data3"`
}
type Captcha struct {
Owner string `json:"owner"`
Name string `json:"name"`
Type string `json:"type"`
AppKey string `json:"appKey"`
Scene string `json:"scene"`
@@ -88,6 +62,17 @@ type Captcha struct {
SubType string `json:"subType"`
}
// this API is used by "Api URL" of Flarum's FoF Passport plugin
// https://github.com/FriendsOfFlarum/passport
type LaravelResponse struct {
Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerifiedAt string `json:"email_verified_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// Signup
// @Tag Login API
// @Title Signup
@@ -97,95 +82,158 @@ type Captcha struct {
// @Success 200 {object} controllers.Response The Response object
// @router /signup [post]
func (c *ApiController) Signup() {
if c.GetSessionUsername() != "" {
c.ResponseError("Please sign out first before signing up", c.GetSessionUsername())
return
}
var form RequestForm
err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
var authForm form.AuthForm
err := json.Unmarshal(c.Ctx.Input.RequestBody, &authForm)
if err != nil {
c.ResponseError(err.Error())
return
}
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
if !application.EnableSignUp {
c.ResponseError("The application does not allow to sign up new account")
application, err := object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application))
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), authForm.Application))
return
}
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", form.Organization))
msg := object.CheckUserSignup(application, organization, form.Username, form.Password, form.Name, form.FirstName, form.LastName, form.Email, form.Phone, form.Affiliation)
if !application.EnableSignUp {
c.ResponseError(c.T("account:The application does not allow to sign up new account"))
return
}
organization, err := object.GetOrganization(util.GetId("admin", authForm.Organization))
if err != nil {
c.ResponseError(c.T(err.Error()))
return
}
if organization == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The organization: %s does not exist"), authForm.Organization))
return
}
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
err = object.CheckEntryIp(clientIp, nil, application, organization, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
msg := object.CheckUserSignup(application, organization, &authForm, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
}
if application.IsSignupItemVisible("Email") && application.GetSignupItemRule("Email") != "No verification" && form.Email != "" {
checkResult := object.CheckVerificationCode(form.Email, form.EmailCode)
if len(checkResult) != 0 {
c.ResponseError(fmt.Sprintf("Email: %s", checkResult))
invitation, msg := object.CheckInvitationCode(application, organization, &authForm, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
}
invitationName := ""
if invitation != nil {
invitationName = invitation.Name
}
userEmailVerified := false
if application.IsSignupItemVisible("Email") && application.GetSignupItemRule("Email") != "No verification" && authForm.Email != "" {
var checkResult *object.VerifyResult
checkResult, err = object.CheckVerificationCode(authForm.Email, authForm.EmailCode, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(c.T(err.Error()))
return
}
if checkResult.Code != object.VerificationSuccess {
c.ResponseError(checkResult.Msg)
return
}
userEmailVerified = true
}
var checkPhone string
if application.IsSignupItemVisible("Phone") && form.Phone != "" {
checkPhone = fmt.Sprintf("+%s%s", form.PhonePrefix, form.Phone)
checkResult := object.CheckVerificationCode(checkPhone, form.PhoneCode)
if len(checkResult) != 0 {
c.ResponseError(fmt.Sprintf("Phone: %s", checkResult))
if application.IsSignupItemVisible("Phone") && application.GetSignupItemRule("Phone") != "No verification" && authForm.Phone != "" {
checkPhone, _ = util.GetE164Number(authForm.Phone, authForm.CountryCode)
var checkResult *object.VerifyResult
checkResult, err = object.CheckVerificationCode(checkPhone, authForm.PhoneCode, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(c.T(err.Error()))
return
}
if checkResult.Code != object.VerificationSuccess {
c.ResponseError(checkResult.Msg)
return
}
}
id := util.GenerateId()
if application.GetSignupItemRule("ID") == "Incremental" {
lastUser := object.GetLastUser(form.Organization)
lastIdInt := -1
if lastUser != nil {
lastIdInt = util.ParseInt(lastUser.Id)
}
id = strconv.Itoa(lastIdInt + 1)
}
username := form.Username
if !application.IsSignupItemVisible("Username") {
username = id
}
initScore, err := getInitScore()
id, err := object.GenerateIdForNewUser(application)
if err != nil {
c.ResponseError(fmt.Errorf("get init score failed, error: %w", err).Error())
c.ResponseError(err.Error())
return
}
username := authForm.Username
if !application.IsSignupItemVisible("Username") {
if organization.UseEmailAsUsername && application.IsSignupItemVisible("Email") {
username = authForm.Email
} else {
username = id
}
}
initScore, err := organization.GetInitScore()
if err != nil {
c.ResponseError(fmt.Errorf(c.T("account:Get init score failed, error: %w"), err).Error())
return
}
userType := "normal-user"
if authForm.Plan != "" && authForm.Pricing != "" {
err = object.CheckPricingAndPlan(authForm.Organization, authForm.Pricing, authForm.Plan, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
userType = "paid-user"
}
user := &object.User{
Owner: form.Organization,
Owner: authForm.Organization,
Name: username,
CreatedTime: util.GetCurrentTime(),
Id: id,
Type: "normal-user",
Password: form.Password,
DisplayName: form.Name,
Type: userType,
Password: authForm.Password,
DisplayName: authForm.Name,
Gender: authForm.Gender,
Bio: authForm.Bio,
Tag: authForm.Tag,
Education: authForm.Education,
Avatar: organization.DefaultAvatar,
Email: form.Email,
Phone: form.Phone,
Email: strings.ToLower(authForm.Email),
Phone: authForm.Phone,
CountryCode: authForm.CountryCode,
Address: []string{},
Affiliation: form.Affiliation,
IdCard: form.IdCard,
Region: form.Region,
Affiliation: authForm.Affiliation,
IdCard: authForm.IdCard,
Region: authForm.Region,
Score: initScore,
IsAdmin: false,
IsGlobalAdmin: false,
IsForbidden: false,
IsDeleted: false,
SignupApplication: application.Name,
Properties: map[string]string{},
Karma: 0,
Invitation: invitationName,
InvitationCode: authForm.InvitationCode,
EmailVerified: userEmailVerified,
RegisterType: "Application Signup",
RegisterSource: fmt.Sprintf("%s/%s", authForm.Organization, application.Name),
}
if len(organization.Tags) > 0 {
@@ -196,37 +244,109 @@ func (c *ApiController) Signup() {
}
if application.GetSignupItemRule("Display name") == "First, last" {
if form.FirstName != "" || form.LastName != "" {
user.DisplayName = fmt.Sprintf("%s %s", form.FirstName, form.LastName)
user.FirstName = form.FirstName
user.LastName = form.LastName
if authForm.FirstName != "" || authForm.LastName != "" {
user.DisplayName = fmt.Sprintf("%s %s", authForm.FirstName, authForm.LastName)
user.FirstName = authForm.FirstName
user.LastName = authForm.LastName
}
}
affected := object.AddUser(user)
if !affected {
c.ResponseError(fmt.Sprintf("Failed to create user, user information is invalid: %s", util.StructToJson(user)))
if invitation != nil && invitation.SignupGroup != "" {
user.Groups = []string{invitation.SignupGroup}
}
if application.DefaultGroup != "" && user.Groups == nil {
user.Groups = []string{application.DefaultGroup}
}
affected, err := object.AddUser(user, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
object.AddUserToOriginalDatabase(user)
if application.HasPromptPage() {
// The prompt page needs the user to be signed in
c.SetSessionUsername(user.GetId())
if !affected {
c.ResponseError(c.T("account:Failed to add user"), util.StructToJson(user))
return
}
object.DisableVerificationCode(form.Email)
object.DisableVerificationCode(checkPhone)
err = object.AddUserToOriginalDatabase(user)
if err != nil {
c.ResponseError(err.Error())
return
}
record := object.NewRecord(c.Ctx)
record.Organization = application.Organization
record.User = user.Name
util.SafeGoroutine(func() { object.AddRecord(record) })
if invitation != nil {
invitation.UsedCount += 1
_, err := object.UpdateInvitation(invitation.GetId(), invitation, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
}
if user.Type == "normal-user" {
c.SetSessionUsername(user.GetId())
} else if user.Type == "paid-user" {
c.SetSession("paidUsername", user.GetId())
}
if authForm.Email != "" {
err = object.DisableVerificationCode(authForm.Email)
if err != nil {
c.ResponseError(err.Error())
return
}
}
if checkPhone != "" {
err = object.DisableVerificationCode(checkPhone)
if err != nil {
c.ResponseError(err.Error())
return
}
}
c.Ctx.Input.SetParam("recordUserId", user.GetId())
c.Ctx.Input.SetParam("recordSignup", "true")
userId := user.GetId()
util.LogInfo(c.Ctx, "API: [%s] is signed up as new user", userId)
// Check if this is an OAuth flow and automatically generate code
clientId := c.Ctx.Input.Query("clientId")
responseType := c.Ctx.Input.Query("responseType")
redirectUri := c.Ctx.Input.Query("redirectUri")
scope := c.Ctx.Input.Query("scope")
state := c.Ctx.Input.Query("state")
nonce := c.Ctx.Input.Query("nonce")
codeChallenge := c.Ctx.Input.Query("code_challenge")
// If OAuth parameters are present, generate OAuth code and return it
if clientId != "" && responseType == ResponseTypeCode {
consentRequired, err := object.CheckConsentRequired(user, application, scope)
if err != nil {
c.ResponseError(err.Error())
return
}
if consentRequired {
c.ResponseOk(map[string]bool{"required": true})
return
}
code, err := object.GetOAuthCode(userId, clientId, "", "password", responseType, redirectUri, scope, state, nonce, codeChallenge, "", c.Ctx.Request.Host, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error(), nil)
return
}
resp := codeToResponse(code)
c.Data["json"] = resp
c.ServeJSON()
return
}
c.ResponseOk(userId)
}
@@ -234,21 +354,217 @@ func (c *ApiController) Signup() {
// @Title Logout
// @Tag Login API
// @Description logout the current user
// @Param id_token_hint query string false "id_token_hint"
// @Param post_logout_redirect_uri query string false "post_logout_redirect_uri"
// @Param state query string false "state"
// @Success 200 {object} controllers.Response The Response object
// @router /logout [get,post]
// @router /logout [post]
func (c *ApiController) Logout() {
// https://openid.net/specs/openid-connect-rpinitiated-1_0-final.html
accessToken := c.GetString("id_token_hint")
redirectUri := c.GetString("post_logout_redirect_uri")
state := c.GetString("state")
user := c.GetSessionUsername()
util.LogInfo(c.Ctx, "API: [%s] logged out", user)
application := c.GetSessionApplication()
c.SetSessionUsername("")
c.SetSessionData(nil)
if accessToken == "" && redirectUri == "" {
// TODO https://github.com/casdoor/casdoor/pull/1494#discussion_r1095675265
if user == "" {
c.ResponseOk()
return
}
if application == nil || application.Name == "app-built-in" || application.HomepageUrl == "" {
c.ResponseOk(user)
// Retrieve application and token before clearing the session
application := c.GetSessionApplication()
sessionToken := c.GetSessionToken()
c.ClearUserSession()
c.ClearTokenSession()
if err := c.deleteUserSession(user); err != nil {
c.ResponseError(err.Error())
return
}
// Propagate logout to external Custom OAuth2 providers
object.InvokeCustomProviderLogout(application, sessionToken)
if application == nil || application.Name == "app-built-in" || application.HomepageUrl == "" {
c.ResponseOk(user)
return
}
c.ResponseOk(user, application.HomepageUrl)
return
} else {
// "post_logout_redirect_uri" has been made optional, see: https://github.com/casdoor/casdoor/issues/2151
// if redirectUri == "" {
// c.ResponseError(c.T("general:Missing parameter") + ": post_logout_redirect_uri")
// return
// }
if accessToken == "" {
c.ResponseError(c.T("general:Missing parameter") + ": id_token_hint")
return
}
_, application, token, err := object.ExpireTokenByAccessToken(accessToken)
if err != nil {
c.ResponseError(err.Error())
return
}
if token == nil {
c.ResponseError(c.T("token:Token not found, invalid accessToken"))
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), token.Application))
return
}
if user == "" {
user = util.GetId(token.Organization, token.User)
}
c.ClearUserSession()
c.ClearTokenSession()
// TODO https://github.com/casdoor/casdoor/pull/1494#discussion_r1095675265
if err := c.deleteUserSession(user); err != nil {
c.ResponseError(err.Error())
return
}
// Propagate logout to external Custom OAuth2 providers
object.InvokeCustomProviderLogout(application, accessToken)
if redirectUri == "" {
c.ResponseOk()
return
} else {
if application.IsRedirectUriValid(redirectUri) {
redirectUrl := redirectUri
if state != "" {
if strings.Contains(redirectUri, "?") {
redirectUrl = fmt.Sprintf("%s&state=%s", strings.TrimSuffix(redirectUri, "/"), state)
} else {
redirectUrl = fmt.Sprintf("%s?state=%s", strings.TrimSuffix(redirectUri, "/"), state)
}
}
c.Ctx.Redirect(http.StatusFound, redirectUrl)
} else {
c.ResponseError(fmt.Sprintf(c.T("token:Redirect URI: %s doesn't exist in the allowed Redirect URI list"), redirectUri))
return
}
}
}
}
// SsoLogout
// @Title SsoLogout
// @Tag Login API
// @Description logout the current user from all applications or current session only
// @Param logoutAll query string false "Whether to logout from all sessions. Accepted values: 'true', '1', or empty (default: true). Any other value means false."
// @Success 200 {object} controllers.Response The Response object
// @router /sso-logout [get,post]
func (c *ApiController) SsoLogout() {
user := c.GetSessionUsername()
if user == "" {
c.ResponseOk()
return
}
c.ResponseOk(user, application.HomepageUrl)
// Check if user wants to logout from all sessions or just current session
// Default is true for backward compatibility
logoutAll := c.Ctx.Input.Query("logoutAll")
logoutAllSessions := logoutAll == "" || logoutAll == "true" || logoutAll == "1"
// Retrieve application and token before clearing the session
ssoApplication := c.GetSessionApplication()
ssoSessionToken := c.GetSessionToken()
c.ClearUserSession()
c.ClearTokenSession()
owner, username, err := util.GetOwnerAndNameFromIdWithError(user)
if err != nil {
c.ResponseError(err.Error())
return
}
currentSessionId := c.Ctx.Input.CruSession.SessionID(context.Background())
_, err = object.DeleteSessionId(util.GetSessionId(owner, username, object.CasdoorApplication), currentSessionId)
if err != nil {
c.ResponseError(err.Error())
return
}
var tokens []*object.Token
var sessionIds []string
// Get tokens for notification (needed for both session-level and full logout)
// This enables subsystems to identify and invalidate corresponding access tokens
// Note: Tokens must be retrieved BEFORE expiration to include their hashes in the notification
tokens, err = object.GetTokensByUser(owner, username)
if err != nil {
c.ResponseError(err.Error())
return
}
if logoutAllSessions {
// Logout from all sessions: expire all tokens and delete all sessions
_, err = object.ExpireTokenByUser(owner, username)
if err != nil {
c.ResponseError(err.Error())
return
}
sessions, err := object.GetUserSessions(owner, username)
if err != nil {
c.ResponseError(err.Error())
return
}
for _, session := range sessions {
sessionIds = append(sessionIds, session.SessionId...)
}
object.DeleteBeegoSession(sessionIds)
_, err = object.DeleteAllUserSessions(owner, username)
if err != nil {
c.ResponseError(err.Error())
return
}
util.LogInfo(c.Ctx, "API: [%s] logged out from all applications", user)
} else {
// Logout from current session only
sessionIds = []string{currentSessionId}
// Only delete the current session's Beego session
object.DeleteBeegoSession(sessionIds)
util.LogInfo(c.Ctx, "API: [%s] logged out from current session", user)
}
// Send SSO logout notifications to all notification providers in the user's signup application
// Now includes session-level information for targeted logout
userObj, err := object.GetUser(user)
if err != nil {
c.ResponseError(err.Error())
return
}
if userObj != nil {
err = object.SendSsoLogoutNotifications(userObj, sessionIds, tokens)
if err != nil {
c.ResponseError(err.Error())
return
}
}
// Propagate logout to external Custom OAuth2 providers
object.InvokeCustomProviderLogout(ssoApplication, ssoSessionToken)
c.ResponseOk()
}
// GetAccount
@@ -258,22 +574,71 @@ func (c *ApiController) Logout() {
// @Success 200 {object} controllers.Response The Response object
// @router /get-account [get]
func (c *ApiController) GetAccount() {
var err error
err = util.AppendWebConfigCookie(c.Ctx)
if err != nil {
logs.Error("AppendWebConfigCookie failed in GetAccount, error: %s", err)
}
user, ok := c.RequireSignedInUser()
if !ok {
return
}
managedAccounts := c.Input().Get("managedAccounts")
managedAccounts := c.Ctx.Input.Query("managedAccounts")
if managedAccounts == "1" {
user = object.ExtendManagedAccountsWithUser(user)
user, err = object.ExtendManagedAccountsWithUser(user)
if err != nil {
c.ResponseError(err.Error())
return
}
}
organization := object.GetMaskedOrganization(object.GetOrganizationByUser(user))
err = object.ExtendUserWithRolesAndPermissions(user)
if err != nil {
c.ResponseError(err.Error())
return
}
if user != nil {
user.Permissions = object.GetMaskedPermissions(user.Permissions)
user.Roles = object.GetMaskedRoles(user.Roles)
user.MultiFactorAuths = object.GetAllMfaProps(user, true)
}
organization, err := object.GetMaskedOrganization(object.GetOrganizationByUser(user))
if err != nil {
c.ResponseError(err.Error())
return
}
isAdminOrSelf := c.IsAdminOrSelf(user)
u, err := object.GetMaskedUser(user, isAdminOrSelf)
if err != nil {
c.ResponseError(err.Error())
return
}
if organization != nil && len(organization.CountryCodes) == 1 && u != nil && u.CountryCode == "" {
u.CountryCode = organization.CountryCodes[0]
}
accessToken := c.GetSessionToken()
if accessToken == "" {
accessToken, err = object.GetAccessTokenByUser(user, c.Ctx.Request.Host)
if err != nil {
c.ResponseError(err.Error())
return
}
c.SetSessionToken(accessToken)
}
u.AccessToken = accessToken
resp := Response{
Status: "ok",
Sub: user.Id,
Name: user.Name,
Data: user,
Data: u,
Data2: organization,
}
c.Data["json"] = resp
@@ -295,21 +660,98 @@ func (c *ApiController) GetUserinfo() {
scope, aud := c.GetSessionOidc()
host := c.Ctx.Request.Host
userInfo := object.GetUserInfo(user, scope, aud, host)
userInfo, err := object.GetUserInfo(user, scope, aud, host)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = userInfo
c.ServeJSON()
}
// GetUserinfo2
// LaravelResponse
// @Title UserInfo2
// @Tag Account API
// @Description return Laravel compatible user information according to OAuth 2.0
// @Success 200 {object} controllers.LaravelResponse The Response object
// @router /user [get]
func (c *ApiController) GetUserinfo2() {
user, ok := c.RequireSignedInUser()
if !ok {
return
}
response := LaravelResponse{
Id: user.Id,
Name: user.Name,
Email: user.Email,
EmailVerifiedAt: user.CreatedTime,
CreatedAt: user.CreatedTime,
UpdatedAt: user.UpdatedTime,
}
c.Data["json"] = response
c.ServeJSON()
}
// GetCaptcha ...
// @Tag Login API
// @Title GetCaptcha
// @router /api/get-captcha [get]
// @router /get-captcha [get]
// @Success 200 {object} object.Userinfo The Response object
func (c *ApiController) GetCaptcha() {
applicationId := c.Input().Get("applicationId")
isCurrentProvider := c.Input().Get("isCurrentProvider")
applicationId := c.Ctx.Input.Query("applicationId")
isCurrentProvider := c.Ctx.Input.Query("isCurrentProvider")
captchaProvider, err := object.GetCaptchaProviderByApplication(applicationId, isCurrentProvider)
// When isCurrentProvider == "true", the frontend passes a provider ID instead of an application ID.
// In that case, skip application lookup and rule evaluation, and just return the provider config.
shouldSkipCaptcha := false
if isCurrentProvider != "true" {
application, err := object.GetApplication(applicationId)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), applicationId))
return
}
// Check the CAPTCHA rule to determine if CAPTCHA should be shown
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
// For Internet-Only rule, we can determine on the backend if CAPTCHA should be shown
// For other rules (Dynamic, Always), we need to return the CAPTCHA config
for _, providerItem := range application.Providers {
if providerItem.Provider == nil || providerItem.Provider.Category != "Captcha" {
continue
}
// For "None" rule, skip CAPTCHA
if providerItem.Rule == "None" || providerItem.Rule == "" {
shouldSkipCaptcha = true
} else if providerItem.Rule == "Internet-Only" {
// For Internet-Only rule, check if the client is from intranet
if !util.IsInternetIp(clientIp) {
// Client is from intranet, skip CAPTCHA
shouldSkipCaptcha = true
}
}
break // Only check the first CAPTCHA provider
}
if shouldSkipCaptcha {
c.ResponseOk(Captcha{Type: "none"})
return
}
}
captchaProvider, err := object.GetCaptchaProviderByApplication(applicationId, isCurrentProvider, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
@@ -317,15 +759,22 @@ func (c *ApiController) GetCaptcha() {
if captchaProvider != nil {
if captchaProvider.Type == "Default" {
id, img := object.GetCaptcha()
c.ResponseOk(Captcha{Type: captchaProvider.Type, CaptchaId: id, CaptchaImage: img})
id, img, err := object.GetCaptcha()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(Captcha{Owner: captchaProvider.Owner, Name: captchaProvider.Name, Type: captchaProvider.Type, CaptchaId: id, CaptchaImage: img})
return
} else if captchaProvider.Type != "" {
c.ResponseOk(Captcha{
Owner: captchaProvider.Owner,
Name: captchaProvider.Name,
Type: captchaProvider.Type,
SubType: captchaProvider.SubType,
ClientId: captchaProvider.ClientId,
ClientSecret: captchaProvider.ClientSecret,
ClientSecret: "***",
ClientId2: captchaProvider.ClientId2,
ClientSecret2: captchaProvider.ClientSecret2,
})
@@ -335,3 +784,24 @@ func (c *ApiController) GetCaptcha() {
c.ResponseOk(Captcha{Type: "none"})
}
func (c *ApiController) deleteUserSession(user string) error {
owner, username, err := util.GetOwnerAndNameFromIdWithError(user)
if err != nil {
return err
}
// Casdoor session ID derived from owner, username, and application
sessionId := util.GetSessionId(owner, username, object.CasdoorApplication)
// Explicitly get the Beego session ID from the context
beegoSessionId := c.Ctx.Input.CruSession.SessionID(context.Background())
_, err = object.DeleteSessionId(sessionId, beegoSessionId)
if err != nil {
return err
}
util.LogInfo(c.Ctx, "API: [%s] logged out", user)
return nil
}

145
controllers/adapter.go Normal file
View File

@@ -0,0 +1,145 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetAdapters
// @Title GetAdapters
// @Tag Adapter API
// @Description get adapters
// @Param owner query string true "The owner of adapters"
// @Success 200 {array} object.Adapter The Response object
// @router /get-adapters [get]
func (c *ApiController) GetAdapters() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
adapters, err := object.GetAdapters(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(adapters)
} else {
limit := util.ParseInt(limit)
count, err := object.GetAdapterCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
adapters, err := object.GetPaginationAdapters(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(adapters, paginator.Nums())
}
}
// GetAdapter
// @Title GetAdapter
// @Tag Adapter API
// @Description get adapter
// @Param id query string true "The id ( owner/name ) of the adapter"
// @Success 200 {object} object.Adapter The Response object
// @router /get-adapter [get]
func (c *ApiController) GetAdapter() {
id := c.Ctx.Input.Query("id")
adapter, err := object.GetAdapter(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(adapter)
}
// UpdateAdapter
// @Title UpdateAdapter
// @Tag Adapter API
// @Description update adapter
// @Param id query string true "The id ( owner/name ) of the adapter"
// @Param body body object.Adapter true "The details of the adapter"
// @Success 200 {object} controllers.Response The Response object
// @router /update-adapter [post]
func (c *ApiController) UpdateAdapter() {
id := c.Ctx.Input.Query("id")
var adapter object.Adapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &adapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateAdapter(id, &adapter))
c.ServeJSON()
}
// AddAdapter
// @Title AddAdapter
// @Tag Adapter API
// @Description add adapter
// @Param body body object.Adapter true "The details of the adapter"
// @Success 200 {object} controllers.Response The Response object
// @router /add-adapter [post]
func (c *ApiController) AddAdapter() {
var adapter object.Adapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &adapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddAdapter(&adapter))
c.ServeJSON()
}
// DeleteAdapter
// @Title DeleteAdapter
// @Tag Adapter API
// @Description delete adapter
// @Param body body object.Adapter true "The details of the adapter"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-adapter [post]
func (c *ApiController) DeleteAdapter() {
var adapter object.Adapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &adapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteAdapter(&adapter))
c.ServeJSON()
}

149
controllers/agent.go Normal file
View File

@@ -0,0 +1,149 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/server/web/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetAgents
// @Title GetAgents
// @Tag Agent API
// @Description get agents
// @Param owner query string true "The owner of agents"
// @Success 200 {array} object.Agent The Response object
// @router /get-agents [get]
func (c *ApiController) GetAgents() {
owner := c.Ctx.Input.Query("owner")
if owner == "admin" {
owner = ""
}
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
agents, err := object.GetAgents(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(agents)
return
}
limitInt := util.ParseInt(limit)
count, err := object.GetAgentCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limitInt, count)
agents, err := object.GetPaginationAgents(owner, paginator.Offset(), limitInt, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(agents, paginator.Nums())
}
// GetAgent
// @Title GetAgent
// @Tag Agent API
// @Description get agent
// @Param id query string true "The id ( owner/name ) of the agent"
// @Success 200 {object} object.Agent The Response object
// @router /get-agent [get]
func (c *ApiController) GetAgent() {
id := c.Ctx.Input.Query("id")
agent, err := object.GetAgent(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(agent)
}
// UpdateAgent
// @Title UpdateAgent
// @Tag Agent API
// @Description update agent
// @Param id query string true "The id ( owner/name ) of the agent"
// @Param body body object.Agent true "The details of the agent"
// @Success 200 {object} controllers.Response The Response object
// @router /update-agent [post]
func (c *ApiController) UpdateAgent() {
id := c.Ctx.Input.Query("id")
var agent object.Agent
err := json.Unmarshal(c.Ctx.Input.RequestBody, &agent)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateAgent(id, &agent))
c.ServeJSON()
}
// AddAgent
// @Title AddAgent
// @Tag Agent API
// @Description add agent
// @Param body body object.Agent true "The details of the agent"
// @Success 200 {object} controllers.Response The Response object
// @router /add-agent [post]
func (c *ApiController) AddAgent() {
var agent object.Agent
err := json.Unmarshal(c.Ctx.Input.RequestBody, &agent)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddAgent(&agent))
c.ServeJSON()
}
// DeleteAgent
// @Title DeleteAgent
// @Tag Agent API
// @Description delete agent
// @Param body body object.Agent true "The details of the agent"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-agent [post]
func (c *ApiController) DeleteAgent() {
var agent object.Agent
err := json.Unmarshal(c.Ctx.Input.RequestBody, &agent)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteAgent(&agent))
c.ServeJSON()
}

View File

@@ -18,7 +18,7 @@ import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -32,29 +32,43 @@ import (
// @router /get-applications [get]
func (c *ApiController) GetApplications() {
userId := c.GetSessionUsername()
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
organization := c.Input().Get("organization")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
organization := c.Ctx.Input.Query("organization")
var err error
if limit == "" || page == "" {
var applications []*object.Application
if organization == "" {
applications = object.GetApplications(owner)
applications, err = object.GetApplications(owner)
} else {
applications = object.GetApplicationsByOrganizationName(owner, organization)
applications, err = object.GetOrganizationApplications(owner, organization)
}
c.Data["json"] = object.GetMaskedApplications(applications, userId)
c.ServeJSON()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedApplications(applications, userId))
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetApplicationCount(owner, field, value)))
applications := object.GetMaskedApplications(object.GetPaginationApplications(owner, paginator.Offset(), limit, field, value, sortField, sortOrder), userId)
count, err := object.GetApplicationCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
application, err := object.GetPaginationApplications(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
applications := object.GetMaskedApplications(application, userId)
c.ResponseOk(applications, paginator.Nums())
}
}
@@ -63,35 +77,77 @@ func (c *ApiController) GetApplications() {
// @Title GetApplication
// @Tag Application API
// @Description get the detail of an application
// @Param id query string true "The id of the application."
// @Param id query string true "The id ( owner/name ) of the application."
// @Success 200 {object} object.Application The Response object
// @router /get-application [get]
func (c *ApiController) GetApplication() {
userId := c.GetSessionUsername()
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetMaskedApplication(object.GetApplication(id), userId)
c.ServeJSON()
application, err := object.GetApplication(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if c.Ctx.Input.Query("withKey") != "" && application != nil && application.Cert != "" {
cert, err := object.GetCert(util.GetId(application.Owner, application.Cert))
if err != nil {
c.ResponseError(err.Error())
return
}
if cert == nil {
cert, err = object.GetCert(util.GetId(application.Organization, application.Cert))
if err != nil {
c.ResponseError(err.Error())
return
}
}
if cert != nil {
application.CertPublicKey = cert.Certificate
}
}
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
object.CheckEntryIp(clientIp, nil, application, nil, c.GetAcceptLanguage())
c.ResponseOk(object.GetMaskedApplication(application, userId))
}
// GetUserApplication
// @Title GetUserApplication
// @Tag Application API
// @Description get the detail of the user's application
// @Param id query string true "The id of the user"
// @Param id query string true "The id ( owner/name ) of the user"
// @Success 200 {object} object.Application The Response object
// @router /get-user-application [get]
func (c *ApiController) GetUserApplication() {
userId := c.GetSessionUsername()
id := c.Input().Get("id")
user := object.GetUser(id)
id := c.Ctx.Input.Query("id")
user, err := object.GetUser(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", id))
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), id))
return
}
c.Data["json"] = object.GetMaskedApplication(object.GetApplicationByUser(user), userId)
c.ServeJSON()
application, err := object.GetApplicationByUser(user)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The organization: %s should have one application at least"), user.Owner))
return
}
c.ResponseOk(object.GetMaskedApplication(application, userId))
}
// GetOrganizationApplications
@@ -103,29 +159,71 @@ func (c *ApiController) GetUserApplication() {
// @router /get-organization-applications [get]
func (c *ApiController) GetOrganizationApplications() {
userId := c.GetSessionUsername()
owner := c.Input().Get("owner")
organization := c.Input().Get("organization")
organization := c.Ctx.Input.Query("organization")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if organization == "" {
c.ResponseError("Parameter organization is missing")
c.ResponseError(c.T("general:Missing parameter") + ": organization")
return
}
applications := object.GetApplicationsByOrganizationName(owner, organization)
c.Data["json"] = object.GetMaskedApplications(applications, userId)
c.ServeJSON()
if limit == "" || page == "" {
applications, err := object.GetOrganizationApplications(owner, organization)
if err != nil {
c.ResponseError(err.Error())
return
}
applications, err = object.GetAllowedApplications(applications, userId, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedApplications(applications, userId))
} else {
limit := util.ParseInt(limit)
count, err := object.GetOrganizationApplicationCount(owner, organization, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
applications, err := object.GetPaginationOrganizationApplications(owner, organization, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
applications, err = object.GetAllowedApplications(applications, userId, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
applications = object.GetMaskedApplications(applications, userId)
c.ResponseOk(applications, paginator.Nums())
}
}
// UpdateApplication
// @Title UpdateApplication
// @Tag Application API
// @Description update an application
// @Param id query string true "The id of the application"
// @Param id query string true "The id ( owner/name ) of the application"
// @Param body body object.Application true "The details of the application"
// @Success 200 {object} controllers.Response The Response object
// @router /update-application [post]
func (c *ApiController) UpdateApplication() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var application object.Application
err := json.Unmarshal(c.Ctx.Input.RequestBody, &application)
@@ -134,7 +232,12 @@ func (c *ApiController) UpdateApplication() {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateApplication(id, &application))
if err = object.CheckIpWhitelist(application.IpWhitelist, c.GetAcceptLanguage()); err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateApplication(id, &application, c.IsGlobalAdmin(), c.GetAcceptLanguage()))
c.ServeJSON()
}
@@ -153,6 +256,22 @@ func (c *ApiController) AddApplication() {
return
}
count, err := object.GetApplicationCount("", "", "")
if err != nil {
c.ResponseError(err.Error())
return
}
if err := checkQuotaForApplication(int(count)); err != nil {
c.ResponseError(err.Error())
return
}
if err = object.CheckIpWhitelist(application.IpWhitelist, c.GetAcceptLanguage()); err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddApplication(&application))
c.ServeJSON()
}

File diff suppressed because it is too large Load Diff

View File

@@ -15,11 +15,13 @@
package controllers
import (
"context"
"strings"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/casdoor/casdoor/mcpself"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -27,7 +29,7 @@ import (
// ApiController
// controller for handlers under /api uri
type ApiController struct {
beego.Controller
web.Controller
}
// RootController
@@ -41,30 +43,83 @@ type SessionData struct {
}
func (c *ApiController) IsGlobalAdmin() bool {
username := c.GetSessionUsername()
if strings.HasPrefix(username, "app/") {
// e.g., "app/app-casnode"
return true
}
isGlobalAdmin, _ := c.isGlobalAdmin()
user := object.GetUser(username)
if user == nil {
return isGlobalAdmin
}
func (c *ApiController) IsAdmin() bool {
isGlobalAdmin, user := c.isGlobalAdmin()
if !isGlobalAdmin && user == nil {
return false
}
return user.Owner == "built-in" || user.IsGlobalAdmin
return isGlobalAdmin || user.IsAdmin
}
func (c *ApiController) IsAdminOrSelf(user2 *object.User) bool {
isGlobalAdmin, user := c.isGlobalAdmin()
if isGlobalAdmin || (user != nil && user.IsAdmin) {
return true
}
if user == nil || user2 == nil {
return false
}
if user.Owner == user2.Owner && user.Name == user2.Name {
return true
}
return false
}
func (c *ApiController) isGlobalAdmin() (bool, *object.User) {
username := c.GetSessionUsername()
if object.IsAppUser(username) {
// e.g., "app/app-casnode"
return true, nil
}
user := c.getCurrentUser()
if user == nil {
return false, nil
}
return user.IsGlobalAdmin(), user
}
func (c *ApiController) getCurrentUser() *object.User {
var user *object.User
var err error
userId := c.GetSessionUsername()
if userId == "" {
user = nil
} else {
user, err = object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return nil
}
}
return user
}
// GetSessionUsername ...
func (c *ApiController) GetSessionUsername() string {
// prefer username stored in Beego context by ApiFilter
if ctxUser := c.Ctx.Input.GetData("currentUserId"); ctxUser != nil {
if username, ok := ctxUser.(string); ok {
return username
}
}
// check if user session expired
sessionData := c.GetSessionData()
if sessionData != nil &&
sessionData.ExpireTime != 0 &&
sessionData.ExpireTime < time.Now().Unix() {
c.SetSessionUsername("")
c.SetSessionData(nil)
c.ClearUserSession()
return ""
}
@@ -76,22 +131,65 @@ func (c *ApiController) GetSessionUsername() string {
return user.(string)
}
// GetPaidUsername ...
func (c *ApiController) GetPaidUsername() string {
// check if user session expired
sessionData := c.GetSessionData()
if sessionData != nil &&
sessionData.ExpireTime != 0 &&
sessionData.ExpireTime < time.Now().Unix() {
c.ClearUserSession()
return ""
}
user := c.GetSession("paidUsername")
if user == nil {
return ""
}
return user.(string)
}
func (c *ApiController) GetSessionToken() string {
accessToken := c.GetSession("accessToken")
if accessToken == nil {
return ""
}
return accessToken.(string)
}
func (c *ApiController) GetSessionApplication() *object.Application {
clientId := c.GetSession("aud")
if clientId == nil {
return nil
}
application := object.GetApplicationByClientId(clientId.(string))
application, err := object.GetApplicationByClientId(clientId.(string))
if err != nil {
c.ResponseError(err.Error())
return nil
}
return application
}
func (c *ApiController) ClearUserSession() {
c.SetSessionUsername("")
c.SetSessionData(nil)
_ = c.SessionRegenerateID()
}
func (c *ApiController) ClearTokenSession() {
c.SetSessionToken("")
}
func (c *ApiController) GetSessionOidc() (string, string) {
sessionData := c.GetSessionData()
if sessionData != nil &&
sessionData.ExpireTime != 0 &&
sessionData.ExpireTime < time.Now().Unix() {
c.SetSessionUsername("")
c.SetSessionData(nil)
c.ClearUserSession()
return "", ""
}
scopeValue := c.GetSession("scope")
@@ -112,6 +210,10 @@ func (c *ApiController) SetSessionUsername(user string) {
c.SetSession("username", user)
}
func (c *ApiController) SetSessionToken(accessToken string) {
c.SetSession("accessToken", accessToken)
}
// GetSessionData ...
func (c *ApiController) GetSessionData() *SessionData {
session := c.GetSession("SessionData")
@@ -139,8 +241,33 @@ func (c *ApiController) SetSessionData(s *SessionData) {
c.SetSession("SessionData", util.StructToJson(s))
}
func wrapActionResponse(affected bool) *Response {
if affected {
func (c *ApiController) setMfaUserSession(userId string) {
c.SetSession(object.MfaSessionUserId, userId)
}
func (c *ApiController) getMfaUserSession() string {
userId := c.Ctx.Input.CruSession.Get(context.Background(), object.MfaSessionUserId)
if userId == nil {
return ""
}
return userId.(string)
}
func (c *ApiController) setExpireForSession(cookieExpireInHours int64) {
timestamp := time.Now().Unix()
if cookieExpireInHours == 0 {
cookieExpireInHours = 720
}
timestamp += 3600 * cookieExpireInHours
c.SetSessionData(&SessionData{
ExpireTime: timestamp,
})
}
func wrapActionResponse(affected bool, e ...error) *Response {
if len(e) != 0 && e[0] != nil {
return &Response{Status: "error", Msg: e[0].Error()}
} else if affected {
return &Response{Status: "ok", Msg: "", Data: "Affected"}
} else {
return &Response{Status: "ok", Msg: "", Data: "Unaffected"}
@@ -154,3 +281,25 @@ func wrapErrorResponse(err error) *Response {
return &Response{Status: "error", Msg: err.Error()}
}
}
func (c *ApiController) Finish() {
if strings.HasPrefix(c.Ctx.Input.URL(), "/api") {
startTime := c.Ctx.Input.GetData("startTime")
if startTime != nil {
latency := time.Since(startTime.(time.Time)).Milliseconds()
object.ApiLatency.WithLabelValues(c.Ctx.Input.URL(), c.Ctx.Input.Method()).Observe(float64(latency))
}
}
c.Controller.Finish()
}
func (c *ApiController) McpResponseError(id interface{}, code int, message string, data interface{}) {
resp := mcpself.BuildMcpResponse(id, nil, &mcpself.McpError{
Code: code,
Message: message,
Data: data,
})
c.Ctx.Output.Header("Content-Type", "application/json")
c.Data["json"] = resp
c.ServeJSON()
}

View File

@@ -35,9 +35,14 @@ const (
UnauthorizedService string = "UNAUTHORIZED_SERVICE"
)
func queryUnescape(service string) string {
s, _ := url.QueryUnescape(service)
return s
}
func (c *RootController) CasValidate() {
ticket := c.Input().Get("ticket")
service := c.Input().Get("service")
ticket := c.Ctx.Input.Query("ticket")
service := c.Ctx.Input.Query("service")
c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
if service == "" || ticket == "" {
c.Ctx.Output.Body([]byte("no\n"))
@@ -55,28 +60,34 @@ func (c *RootController) CasValidate() {
}
func (c *RootController) CasServiceValidate() {
ticket := c.Input().Get("ticket")
format := c.Input().Get("format")
ticket := c.Ctx.Input.Query("ticket")
format := c.Ctx.Input.Query("format")
if !strings.HasPrefix(ticket, "ST") {
c.sendCasAuthenticationResponseErr(InvalidTicket, fmt.Sprintf("Ticket %s not recognized", ticket), format)
}
c.CasP3ServiceAndProxyValidate()
c.CasP3ProxyValidate()
}
func (c *RootController) CasProxyValidate() {
ticket := c.Input().Get("ticket")
format := c.Input().Get("format")
if !strings.HasPrefix(ticket, "PT") {
c.sendCasAuthenticationResponseErr(InvalidTicket, fmt.Sprintf("Ticket %s not recognized", ticket), format)
}
c.CasP3ServiceAndProxyValidate()
// https://apereo.github.io/cas/6.6.x/protocol/CAS-Protocol-Specification.html#26-proxyvalidate-cas-20
// "/proxyValidate" should accept both service tickets and proxy tickets.
c.CasP3ProxyValidate()
}
func (c *RootController) CasP3ServiceAndProxyValidate() {
ticket := c.Input().Get("ticket")
format := c.Input().Get("format")
service := c.Input().Get("service")
pgtUrl := c.Input().Get("pgtUrl")
func (c *RootController) CasP3ServiceValidate() {
ticket := c.Ctx.Input.Query("ticket")
format := c.Ctx.Input.Query("format")
if !strings.HasPrefix(ticket, "ST") {
c.sendCasAuthenticationResponseErr(InvalidTicket, fmt.Sprintf("Ticket %s not recognized", ticket), format)
}
c.CasP3ProxyValidate()
}
func (c *RootController) CasP3ProxyValidate() {
ticket := c.Ctx.Input.Query("ticket")
format := c.Ctx.Input.Query("format")
service := c.Ctx.Input.Query("service")
pgtUrl := c.Ctx.Input.Query("pgtUrl")
serviceResponse := object.CasServiceResponse{
Xmlns: "http://www.yale.edu/tp/cas",
@@ -91,7 +102,7 @@ func (c *RootController) CasP3ServiceAndProxyValidate() {
// find the token
if ok {
// check whether service is the one for which we previously issued token
if strings.HasPrefix(service, issuedService) {
if strings.HasPrefix(service, issuedService) || strings.HasPrefix(queryUnescape(service), issuedService) {
serviceResponse.Success = response
} else {
// service not match
@@ -110,15 +121,17 @@ func (c *RootController) CasP3ServiceAndProxyValidate() {
pgtiou := serviceResponse.Success.ProxyGrantingTicket
// todo: check whether it is https
pgtUrlObj, err := url.Parse(pgtUrl)
if err != nil {
c.sendCasAuthenticationResponseErr(InvalidProxyCallback, err.Error(), format)
return
}
if pgtUrlObj.Scheme != "https" {
c.sendCasAuthenticationResponseErr(InvalidProxyCallback, "callback is not https", format)
return
}
// make a request to pgturl passing pgt and pgtiou
if err != nil {
c.sendCasAuthenticationResponseErr(InternalError, err.Error(), format)
return
}
param := pgtUrlObj.Query()
param.Add("pgtId", pgt)
param.Add("pgtIou", pgtiou)
@@ -148,9 +161,9 @@ func (c *RootController) CasP3ServiceAndProxyValidate() {
}
func (c *RootController) CasProxy() {
pgt := c.Input().Get("pgt")
targetService := c.Input().Get("targetService")
format := c.Input().Get("format")
pgt := c.Ctx.Input.Query("pgt")
targetService := c.Ctx.Input.Query("targetService")
format := c.Ctx.Input.Query("format")
if pgt == "" || targetService == "" {
c.sendCasProxyResponseErr(InvalidRequest, "pgt and targetService must exist", format)
return
@@ -187,7 +200,7 @@ func (c *RootController) CasProxy() {
func (c *RootController) SamlValidate() {
c.Ctx.Output.Header("Content-Type", "text/xml; charset=utf-8")
target := c.Input().Get("TARGET")
target := c.Ctx.Input.Query("TARGET")
body := c.Ctx.Input.RequestBody
envelopRequest := struct {
XMLName xml.Name `xml:"Envelope"`
@@ -210,7 +223,7 @@ func (c *RootController) SamlValidate() {
}
if !strings.HasPrefix(target, service) {
c.ResponseError(fmt.Sprintf("service %s and %s do not match", target, service))
c.ResponseError(fmt.Sprintf(c.T("cas:Service %s and %s do not match"), target, service))
return
}
@@ -258,7 +271,6 @@ func (c *RootController) sendCasAuthenticationResponseErr(code, msg, format stri
Message: msg,
},
}
if format == "json" {
c.Data["json"] = serviceResponse
c.ServeJSON()

View File

@@ -1,94 +0,0 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
func (c *ApiController) GetCasbinAdapters() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetCasbinAdapters(owner)
c.ServeJSON()
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetCasbinAdapterCount(owner, field, value)))
adapters := object.GetPaginationCasbinAdapters(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
c.ResponseOk(adapters, paginator.Nums())
}
}
func (c *ApiController) GetCasbinAdapter() {
id := c.Input().Get("id")
c.Data["json"] = object.GetCasbinAdapter(id)
c.ServeJSON()
}
func (c *ApiController) UpdateCasbinAdapter() {
id := c.Input().Get("id")
var casbinAdapter object.CasbinAdapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &casbinAdapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateCasbinAdapter(id, &casbinAdapter))
c.ServeJSON()
}
func (c *ApiController) AddCasbinAdapter() {
var casbinAdapter object.CasbinAdapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &casbinAdapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddCasbinAdapter(&casbinAdapter))
c.ServeJSON()
}
func (c *ApiController) DeleteCasbinAdapter() {
var casbinAdapter object.CasbinAdapter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &casbinAdapter)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteCasbinAdapter(&casbinAdapter))
c.ServeJSON()
}
func (c *ApiController) SyncPolicies() {
id := c.Input().Get("id")
adapter := object.GetCasbinAdapter(id)
c.Data["json"] = object.SyncPolicies(adapter)
c.ServeJSON()
}

385
controllers/casbin_api.go Normal file
View File

@@ -0,0 +1,385 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// Enforce
// @Title Enforce
// @Tag Enforcer API
// @Description Call Casbin Enforce API
// @Param body body []string true "Casbin request"
// @Param permissionId query string false "permission id"
// @Param modelId query string false "model id"
// @Param resourceId query string false "resource id"
// @Param owner query string false "owner"
// @Success 200 {object} controllers.Response The Response object
// @router /enforce [post]
func (c *ApiController) Enforce() {
permissionId := c.Ctx.Input.Query("permissionId")
modelId := c.Ctx.Input.Query("modelId")
resourceId := c.Ctx.Input.Query("resourceId")
enforcerId := c.Ctx.Input.Query("enforcerId")
owner := c.Ctx.Input.Query("owner")
params := []string{permissionId, modelId, resourceId, enforcerId, owner}
nonEmpty := 0
for _, param := range params {
if param != "" {
nonEmpty++
}
}
if nonEmpty > 1 {
c.ResponseError("Only one of the parameters (permissionId, modelId, resourceId, enforcerId, owner) should be provided")
return
}
if len(c.Ctx.Input.RequestBody) == 0 {
c.ResponseError("The request body should not be empty")
return
}
// Accept both plain string arrays (["alice","data1","read"]) and mixed arrays
// with JSON objects ([{"DivisionGuid":"x"}, "resource", "read"]) for ABAC support.
var request []interface{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &request)
if err != nil {
c.ResponseError(err.Error())
return
}
if enforcerId != "" {
enforcer, err := object.GetInitializedEnforcer(enforcerId)
if err != nil {
c.ResponseError(err.Error())
return
}
res := []bool{}
keyRes := []string{}
// Convert elements: JSON-object strings and maps become anonymous structs for ABAC.
interfaceRequest := util.InterfaceToEnforceArray(request)
enforceResult, err := enforcer.Enforce(interfaceRequest...)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, enforcer.GetModelAndAdapter())
c.ResponseOk(res, keyRes)
return
}
if permissionId != "" {
permission, err := object.GetPermission(permissionId)
if err != nil {
c.ResponseError(err.Error())
return
}
if permission == nil {
c.ResponseError(fmt.Sprintf(c.T("permission:The permission: \"%s\" doesn't exist"), permissionId))
return
}
res := []bool{}
keyRes := []string{}
enforceResult, err := object.Enforce(permission, request)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, permission.GetModelAndAdapter())
c.ResponseOk(res, keyRes)
return
}
permissions := []*object.Permission{}
if modelId != "" {
owner, modelName, err := util.GetOwnerAndNameFromIdWithError(modelId)
if err != nil {
c.ResponseError(err.Error())
return
}
permissions, err = object.GetPermissionsByModel(owner, modelName)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if resourceId != "" {
permissions, err = object.GetPermissionsByResource(resourceId)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if owner != "" {
permissions, err = object.GetPermissions(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
} else {
c.ResponseError(c.T("general:Missing parameter"))
return
}
res := []bool{}
keyRes := []string{}
listPermissionIdMap := object.GroupPermissionsByModelAdapter(permissions)
for key, permissionIds := range listPermissionIdMap {
firstPermission, err := object.GetPermission(permissionIds[0])
if err != nil {
c.ResponseError(err.Error())
return
}
enforceResult, err := object.Enforce(firstPermission, request, permissionIds...)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, key)
}
c.ResponseOk(res, keyRes)
}
// BatchEnforce
// @Title BatchEnforce
// @Tag Enforcer API
// @Description Call Casbin BatchEnforce API
// @Param body body []string true "array of casbin requests"
// @Param permissionId query string false "permission id"
// @Param modelId query string false "model id"
// @Param owner query string false "owner"
// @Success 200 {object} controllers.Response The Response object
// @router /batch-enforce [post]
func (c *ApiController) BatchEnforce() {
permissionId := c.Ctx.Input.Query("permissionId")
modelId := c.Ctx.Input.Query("modelId")
enforcerId := c.Ctx.Input.Query("enforcerId")
owner := c.Ctx.Input.Query("owner")
params := []string{permissionId, modelId, enforcerId, owner}
nonEmpty := 0
for _, param := range params {
if param != "" {
nonEmpty++
}
}
if nonEmpty > 1 {
c.ResponseError("Only one of the parameters (permissionId, modelId, enforcerId, owner) should be provided")
return
}
// Accept both string arrays and mixed arrays with JSON objects for ABAC support.
var requests [][]interface{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &requests)
if err != nil {
c.ResponseError(err.Error())
return
}
if enforcerId != "" {
enforcer, err := object.GetInitializedEnforcer(enforcerId)
if err != nil {
c.ResponseError(err.Error())
return
}
res := [][]bool{}
keyRes := []string{}
// Convert elements: JSON-object strings and maps become anonymous structs for ABAC.
interfaceRequests := util.InterfaceToEnforceArray2d(requests)
enforceResult, err := enforcer.BatchEnforce(interfaceRequests)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, enforcer.GetModelAndAdapter())
c.ResponseOk(res, keyRes)
return
}
if permissionId != "" {
permission, err := object.GetPermission(permissionId)
if err != nil {
c.ResponseError(err.Error())
return
}
if permission == nil {
c.ResponseError(fmt.Sprintf(c.T("permission:The permission: \"%s\" doesn't exist"), permissionId))
return
}
res := [][]bool{}
keyRes := []string{}
enforceResult, err := object.BatchEnforce(permission, requests)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, permission.GetModelAndAdapter())
c.ResponseOk(res, keyRes)
return
}
permissions := []*object.Permission{}
if modelId != "" {
owner, modelName, err := util.GetOwnerAndNameFromIdWithError(modelId)
if err != nil {
c.ResponseError(err.Error())
return
}
permissions, err = object.GetPermissionsByModel(owner, modelName)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if owner != "" {
permissions, err = object.GetPermissions(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
} else {
c.ResponseError(c.T("general:Missing parameter"))
return
}
res := [][]bool{}
keyRes := []string{}
listPermissionIdMap := object.GroupPermissionsByModelAdapter(permissions)
for _, permissionIds := range listPermissionIdMap {
firstPermission, err := object.GetPermission(permissionIds[0])
if err != nil {
c.ResponseError(err.Error())
return
}
enforceResult, err := object.BatchEnforce(firstPermission, requests, permissionIds...)
if err != nil {
c.ResponseError(err.Error())
return
}
res = append(res, enforceResult)
keyRes = append(keyRes, firstPermission.GetModelAndAdapter())
}
c.ResponseOk(res, keyRes)
}
// GetAllObjects
// @Title GetAllObjects
// @Tag Enforcer API
// @Description Get all objects for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-objects [get]
func (c *ApiController) GetAllObjects() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {
userId = c.GetSessionUsername()
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
}
objects, err := object.GetAllObjects(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(objects)
}
// GetAllActions
// @Title GetAllActions
// @Tag Enforcer API
// @Description Get all actions for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-actions [get]
func (c *ApiController) GetAllActions() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {
userId = c.GetSessionUsername()
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
}
actions, err := object.GetAllActions(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(actions)
}
// GetAllRoles
// @Title GetAllRoles
// @Tag Enforcer API
// @Description Get all roles for a user (Casbin API)
// @Param userId query string false "user id like built-in/admin"
// @Success 200 {object} controllers.Response The Response object
// @router /get-all-roles [get]
func (c *ApiController) GetAllRoles() {
userId := c.Ctx.Input.Query("userId")
if userId == "" {
userId = c.GetSessionUsername()
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
}
roles, err := object.GetAllRoles(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(roles)
}

View File

@@ -0,0 +1,319 @@
// Copyright 2024 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/casdoor/casdoor/conf"
)
type CLIVersionInfo struct {
Version string
BinaryPath string
BinaryTime time.Time
}
var (
cliVersionCache = make(map[string]*CLIVersionInfo)
cliVersionMutex sync.RWMutex
)
// cleanOldMEIFolders cleans up old _MEIXXX folders from the Casdoor temp directory
// that are older than 24 hours. These folders are created by PyInstaller when
// executing casbin-python-cli and can accumulate over time.
func cleanOldMEIFolders() {
tempDir := "temp"
cutoffTime := time.Now().Add(-24 * time.Hour)
entries, err := os.ReadDir(tempDir)
if err != nil {
// Log error but don't fail - cleanup is best-effort
// This is expected if temp directory doesn't exist yet
return
}
for _, entry := range entries {
// Check if the entry is a directory and matches the _MEI pattern
if !entry.IsDir() || !strings.HasPrefix(entry.Name(), "_MEI") {
continue
}
dirPath := filepath.Join(tempDir, entry.Name())
info, err := entry.Info()
if err != nil {
continue
}
// Check if the folder is older than 24 hours
if info.ModTime().Before(cutoffTime) {
// Try to remove the directory
err = os.RemoveAll(dirPath)
if err != nil {
// Log but continue with other folders
fmt.Printf("failed to remove old MEI folder %s: %v\n", dirPath, err)
} else {
fmt.Printf("removed old MEI folder: %s\n", dirPath)
}
}
}
}
// getCLIVersion
// @Title getCLIVersion
// @Description Get CLI version with cache mechanism
// @Param language string The language of CLI (go/java/rust etc.)
// @Return string The version string of CLI
// @Return error Error if CLI execution fails
func getCLIVersion(language string) (string, error) {
binaryName := fmt.Sprintf("casbin-%s-cli", language)
binaryPath, err := exec.LookPath(binaryName)
if err != nil {
return "", fmt.Errorf("executable file not found: %v", err)
}
fileInfo, err := os.Stat(binaryPath)
if err != nil {
return "", fmt.Errorf("failed to get binary info: %v", err)
}
cliVersionMutex.RLock()
if info, exists := cliVersionCache[language]; exists {
if info.BinaryPath == binaryPath && info.BinaryTime == fileInfo.ModTime() {
cliVersionMutex.RUnlock()
return info.Version, nil
}
}
cliVersionMutex.RUnlock()
// Clean up old _MEI folders before running the command
cleanOldMEIFolders()
cmd := exec.Command(binaryName, "--version")
output, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("failed to get CLI version: %v", err)
}
version := strings.TrimSpace(string(output))
cliVersionMutex.Lock()
cliVersionCache[language] = &CLIVersionInfo{
Version: version,
BinaryPath: binaryPath,
BinaryTime: fileInfo.ModTime(),
}
cliVersionMutex.Unlock()
return version, nil
}
func processArgsToTempFiles(args []string) ([]string, []string, error) {
tempFiles := []string{}
newArgs := []string{}
for i := 0; i < len(args); i++ {
if (args[i] == "-m" || args[i] == "-p") && i+1 < len(args) {
pattern := fmt.Sprintf("casbin_temp_%s_*.conf", args[i])
tempFile, err := os.CreateTemp("", pattern)
if err != nil {
return nil, nil, fmt.Errorf("failed to create temp file: %v", err)
}
_, err = tempFile.WriteString(args[i+1])
if err != nil {
tempFile.Close()
return nil, nil, fmt.Errorf("failed to write to temp file: %v", err)
}
tempFile.Close()
tempFiles = append(tempFiles, tempFile.Name())
newArgs = append(newArgs, args[i], tempFile.Name())
i++
} else {
newArgs = append(newArgs, args[i])
}
}
return tempFiles, newArgs, nil
}
// RunCasbinCommand
// @Title RunCasbinCommand
// @Tag Enforcer API
// @Description Call Casbin CLI commands
// @Success 200 {object} controllers.Response The Response object
// @router /run-casbin-command [get]
func (c *ApiController) RunCasbinCommand() {
if !conf.IsDemoMode() && !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
if err := validateIdentifier(c); err != nil {
c.ResponseError(err.Error())
return
}
language := c.Ctx.Input.Query("language")
argString := c.Ctx.Input.Query("args")
if language == "" {
language = "go"
}
// use "casbin-go-cli" by default, can be also "casbin-java-cli", "casbin-node-cli", etc.
// the pre-built binary of "casbin-go-cli" can be found at: https://github.com/casbin/casbin-go-cli/releases
binaryName := fmt.Sprintf("casbin-%s-cli", language)
_, err := exec.LookPath(binaryName)
if err != nil {
c.ResponseError(fmt.Sprintf("executable file: %s not found in PATH", binaryName))
return
}
// RBAC model & policy example:
// https://door.casdoor.com/api/run-casbin-command?language=go&args=["enforce", "-m", "[request_definition]\nr = sub, obj, act\n\n[policy_definition]\np = sub, obj, act\n\n[role_definition]\ng = _, _\n\n[policy_effect]\ne = some(where (p.eft == allow))\n\n[matchers]\nm = g(r.sub, p.sub) %26%26 r.obj == p.obj %26%26 r.act == p.act", "-p", "p, alice, data1, read\np, bob, data2, write\np, data2_admin, data2, read\np, data2_admin, data2, write\ng, alice, data2_admin", "alice", "data1", "read"]
// Casbin CLI usage:
// https://github.com/jcasbin/casbin-java-cli?tab=readme-ov-file#get-started
var args []string
err = json.Unmarshal([]byte(argString), &args)
if err != nil {
c.ResponseError(err.Error())
return
}
// Generate cache key for this command
cacheKey, err := generateCacheKey(language, args)
if err != nil {
c.ResponseError(err.Error())
return
}
// Check if result is cached
if cachedOutput, found := getCachedCommandResult(cacheKey); found {
c.ResponseOk(cachedOutput)
return
}
if len(args) > 0 && args[0] == "--version" {
version, err := getCLIVersion(language)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(version)
return
}
tempFiles, processedArgs, err := processArgsToTempFiles(args)
defer func() {
for _, file := range tempFiles {
os.Remove(file)
}
}()
if err != nil {
c.ResponseError(err.Error())
return
}
// Clean up old _MEI folders before running the command
// This is especially important for Python CLI which creates these folders
cleanOldMEIFolders()
command := exec.Command(binaryName, processedArgs...)
outputBytes, err := command.CombinedOutput()
if err != nil {
errorString := err.Error()
if outputBytes != nil {
output := string(outputBytes)
errorString = fmt.Sprintf("%s, error: %s", output, err.Error())
}
c.ResponseError(errorString)
return
}
output := string(outputBytes)
output = strings.TrimSuffix(output, "\n")
// Store result in cache
setCachedCommandResult(cacheKey, output)
c.ResponseOk(output)
}
// validateIdentifier
// @Title validateIdentifier
// @Description Validate the request hash and timestamp
// @Param hash string The SHA-256 hash string
// @Return error Returns error if validation fails, nil if successful
func validateIdentifier(c *ApiController) error {
language := c.Ctx.Input.Query("language")
args := c.Ctx.Input.Query("args")
hash := c.Ctx.Input.Query("m")
timestamp := c.Ctx.Input.Query("t")
if hash == "" || timestamp == "" || language == "" || args == "" {
return fmt.Errorf("invalid identifier")
}
requestTime, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
return fmt.Errorf("invalid identifier")
}
timeDiff := time.Since(requestTime)
if timeDiff > 5*time.Minute || timeDiff < -5*time.Minute {
return fmt.Errorf("invalid identifier")
}
params := map[string]string{
"language": language,
"args": args,
}
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var paramParts []string
for _, k := range keys {
paramParts = append(paramParts, fmt.Sprintf("%s=%s", k, params[k]))
}
paramString := strings.Join(paramParts, "&")
version := "casbin-editor-v1"
rawString := fmt.Sprintf("%s|%s|%s", version, timestamp, paramString)
hasher := sha256.New()
hasher.Write([]byte(rawString))
calculatedHash := strings.ToLower(hex.EncodeToString(hasher.Sum(nil)))
if calculatedHash != strings.ToLower(hash) {
return fmt.Errorf("invalid identifier")
}
return nil
}

View File

@@ -0,0 +1,100 @@
// Copyright 2024 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sync"
"time"
)
type CommandCacheEntry struct {
Output string
CachedTime time.Time
}
var (
commandCache = make(map[string]*CommandCacheEntry)
commandCacheMutex sync.RWMutex
cacheTTL = 5 * time.Minute
cleanupInProgress = false
cleanupMutex sync.Mutex
)
// generateCacheKey creates a unique cache key based on language and arguments
func generateCacheKey(language string, args []string) (string, error) {
argsJSON, err := json.Marshal(args)
if err != nil {
return "", fmt.Errorf("failed to marshal args: %v", err)
}
data := fmt.Sprintf("%s:%s", language, string(argsJSON))
hash := sha256.Sum256([]byte(data))
return hex.EncodeToString(hash[:]), nil
}
// cleanExpiredCacheEntries removes expired entries from the cache
func cleanExpiredCacheEntries() {
commandCacheMutex.Lock()
defer commandCacheMutex.Unlock()
for key, entry := range commandCache {
if time.Since(entry.CachedTime) >= cacheTTL {
delete(commandCache, key)
}
}
cleanupMutex.Lock()
cleanupInProgress = false
cleanupMutex.Unlock()
}
// getCachedCommandResult retrieves cached command result if available and not expired
func getCachedCommandResult(cacheKey string) (string, bool) {
commandCacheMutex.RLock()
defer commandCacheMutex.RUnlock()
if entry, exists := commandCache[cacheKey]; exists {
if time.Since(entry.CachedTime) < cacheTTL {
return entry.Output, true
}
}
return "", false
}
// setCachedCommandResult stores command result in cache and performs periodic cleanup
func setCachedCommandResult(cacheKey string, output string) {
commandCacheMutex.Lock()
commandCache[cacheKey] = &CommandCacheEntry{
Output: output,
CachedTime: time.Now(),
}
shouldCleanup := len(commandCache)%100 == 0
commandCacheMutex.Unlock()
// Periodically clean expired entries (every 100 cache sets)
if shouldCleanup {
cleanupMutex.Lock()
if !cleanupInProgress {
cleanupInProgress = true
cleanupMutex.Unlock()
go cleanExpiredCacheEntries()
} else {
cleanupMutex.Unlock()
}
}
}

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +30,78 @@ import (
// @Success 200 {array} object.Cert The Response object
// @router /get-certs [get]
func (c *ApiController) GetCerts() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetMaskedCerts(object.GetCerts(owner))
c.ServeJSON()
certs, err := object.GetMaskedCerts(object.GetCerts(owner))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(certs)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetCertCount(owner, field, value)))
certs := object.GetMaskedCerts(object.GetPaginationCerts(owner, paginator.Offset(), limit, field, value, sortField, sortOrder))
count, err := object.GetCertCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
certs, err := object.GetMaskedCerts(object.GetPaginationCerts(owner, paginator.Offset(), limit, field, value, sortField, sortOrder))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(certs, paginator.Nums())
}
}
// GetGlobalCerts
// @Title GetGlobalCerts
// @Tag Cert API
// @Description get global certs
// @Success 200 {array} object.Cert The Response object
// @router /get-global-certs [get]
func (c *ApiController) GetGlobalCerts() {
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
certs, err := object.GetMaskedCerts(object.GetGlobalCerts())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(certs)
} else {
limit := util.ParseInt(limit)
count, err := object.GetGlobalCertsCount(field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
certs, err := object.GetMaskedCerts(object.GetPaginationGlobalCerts(paginator.Offset(), limit, field, value, sortField, sortOrder))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(certs, paginator.Nums())
}
}
@@ -52,26 +110,30 @@ func (c *ApiController) GetCerts() {
// @Title GetCert
// @Tag Cert API
// @Description get cert
// @Param id query string true "The id of the cert"
// @Param id query string true "The id ( owner/name ) of the cert"
// @Success 200 {object} object.Cert The Response object
// @router /get-cert [get]
func (c *ApiController) GetCert() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
cert, err := object.GetCert(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.GetMaskedCert(object.GetCert(id))
c.ServeJSON()
c.ResponseOk(object.GetMaskedCert(cert))
}
// UpdateCert
// @Title UpdateCert
// @Tag Cert API
// @Description update cert
// @Param id query string true "The id of the cert"
// @Param id query string true "The id ( owner/name ) of the cert"
// @Param body body object.Cert true "The details of the cert"
// @Success 200 {object} controllers.Response The Response object
// @router /update-cert [post]
func (c *ApiController) UpdateCert() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var cert object.Cert
err := json.Unmarshal(c.Ctx.Input.RequestBody, &cert)
@@ -121,3 +183,40 @@ func (c *ApiController) DeleteCert() {
c.Data["json"] = wrapActionResponse(object.DeleteCert(&cert))
c.ServeJSON()
}
// UpdateCertDomainExpire
// @Title UpdateCertDomainExpire
// @Tag Cert API
// @Description update cert domain expire time
// @Param id query string true "The ID of the cert"
// @Success 200 {object} controllers.Response The Response object
// @router /update-cert-domain-expire [post]
func (c *ApiController) UpdateCertDomainExpire() {
if _, ok := c.RequireSignedIn(); !ok {
return
}
id := c.Ctx.Input.Query("id")
cert, err := object.GetCert(id)
if err != nil {
c.ResponseError(err.Error())
return
}
domainExpireTime, err := object.GetDomainExpireTime(cert.Name)
if err != nil {
c.ResponseError(err.Error())
return
}
if domainExpireTime == "" {
c.ResponseError("Failed to determine domain expiration time for domain " + cert.Name +
". Please verify that the domain is valid, publicly resolvable, and has a retrievable expiration date, " +
"or update the domain expiration time manually.")
return
}
cert.DomainExpireTime = domainExpireTime
c.Data["json"] = wrapActionResponse(object.UpdateCert(id, cert))
c.ServeJSON()
}

View File

@@ -0,0 +1,542 @@
package controllers
import (
"archive/tar"
"archive/zip"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/beego/beego/v2/server/web"
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/proxy"
"github.com/casdoor/casdoor/util"
)
const (
javaCliRepo = "https://api.github.com/repos/jcasbin/casbin-java-cli/releases/latest"
goCliRepo = "https://api.github.com/repos/casbin/casbin-go-cli/releases/latest"
rustCliRepo = "https://api.github.com/repos/casbin-rs/casbin-rust-cli/releases/latest"
pythonCliRepo = "https://api.github.com/repos/casbin/casbin-python-cli/releases/latest"
dotnetCliRepo = "https://api.github.com/repos/casbin-net/casbin-dotnet-cli/releases/latest"
downloadFolder = "bin"
)
type ReleaseInfo struct {
TagName string `json:"tag_name"`
Assets []struct {
Name string `json:"name"`
URL string `json:"browser_download_url"`
} `json:"assets"`
}
// @Title getBinaryNames
// @Description Get binary names for different platforms and architectures
// @Success 200 {map[string]string} map[string]string "Binary names map"
func getBinaryNames() map[string]string {
const (
golang = "go"
java = "java"
rust = "rust"
python = "python"
dotnet = "dotnet"
)
arch := runtime.GOARCH
archMap := map[string]struct{ goArch, rustArch string }{
"amd64": {"x86_64", "x86_64"},
"arm64": {"arm64", "aarch64"},
}
archNames, ok := archMap[arch]
if !ok {
archNames = struct{ goArch, rustArch string }{arch, arch}
}
switch runtime.GOOS {
case "windows":
return map[string]string{
golang: fmt.Sprintf("casbin-go-cli_Windows_%s.zip", archNames.goArch),
java: "casbin-java-cli.jar",
rust: fmt.Sprintf("casbin-rust-cli-%s-pc-windows-gnu", archNames.rustArch),
python: fmt.Sprintf("casbin-python-cli-windows-%s.exe", archNames.goArch),
dotnet: fmt.Sprintf("casbin-dotnet-cli-windows-%s.exe", archNames.goArch),
}
case "darwin":
return map[string]string{
golang: fmt.Sprintf("casbin-go-cli_Darwin_%s.tar.gz", archNames.goArch),
java: "casbin-java-cli.jar",
rust: fmt.Sprintf("casbin-rust-cli-%s-apple-darwin", archNames.rustArch),
python: fmt.Sprintf("casbin-python-cli-darwin-%s", archNames.goArch),
dotnet: fmt.Sprintf("casbin-dotnet-cli-darwin-%s", archNames.goArch),
}
case "linux":
return map[string]string{
golang: fmt.Sprintf("casbin-go-cli_Linux_%s.tar.gz", archNames.goArch),
java: "casbin-java-cli.jar",
rust: fmt.Sprintf("casbin-rust-cli-%s-unknown-linux-gnu", archNames.rustArch),
python: fmt.Sprintf("casbin-python-cli-linux-%s", archNames.goArch),
dotnet: fmt.Sprintf("casbin-dotnet-cli-linux-%s", archNames.goArch),
}
default:
return nil
}
}
// @Title getFinalBinaryName
// @Description Get final binary name for specific language
// @Param lang string true "Language type (go/java/rust)"
// @Success 200 {string} string "Final binary name"
func getFinalBinaryName(lang string) string {
switch lang {
case "go":
if runtime.GOOS == "windows" {
return "casbin-go-cli.exe"
}
return "casbin-go-cli"
case "java":
return "casbin-java-cli.jar"
case "rust":
if runtime.GOOS == "windows" {
return "casbin-rust-cli.exe"
}
return "casbin-rust-cli"
case "python":
if runtime.GOOS == "windows" {
return "casbin-python-cli.exe"
}
return "casbin-python-cli"
case "dotnet":
if runtime.GOOS == "windows" {
return "casbin-dotnet-cli.exe"
}
return "casbin-dotnet-cli"
default:
return ""
}
}
// @Title getLatestCLIURL
// @Description Get latest CLI download URL from GitHub
// @Param repoURL string true "GitHub repository URL"
// @Param language string true "Language type"
// @Success 200 {string} string "Download URL and version"
func getLatestCLIURL(repoURL string, language string) (string, string, error) {
client := proxy.GetHttpClient(repoURL)
resp, err := client.Get(repoURL)
if err != nil {
return "", "", fmt.Errorf("failed to fetch release info: %v", err)
}
defer resp.Body.Close()
var release ReleaseInfo
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return "", "", err
}
binaryNames := getBinaryNames()
if binaryNames == nil {
return "", "", fmt.Errorf("unsupported OS: %s", runtime.GOOS)
}
binaryName := binaryNames[language]
for _, asset := range release.Assets {
if asset.Name == binaryName {
return asset.URL, release.TagName, nil
}
}
return "", "", fmt.Errorf("no suitable binary found for OS: %s, language: %s", runtime.GOOS, language)
}
// @Title extractGoCliFile
// @Description Extract the Go CLI file
// @Param filePath string true "The file path"
// @Success 200 {string} string "The extracted file path"
// @router /extractGoCliFile [post]
func extractGoCliFile(filePath string) error {
tempDir := filepath.Join(downloadFolder, "temp")
if err := os.MkdirAll(tempDir, 0o755); err != nil {
return err
}
defer os.RemoveAll(tempDir)
if runtime.GOOS == "windows" {
if err := unzipFile(filePath, tempDir); err != nil {
return err
}
} else {
if err := untarFile(filePath, tempDir); err != nil {
return err
}
}
execName := "casbin-go-cli"
if runtime.GOOS == "windows" {
execName += ".exe"
}
var execPath string
err := filepath.Walk(tempDir, func(path string, info os.FileInfo, err error) error {
if info.Name() == execName {
execPath = path
return nil
}
return nil
})
if err != nil {
return err
}
finalPath := filepath.Join(downloadFolder, execName)
if err := os.Rename(execPath, finalPath); err != nil {
return err
}
return os.Remove(filePath)
}
// @Title unzipFile
// @Description Unzip the file
// @Param zipPath string true "The zip file path"
// @Param destDir string true "The destination directory"
// @Success 200 {string} string "The extracted file path"
// @router /unzipFile [post]
func unzipFile(zipPath, destDir string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
fpath := filepath.Join(destDir, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, os.ModePerm)
continue
}
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
outFile.Close()
return err
}
_, err = io.Copy(outFile, rc)
outFile.Close()
rc.Close()
if err != nil {
return err
}
}
return nil
}
// @Title untarFile
// @Description Untar the file
// @Param tarPath string true "The tar file path"
// @Param destDir string true "The destination directory"
// @Success 200 {string} string "The extracted file path"
// @router /untarFile [post]
func untarFile(tarPath, destDir string) error {
file, err := os.Open(tarPath)
if err != nil {
return err
}
defer file.Close()
gzr, err := gzip.NewReader(file)
if err != nil {
return err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
path := filepath.Join(destDir, header.Name)
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(path, 0o755); err != nil {
return err
}
case tar.TypeReg:
outFile, err := os.Create(path)
if err != nil {
return err
}
if _, err := io.Copy(outFile, tr); err != nil {
outFile.Close()
return err
}
outFile.Close()
}
}
return nil
}
// @Title createJavaCliWrapper
// @Description Create the Java CLI wrapper
// @Param binPath string true "The binary path"
// @Success 200 {string} string "The created file path"
// @router /createJavaCliWrapper [post]
func createJavaCliWrapper(binPath string) error {
if runtime.GOOS == "windows" {
// Create a Windows CMD file
cmdPath := filepath.Join(binPath, "casbin-java-cli.cmd")
cmdContent := fmt.Sprintf(`@echo off
java -jar "%s\casbin-java-cli.jar" %%*`, binPath)
err := os.WriteFile(cmdPath, []byte(cmdContent), 0o755)
if err != nil {
return fmt.Errorf("failed to create Java CLI wrapper: %v", err)
}
} else {
// Create Unix shell script
shPath := filepath.Join(binPath, "casbin-java-cli")
shContent := fmt.Sprintf(`#!/bin/sh
java -jar "%s/casbin-java-cli.jar" "$@"`, binPath)
err := os.WriteFile(shPath, []byte(shContent), 0o755)
if err != nil {
return fmt.Errorf("failed to create Java CLI wrapper: %v", err)
}
}
return nil
}
// @Title downloadCLI
// @Description Download and setup CLI tools
// @Success 200 {error} error "Error if any"
func downloadCLI() error {
pathEnv := os.Getenv("PATH")
binPath, err := filepath.Abs(downloadFolder)
if err != nil {
return fmt.Errorf("failed to get absolute path to download directory: %v", err)
}
if !strings.Contains(pathEnv, binPath) {
newPath := fmt.Sprintf("%s%s%s", binPath, string(os.PathListSeparator), pathEnv)
if err := os.Setenv("PATH", newPath); err != nil {
return fmt.Errorf("failed to update PATH environment variable: %v", err)
}
}
if err := os.MkdirAll(downloadFolder, 0o755); err != nil {
return fmt.Errorf("failed to create download directory: %v", err)
}
repos := map[string]string{
"java": javaCliRepo,
"go": goCliRepo,
"rust": rustCliRepo,
"python": pythonCliRepo,
"dotnet": dotnetCliRepo,
}
for lang, repo := range repos {
cliURL, version, err := getLatestCLIURL(repo, lang)
if err != nil {
fmt.Printf("failed to get %s CLI URL: %v\n", lang, err)
continue
}
originalPath := filepath.Join(downloadFolder, getBinaryNames()[lang])
fmt.Printf("downloading %s CLI: %s\n", lang, cliURL)
client := proxy.GetHttpClient(cliURL)
resp, err := client.Get(cliURL)
if err != nil {
fmt.Printf("failed to download %s CLI: %v\n", lang, err)
continue
}
func() {
defer resp.Body.Close()
if err := os.MkdirAll(filepath.Dir(originalPath), 0o755); err != nil {
fmt.Printf("failed to create directory for %s CLI: %v\n", lang, err)
return
}
tmpFile := originalPath + ".tmp"
out, err := os.Create(tmpFile)
if err != nil {
fmt.Printf("failed to create or write %s CLI: %v\n", lang, err)
return
}
defer func() {
out.Close()
os.Remove(tmpFile)
}()
if _, err = io.Copy(out, resp.Body); err != nil ||
out.Close() != nil ||
os.Rename(tmpFile, originalPath) != nil {
fmt.Printf("failed to download %s CLI: %v\n", lang, err)
return
}
}()
if lang == "go" {
if err := extractGoCliFile(originalPath); err != nil {
fmt.Printf("failed to extract Go CLI: %v\n", err)
continue
}
} else {
finalPath := filepath.Join(downloadFolder, getFinalBinaryName(lang))
if err := os.Rename(originalPath, finalPath); err != nil {
fmt.Printf("failed to rename %s CLI: %v\n", lang, err)
continue
}
}
if runtime.GOOS != "windows" {
execPath := filepath.Join(downloadFolder, getFinalBinaryName(lang))
if err := os.Chmod(execPath, 0o755); err != nil {
fmt.Printf("failed to set %s CLI execution permission: %v\n", lang, err)
continue
}
}
fmt.Printf("downloaded %s CLI version: %s\n", lang, version)
if lang == "java" {
if err := createJavaCliWrapper(binPath); err != nil {
fmt.Printf("failed to create Java CLI wrapper: %v\n", err)
continue
}
}
}
return nil
}
// @Title RefreshEngines
// @Tag CLI API
// @Description Refresh all CLI engines
// @Param m query string true "Hash for request validation"
// @Param t query string true "Timestamp for request validation"
// @Success 200 {object} controllers.Response The Response object
// @router /refresh-engines [post]
func (c *ApiController) RefreshEngines() {
if !conf.IsDemoMode() && !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
hash := c.Ctx.Input.Query("m")
timestamp := c.Ctx.Input.Query("t")
if hash == "" || timestamp == "" {
c.ResponseError("invalid identifier")
return
}
requestTime, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
c.ResponseError("invalid identifier")
return
}
timeDiff := time.Since(requestTime)
if timeDiff > 5*time.Minute || timeDiff < -5*time.Minute {
c.ResponseError("invalid identifier")
return
}
version := "casbin-editor-v1"
rawString := fmt.Sprintf("%s|%s", version, timestamp)
hasher := sha256.New()
hasher.Write([]byte(rawString))
calculatedHash := strings.ToLower(hex.EncodeToString(hasher.Sum(nil)))
if calculatedHash != strings.ToLower(hash) {
c.ResponseError("invalid identifier")
return
}
err = downloadCLI()
if err != nil {
c.ResponseError(fmt.Sprintf("failed to refresh engines: %v", err))
return
}
c.ResponseOk(map[string]string{
"status": "success",
"message": "CLI engines updated successfully",
})
}
// @Title ScheduleCLIUpdater
// @Description Start periodic CLI update scheduler
func ScheduleCLIUpdater() {
if !web.AppConfig.DefaultBool("isDemoMode", false) {
return
}
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for range ticker.C {
err := downloadCLI()
if err != nil {
fmt.Printf("failed to update CLI: %v\n", err)
} else {
fmt.Println("CLI updated successfully")
}
}
}
// @Title DownloadCLI
// @Description Download the CLI
// @Success 200 {string} string "The downloaded file path"
// @router /downloadCLI [post]
func DownloadCLI() error {
return downloadCLI()
}
// @Title InitCLIDownloader
// @Description Initialize CLI downloader and start update scheduler
func InitCLIDownloader() {
if !web.AppConfig.DefaultBool("isDemoMode", false) {
return
}
util.SafeGoroutine(func() {
err := DownloadCLI()
if err != nil {
fmt.Printf("failed to initialize CLI downloader: %v\n", err)
}
ScheduleCLIUpdater()
})
}

226
controllers/consent.go Normal file
View File

@@ -0,0 +1,226 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/casdoor/casdoor/object"
)
// RevokeConsent revokes a consent record
// @Title RevokeConsent
// @Tag Consent API
// @Description revoke a consent record
// @Param body body object.ConsentRecord true "The consent object"
// @Success 200 {object} controllers.Response The Response object
// @router /revoke-consent [post]
func (c *ApiController) RevokeConsent() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
var consent object.ConsentRecord
err := json.Unmarshal(c.Ctx.Input.RequestBody, &consent)
if err != nil {
c.ResponseError(err.Error())
return
}
// Validate that consent.Application is not empty
if consent.Application == "" {
c.ResponseError(c.T("general:Application cannot be empty"))
return
}
// Validate that GrantedScopes is not empty when scope-specific revoke is requested
if len(consent.GrantedScopes) == 0 {
c.ResponseError(c.T("general:Granted scopes cannot be empty"))
return
}
userObj, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if userObj == nil {
c.ResponseError(c.T("general:The user doesn't exist"))
return
}
newScopes := []object.ConsentRecord{}
for _, record := range userObj.ApplicationScopes {
if record.Application != consent.Application {
// skip other applications
newScopes = append(newScopes, record)
continue
}
// revoke specified scopes
revokeSet := make(map[string]bool)
for _, s := range consent.GrantedScopes {
revokeSet[s] = true
}
remaining := []string{}
for _, s := range record.GrantedScopes {
if !revokeSet[s] {
remaining = append(remaining, s)
}
}
if len(remaining) > 0 {
// still have remaining scopes, keep the record and update
record.GrantedScopes = remaining
newScopes = append(newScopes, record)
}
// otherwise the application authorization is revoked, delete the whole record
}
userObj.ApplicationScopes = newScopes
success, err := object.UpdateUser(userObj.GetId(), userObj, nil, false)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}
// GrantConsent grants consent for an OAuth application and returns authorization code
// @Title GrantConsent
// @Tag Consent API
// @Description grant consent for an OAuth application and get authorization code
// @Param body body object.ConsentRecord true "The consent object with OAuth parameters"
// @Success 200 {object} controllers.Response The Response object
// @router /grant-consent [post]
func (c *ApiController) GrantConsent() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
var request struct {
Application string `json:"application"`
Scopes []string `json:"grantedScopes"`
ClientId string `json:"clientId"`
Provider string `json:"provider"`
SigninMethod string `json:"signinMethod"`
ResponseType string `json:"responseType"`
RedirectUri string `json:"redirectUri"`
Scope string `json:"scope"`
State string `json:"state"`
Nonce string `json:"nonce"`
Challenge string `json:"challenge"`
Resource string `json:"resource"`
}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &request)
if err != nil {
c.ResponseError(err.Error())
return
}
// Validate application by clientId
application, err := object.GetApplicationByClientId(request.ClientId)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(c.T("general:Invalid client_id"))
return
}
// Verify that request.Application matches the application's actual ID
if request.Application != application.GetId() {
c.ResponseError(c.T("general:Invalid application"))
return
}
// Update user's ApplicationScopes
userObj, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if userObj == nil {
c.ResponseError(c.T("general:User not found"))
return
}
appId := application.GetId()
found := false
// Insert new scope into existing applicationScopes
for i, record := range userObj.ApplicationScopes {
if record.Application == appId {
existing := make(map[string]bool)
for _, s := range userObj.ApplicationScopes[i].GrantedScopes {
existing[s] = true
}
for _, s := range request.Scopes {
if !existing[s] {
userObj.ApplicationScopes[i].GrantedScopes = append(userObj.ApplicationScopes[i].GrantedScopes, s)
existing[s] = true
}
}
found = true
break
}
}
// create a new applicationScopes if not found
if !found {
uniqueScopes := []string{}
existing := make(map[string]bool)
for _, s := range request.Scopes {
if !existing[s] {
uniqueScopes = append(uniqueScopes, s)
existing[s] = true
}
}
userObj.ApplicationScopes = append(userObj.ApplicationScopes, object.ConsentRecord{
Application: appId,
GrantedScopes: uniqueScopes,
})
}
_, err = object.UpdateUser(userObj.GetId(), userObj, []string{"application_scopes"}, false)
if err != nil {
c.ResponseError(err.Error())
return
}
// Now get the OAuth code
code, err := object.GetOAuthCode(
userId,
request.ClientId,
request.Provider,
request.SigninMethod,
request.ResponseType,
request.RedirectUri,
request.Scope,
request.State,
request.Nonce,
request.Challenge,
request.Resource,
c.Ctx.Request.Host,
c.GetAcceptLanguage(),
)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(code.Code)
}

View File

@@ -1,4 +1,4 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -16,75 +16,292 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
xormadapter "github.com/casdoor/xorm-adapter/v3"
)
func (c *ApiController) Enforce() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
return
}
// GetEnforcers
// @Title GetEnforcers
// @Tag Enforcer API
// @Description get enforcers
// @Param owner query string true "The owner of enforcers"
// @Success 200 {array} object.Enforcer
// @router /get-enforcers [get]
func (c *ApiController) GetEnforcers() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
var permissionRule object.PermissionRule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &permissionRule)
if limit == "" || page == "" {
enforcers, err := object.GetEnforcers(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(enforcers)
} else {
limit := util.ParseInt(limit)
count, err := object.GetEnforcerCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
enforcers, err := object.GetPaginationEnforcers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(enforcers, paginator.Nums())
}
}
// GetEnforcer
// @Title GetEnforcer
// @Tag Enforcer API
// @Description get enforcer
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Success 200 {object} object.Enforcer
// @router /get-enforcer [get]
func (c *ApiController) GetEnforcer() {
id := c.Ctx.Input.Query("id")
loadModelCfg := c.Ctx.Input.Query("loadModelCfg")
enforcer, err := object.GetEnforcer(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.Enforce(userId, &permissionRule)
c.ServeJSON()
}
func (c *ApiController) BatchEnforce() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
return
if enforcer != nil {
if loadModelCfg == "true" && enforcer.Model != "" {
err = enforcer.LoadModelCfg()
if err != nil {
return
}
}
}
var permissionRules []object.PermissionRule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &permissionRules)
c.ResponseOk(enforcer)
}
// UpdateEnforcer
// @Title UpdateEnforcer
// @Tag Enforcer API
// @Description update enforcer
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param enforcer body object true "The enforcer object"
// @Success 200 {object} object.Enforcer
// @router /update-enforcer [post]
func (c *ApiController) UpdateEnforcer() {
id := c.Ctx.Input.Query("id")
enforcer := object.Enforcer{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &enforcer)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.BatchEnforce(userId, permissionRules)
c.Data["json"] = wrapActionResponse(object.UpdateEnforcer(id, &enforcer))
c.ServeJSON()
}
func (c *ApiController) GetAllObjects() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
// AddEnforcer
// @Title AddEnforcer
// @Tag Enforcer API
// @Description add enforcer
// @Param enforcer body object true "The enforcer object"
// @Success 200 {object} object.Enforcer
// @router /add-enforcer [post]
func (c *ApiController) AddEnforcer() {
enforcer := object.Enforcer{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &enforcer)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.GetAllObjects(userId)
c.Data["json"] = wrapActionResponse(object.AddEnforcer(&enforcer))
c.ServeJSON()
}
func (c *ApiController) GetAllActions() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
// DeleteEnforcer
// @Title DeleteEnforcer
// @Tag Enforcer API
// @Description delete enforcer
// @Param body body object.Enforcer true "The enforcer object"
// @Success 200 {object} object.Enforcer
// @router /delete-enforcer [post]
func (c *ApiController) DeleteEnforcer() {
var enforcer object.Enforcer
err := json.Unmarshal(c.Ctx.Input.RequestBody, &enforcer)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.GetAllActions(userId)
c.Data["json"] = wrapActionResponse(object.DeleteEnforcer(&enforcer))
c.ServeJSON()
}
func (c *ApiController) GetAllRoles() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
// GetPolicies
// @Title GetPolicies
// @Tag Enforcer API
// @Description get policies
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param adapterId query string false "The adapter id"
// @Success 200 {array} xormadapter.CasbinRule
// @router /get-policies [get]
func (c *ApiController) GetPolicies() {
id := c.Ctx.Input.Query("id")
adapterId := c.Ctx.Input.Query("adapterId")
if adapterId != "" {
adapter, err := object.GetAdapter(adapterId)
if err != nil {
c.ResponseError(err.Error())
return
}
if adapter == nil {
c.ResponseError(fmt.Sprintf(c.T("enforcer:the adapter: %s is not found"), adapterId))
return
}
err = adapter.InitAdapter()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk()
return
}
c.Data["json"] = object.GetAllRoles(userId)
policies, err := object.GetPolicies(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(policies)
}
// GetFilteredPolicies
// @Title GetFilteredPolicies
// @Tag Enforcer API
// @Description get filtered policies with support for multiple filters via POST body
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param body body []object.Filter true "Array of filter objects for multiple filters"
// @Success 200 {array} xormadapter.CasbinRule
// @router /get-filtered-policies [post]
func (c *ApiController) GetFilteredPolicies() {
id := c.Ctx.Input.Query("id")
var filters []object.Filter
err := json.Unmarshal(c.Ctx.Input.RequestBody, &filters)
if err != nil {
c.ResponseError(err.Error())
return
}
filteredPolicies, err := object.GetFilteredPoliciesMulti(id, filters)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(filteredPolicies)
}
// UpdatePolicy
// @Title UpdatePolicy
// @Tag Enforcer API
// @Description update policy
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param body body []xormadapter.CasbinRule true "Array containing old and new policy"
// @Success 200 {object} Response
// @router /update-policy [post]
func (c *ApiController) UpdatePolicy() {
id := c.Ctx.Input.Query("id")
var policies []xormadapter.CasbinRule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &policies)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.UpdatePolicy(id, policies[0].Ptype, util.CasbinToSlice(policies[0]), util.CasbinToSlice(policies[1]))
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(affected)
c.ServeJSON()
}
// AddPolicy
// @Title AddPolicy
// @Tag Enforcer API
// @Description add policy
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param body body xormadapter.CasbinRule true "The policy to add"
// @Success 200 {object} Response
// @router /add-policy [post]
func (c *ApiController) AddPolicy() {
id := c.Ctx.Input.Query("id")
var policy xormadapter.CasbinRule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &policy)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.AddPolicy(id, policy.Ptype, util.CasbinToSlice(policy))
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(affected)
c.ServeJSON()
}
// RemovePolicy
// @Title RemovePolicy
// @Tag Enforcer API
// @Description remove policy
// @Param id query string true "The id ( owner/name ) of enforcer"
// @Param body body xormadapter.CasbinRule true "The policy to remove"
// @Success 200 {object} Response
// @router /remove-policy [post]
func (c *ApiController) RemovePolicy() {
id := c.Ctx.Input.Query("id")
var policy xormadapter.CasbinRule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &policy)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.RemovePolicy(id, policy.Ptype, util.CasbinToSlice(policy))
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(affected)
c.ServeJSON()
}

168
controllers/entry.go Normal file
View File

@@ -0,0 +1,168 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/server/web/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetEntries
// @Title GetEntries
// @Tag Entry API
// @Description get entries
// @Param owner query string true "The owner of entries"
// @Success 200 {array} object.Entry The Response object
// @router /get-entries [get]
func (c *ApiController) GetEntries() {
owner := c.Ctx.Input.Query("owner")
if owner == "admin" {
owner = ""
}
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
entries, err := object.GetEntries(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(entries)
return
}
limitInt := util.ParseInt(limit)
count, err := object.GetEntryCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limitInt, count)
entries, err := object.GetPaginationEntries(owner, paginator.Offset(), limitInt, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(entries, paginator.Nums())
}
// GetEntry
// @Title GetEntry
// @Tag Entry API
// @Description get entry
// @Param id query string true "The id ( owner/name ) of the entry"
// @Success 200 {object} object.Entry The Response object
// @router /get-entry [get]
func (c *ApiController) GetEntry() {
id := c.Ctx.Input.Query("id")
entry, err := object.GetEntry(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(entry)
}
// GetOpenClawSessionGraph
// @Title GetOpenClawSessionGraph
// @Tag Entry API
// @Description get OpenClaw session graph
// @Param id query string true "The id ( owner/name ) of the entry"
// @Success 200 {object} object.OpenClawSessionGraph The Response object
// @router /get-openclaw-session-graph [get]
func (c *ApiController) GetOpenClawSessionGraph() {
id := c.Ctx.Input.Query("id")
graph, err := object.GetOpenClawSessionGraph(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(graph)
}
// UpdateEntry
// @Title UpdateEntry
// @Tag Entry API
// @Description update entry
// @Param id query string true "The id ( owner/name ) of the entry"
// @Param body body object.Entry true "The details of the entry"
// @Success 200 {object} controllers.Response The Response object
// @router /update-entry [post]
func (c *ApiController) UpdateEntry() {
id := c.Ctx.Input.Query("id")
var entry object.Entry
err := json.Unmarshal(c.Ctx.Input.RequestBody, &entry)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateEntry(id, &entry))
c.ServeJSON()
}
// AddEntry
// @Title AddEntry
// @Tag Entry API
// @Description add entry
// @Param body body object.Entry true "The details of the entry"
// @Success 200 {object} controllers.Response The Response object
// @router /add-entry [post]
func (c *ApiController) AddEntry() {
var entry object.Entry
err := json.Unmarshal(c.Ctx.Input.RequestBody, &entry)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddEntry(&entry))
c.ServeJSON()
}
// DeleteEntry
// @Title DeleteEntry
// @Tag Entry API
// @Description delete entry
// @Param body body object.Entry true "The details of the entry"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-entry [post]
func (c *ApiController) DeleteEntry() {
var entry object.Entry
err := json.Unmarshal(c.Ctx.Input.RequestBody, &entry)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteEntry(&entry))
c.ServeJSON()
}

View File

@@ -0,0 +1,148 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
collogspb "go.opentelemetry.io/proto/otlp/collector/logs/v1"
colmetricspb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/casdoor/casdoor/util"
)
// @Title AddOtlpTrace
// @Tag OTLP API
// @Description receive otlp trace protobuf
// @Success 200 {object} string
// @router /api/v1/traces [post]
func (c *ApiController) AddOtlpTrace() {
body := readProtobufBody(c.Ctx)
if body == nil {
return
}
provider, status, err := resolveOpenClawProvider(c.Ctx)
if err != nil {
responseOtlpError(c.Ctx, status, body, "%s", err.Error())
return
}
var req coltracepb.ExportTraceServiceRequest
if err := proto.Unmarshal(body, &req); err != nil {
responseOtlpError(c.Ctx, 400, body, "bad protobuf: %v", err)
return
}
message, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(&req)
if err != nil {
responseOtlpError(c.Ctx, 500, body, "marshal trace failed: %v", err)
return
}
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
userAgent := c.Ctx.Request.Header.Get("User-Agent")
if err := provider.AddTrace(message, clientIp, userAgent); err != nil {
responseOtlpError(c.Ctx, 500, body, "save trace failed: %v", err)
return
}
resp, _ := proto.Marshal(&coltracepb.ExportTraceServiceResponse{})
c.Ctx.Output.Header("Content-Type", "application/x-protobuf")
c.Ctx.Output.SetStatus(200)
c.Ctx.Output.Body(resp)
}
// @Title AddOtlpMetrics
// @Tag OTLP API
// @Description receive otlp metrics protobuf
// @Success 200 {object} string
// @router /api/v1/metrics [post]
func (c *ApiController) AddOtlpMetrics() {
body := readProtobufBody(c.Ctx)
if body == nil {
return
}
provider, status, err := resolveOpenClawProvider(c.Ctx)
if err != nil {
responseOtlpError(c.Ctx, status, body, "%s", err.Error())
return
}
var req colmetricspb.ExportMetricsServiceRequest
if err := proto.Unmarshal(body, &req); err != nil {
responseOtlpError(c.Ctx, 400, body, "bad protobuf: %v", err)
return
}
message, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(&req)
if err != nil {
responseOtlpError(c.Ctx, 500, body, "marshal metrics failed: %v", err)
return
}
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
userAgent := c.Ctx.Request.Header.Get("User-Agent")
if err := provider.AddMetrics(message, clientIp, userAgent); err != nil {
responseOtlpError(c.Ctx, 500, body, "save metrics failed: %v", err)
return
}
resp, _ := proto.Marshal(&colmetricspb.ExportMetricsServiceResponse{})
c.Ctx.Output.Header("Content-Type", "application/x-protobuf")
c.Ctx.Output.SetStatus(200)
c.Ctx.Output.Body(resp)
}
// @Title AddOtlpLogs
// @Tag OTLP API
// @Description receive otlp logs protobuf
// @Success 200 {object} string
// @router /api/v1/logs [post]
func (c *ApiController) AddOtlpLogs() {
body := readProtobufBody(c.Ctx)
if body == nil {
return
}
provider, status, err := resolveOpenClawProvider(c.Ctx)
if err != nil {
responseOtlpError(c.Ctx, status, body, "%s", err.Error())
return
}
var req collogspb.ExportLogsServiceRequest
if err := proto.Unmarshal(body, &req); err != nil {
responseOtlpError(c.Ctx, 400, body, "bad protobuf: %v", err)
return
}
message, err := protojson.MarshalOptions{Multiline: true, Indent: " "}.Marshal(&req)
if err != nil {
responseOtlpError(c.Ctx, 500, body, "marshal logs failed: %v", err)
return
}
clientIp := util.GetClientIpFromRequest(c.Ctx.Request)
userAgent := c.Ctx.Request.Header.Get("User-Agent")
if err := provider.AddLogs(message, clientIp, userAgent); err != nil {
responseOtlpError(c.Ctx, 500, body, "save logs failed: %v", err)
return
}
resp, _ := proto.Marshal(&collogspb.ExportLogsServiceResponse{})
c.Ctx.Output.Header("Content-Type", "application/x-protobuf")
c.Ctx.Output.SetStatus(200)
c.Ctx.Output.Body(resp)
}

78
controllers/entry_util.go Normal file
View File

@@ -0,0 +1,78 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"io"
"strings"
"github.com/beego/beego/v2/server/web/context"
"github.com/casdoor/casdoor/log"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
func responseOtlpError(ctx *context.Context, status int, body []byte, format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
req := ctx.Request
bodyInfo := "(no body)"
if len(body) > 0 {
bodyInfo = fmt.Sprintf("%d bytes: %q", len(body), truncate(body, 256))
}
fmt.Printf("responseOtlpError: [%d] %s | %s %s | remoteAddr=%s | Content-Type=%s | User-Agent=%s | body=%s\n",
status, msg,
req.Method, req.URL.Path,
req.RemoteAddr,
req.Header.Get("Content-Type"),
req.Header.Get("User-Agent"),
bodyInfo,
)
ctx.Output.SetStatus(status)
ctx.Output.Body([]byte(msg))
}
func truncate(b []byte, max int) []byte {
if len(b) <= max {
return b
}
return b[:max]
}
func resolveOpenClawProvider(ctx *context.Context) (*log.OpenClawProvider, int, error) {
clientIP := util.GetClientIpFromRequest(ctx.Request)
provider, err := object.GetOpenClawProviderByIP(clientIP)
if err != nil {
return nil, 500, fmt.Errorf("provider lookup failed: %w", err)
}
if provider == nil {
return nil, 403, fmt.Errorf("forbidden: no OpenClaw provider configured for IP %s", clientIP)
}
return provider, 0, nil
}
func readProtobufBody(ctx *context.Context) []byte {
if !strings.HasPrefix(ctx.Input.Header("Content-Type"), "application/x-protobuf") {
preview, _ := io.ReadAll(io.LimitReader(ctx.Request.Body, 256))
responseOtlpError(ctx, 415, preview, "unsupported content type")
return nil
}
body, err := io.ReadAll(ctx.Request.Body)
if err != nil {
responseOtlpError(ctx, 400, nil, "read body failed")
return nil
}
return body
}

55
controllers/face.go Normal file
View File

@@ -0,0 +1,55 @@
// Copyright 2024 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Casdoor will expose its providers as services to SDK
// We are going to implement those services as APIs here
package controllers
import (
"fmt"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// FaceIDSigninBegin
// @Title FaceIDSigninBegin
// @Tag Login API
// @Description FaceId Login Flow 1st stage
// @Param owner query string true "owner"
// @Param name query string true "name"
// @Success 200 {object} controllers.Response The Response object
// @router /faceid-signin-begin [get]
func (c *ApiController) FaceIDSigninBegin() {
userOwner := c.Ctx.Input.Query("owner")
userName := c.Ctx.Input.Query("name")
user, err := object.GetUserByFields(userOwner, userName)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), util.GetId(userOwner, userName)))
return
}
if len(user.FaceIds) == 0 {
c.ResponseError(c.T("check:Face data does not exist, cannot log in"))
return
}
c.ResponseOk()
}

175
controllers/form.go Normal file
View File

@@ -0,0 +1,175 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetGlobalForms
// @Title GetGlobalForms
// @Tag Form API
// @Description get global forms
// @Success 200 {array} object.Form The Response object
// @router /get-global-forms [get]
func (c *ApiController) GetGlobalForms() {
forms, err := object.GetGlobalForms()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedForms(forms, true))
}
// GetForms
// @Title GetForms
// @Tag Form API
// @Description get forms
// @Param owner query string true "The owner of form"
// @Success 200 {array} object.Form The Response object
// @router /get-forms [get]
func (c *ApiController) GetForms() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
forms, err := object.GetForms(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedForms(forms, true))
} else {
limit := util.ParseInt(limit)
count, err := object.GetFormCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
forms, err := object.GetPaginationForms(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(forms, paginator.Nums())
}
}
// GetForm
// @Title GetForm
// @Tag Form API
// @Description get form
// @Param id query string true "The id (owner/name) of form"
// @Success 200 {object} object.Form The Response object
// @router /get-form [get]
func (c *ApiController) GetForm() {
id := c.Ctx.Input.Query("id")
form, err := object.GetForm(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedForm(form, true))
}
// UpdateForm
// @Title UpdateForm
// @Tag Form API
// @Description update form
// @Param id query string true "The id (owner/name) of the form"
// @Param body body object.Form true "The details of the form"
// @Success 200 {object} controllers.Response The Response object
// @router /update-form [post]
func (c *ApiController) UpdateForm() {
id := c.Ctx.Input.Query("id")
var form object.Form
err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
if err != nil {
c.ResponseError(err.Error())
return
}
success, err := object.UpdateForm(id, &form)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}
// AddForm
// @Title AddForm
// @Tag Form API
// @Description add form
// @Param body body object.Form true "The details of the form"
// @Success 200 {object} controllers.Response The Response object
// @router /add-form [post]
func (c *ApiController) AddForm() {
var form object.Form
err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
if err != nil {
c.ResponseError(err.Error())
return
}
success, err := object.AddForm(&form)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}
// DeleteForm
// @Title DeleteForm
// @Tag Form API
// @Description delete form
// @Param body body object.Form true "The details of the form"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-form [post]
func (c *ApiController) DeleteForm() {
var form object.Form
err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
if err != nil {
c.ResponseError(err.Error())
return
}
success, err := object.DeleteForm(&form)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(success)
}

View File

@@ -1,4 +1,4 @@
// Copyright 2021 The Casdoor Authors. All Rights Reserved.
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -16,29 +16,20 @@ package controllers
import "github.com/casdoor/casdoor/object"
// GetOidcDiscovery
// @Title GetOidcDiscovery
// @Tag OIDC API
// @Description Get Oidc Discovery
// @Success 200 {object} object.OidcDiscovery
// @router /.well-known/openid-configuration [get]
func (c *RootController) GetOidcDiscovery() {
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOidcDiscovery(host)
c.ServeJSON()
}
// GetDashboard
// @Title GetDashboard
// @Tag System API
// @Description get information of dashboard
// @Success 200 {object} controllers.Response The Response object
// @router /get-dashboard [get]
func (c *ApiController) GetDashboard() {
owner := c.Ctx.Input.Query("owner")
// GetJwks
// @Title GetJwks
// @Tag OIDC API
// @Success 200 {object} jose.JSONWebKey
// @router /.well-known/jwks [get]
func (c *RootController) GetJwks() {
jwks, err := object.GetJsonWebKeySet()
data, err := object.GetDashboard(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = jwks
c.ServeJSON()
c.ResponseOk(data)
}

187
controllers/group.go Normal file
View File

@@ -0,0 +1,187 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
package controllers
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetGroups
// @Title GetGroups
// @Tag Group API
// @Description get groups
// @Param owner query string true "The owner of groups"
// @Success 200 {array} object.Group The Response object
// @router /get-groups [get]
func (c *ApiController) GetGroups() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
withTree := c.Ctx.Input.Query("withTree")
if limit == "" || page == "" {
groups, err := object.GetGroups(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
err = object.ExtendGroupsWithUsers(groups)
if err != nil {
c.ResponseError(err.Error())
return
}
if withTree == "true" {
c.ResponseOk(object.ConvertToTreeData(groups, owner))
return
}
c.ResponseOk(groups)
} else {
limit := util.ParseInt(limit)
count, err := object.GetGroupCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
groups, err := object.GetPaginationGroups(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
groupsHaveChildrenMap, err := object.GetGroupsHaveChildrenMap(groups)
if err != nil {
c.ResponseError(err.Error())
return
}
for _, group := range groups {
_, ok := groupsHaveChildrenMap[group.GetId()]
if ok {
group.HaveChildren = true
}
parent, ok := groupsHaveChildrenMap[fmt.Sprintf("%s/%s", group.Owner, group.ParentId)]
if ok {
group.ParentName = parent.DisplayName
}
}
err = object.ExtendGroupsWithUsers(groups)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(groups, paginator.Nums())
}
}
// GetGroup
// @Title GetGroup
// @Tag Group API
// @Description get group
// @Param id query string true "The id ( owner/name ) of the group"
// @Success 200 {object} object.Group The Response object
// @router /get-group [get]
func (c *ApiController) GetGroup() {
id := c.Ctx.Input.Query("id")
group, err := object.GetGroup(id)
if err != nil {
c.ResponseError(err.Error())
return
}
err = object.ExtendGroupWithUsers(group)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(group)
}
// UpdateGroup
// @Title UpdateGroup
// @Tag Group API
// @Description update group
// @Param id query string true "The id ( owner/name ) of the group"
// @Param body body object.Group true "The details of the group"
// @Success 200 {object} controllers.Response The Response object
// @router /update-group [post]
func (c *ApiController) UpdateGroup() {
id := c.Ctx.Input.Query("id")
var group object.Group
err := json.Unmarshal(c.Ctx.Input.RequestBody, &group)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateGroup(id, &group))
c.ServeJSON()
}
// AddGroup
// @Title AddGroup
// @Tag Group API
// @Description add group
// @Param body body object.Group true "The details of the group"
// @Success 200 {object} controllers.Response The Response object
// @router /add-group [post]
func (c *ApiController) AddGroup() {
var group object.Group
err := json.Unmarshal(c.Ctx.Input.RequestBody, &group)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddGroup(&group))
c.ServeJSON()
}
// DeleteGroup
// @Title DeleteGroup
// @Tag Group API
// @Description delete group
// @Param body body object.Group true "The details of the group"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-group [post]
func (c *ApiController) DeleteGroup() {
var group object.Group
err := json.Unmarshal(c.Ctx.Input.RequestBody, &group)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteGroup(&group))
c.ServeJSON()
}

View File

@@ -0,0 +1,60 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"os"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
func (c *ApiController) UploadGroups() {
userId := c.GetSessionUsername()
owner, user, err := util.GetOwnerAndNameFromIdWithError(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
file, header, err := c.Ctx.Request.FormFile("file")
if err != nil {
c.ResponseError(err.Error())
return
}
fileId := fmt.Sprintf("%s_%s_%s", owner, user, util.RemoveExt(header.Filename))
path := util.GetUploadXlsxPath(fileId)
defer os.Remove(path)
err = saveFile(path, &file)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.UploadGroups(owner, path)
if err != nil {
c.ResponseError(err.Error())
return
}
if affected {
c.ResponseOk()
} else {
c.ResponseError(c.T("general:Failed to import groups"))
}
}

283
controllers/invitation.go Normal file
View File

@@ -0,0 +1,283 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"strings"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetInvitations
// @Title GetInvitations
// @Tag Invitation API
// @Description get invitations
// @Param owner query string true "The owner of invitations"
// @Success 200 {array} object.Invitation The Response object
// @router /get-invitations [get]
func (c *ApiController) GetInvitations() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
invitations, err := object.GetInvitations(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(invitations)
} else {
limit := util.ParseInt(limit)
count, err := object.GetInvitationCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
invitations, err := object.GetPaginationInvitations(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(invitations, paginator.Nums())
}
}
// GetInvitation
// @Title GetInvitation
// @Tag Invitation API
// @Description get invitation
// @Param id query string true "The id ( owner/name ) of the invitation"
// @Success 200 {object} object.Invitation The Response object
// @router /get-invitation [get]
func (c *ApiController) GetInvitation() {
id := c.Ctx.Input.Query("id")
invitation, err := object.GetInvitation(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(invitation)
}
// GetInvitationCodeInfo
// @Title GetInvitationCodeInfo
// @Tag Invitation API
// @Description get invitation code information
// @Param code query string true "Invitation code"
// @Success 200 {object} object.Invitation The Response object
// @router /get-invitation-info [get]
func (c *ApiController) GetInvitationCodeInfo() {
code := c.Ctx.Input.Query("code")
applicationId := c.Ctx.Input.Query("applicationId")
application, err := object.GetApplication(applicationId)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), applicationId))
return
}
invitation, msg := object.GetInvitationByCode(code, application.Organization, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
}
c.ResponseOk(object.GetMaskedInvitation(invitation))
}
// UpdateInvitation
// @Title UpdateInvitation
// @Tag Invitation API
// @Description update invitation
// @Param id query string true "The id ( owner/name ) of the invitation"
// @Param body body object.Invitation true "The details of the invitation"
// @Success 200 {object} controllers.Response The Response object
// @router /update-invitation [post]
func (c *ApiController) UpdateInvitation() {
id := c.Ctx.Input.Query("id")
var invitation object.Invitation
err := json.Unmarshal(c.Ctx.Input.RequestBody, &invitation)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateInvitation(id, &invitation, c.GetAcceptLanguage()))
c.ServeJSON()
}
// AddInvitation
// @Title AddInvitation
// @Tag Invitation API
// @Description add invitation
// @Param body body object.Invitation true "The details of the invitation"
// @Success 200 {object} controllers.Response The Response object
// @router /add-invitation [post]
func (c *ApiController) AddInvitation() {
var invitation object.Invitation
err := json.Unmarshal(c.Ctx.Input.RequestBody, &invitation)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddInvitation(&invitation, c.GetAcceptLanguage()))
c.ServeJSON()
}
// DeleteInvitation
// @Title DeleteInvitation
// @Tag Invitation API
// @Description delete invitation
// @Param body body object.Invitation true "The details of the invitation"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-invitation [post]
func (c *ApiController) DeleteInvitation() {
var invitation object.Invitation
err := json.Unmarshal(c.Ctx.Input.RequestBody, &invitation)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteInvitation(&invitation))
c.ServeJSON()
}
// VerifyInvitation
// @Title VerifyInvitation
// @Tag Invitation API
// @Description verify invitation
// @Param id query string true "The id ( owner/name ) of the invitation"
// @Success 200 {object} controllers.Response The Response object
// @router /verify-invitation [get]
func (c *ApiController) VerifyInvitation() {
id := c.Ctx.Input.Query("id")
payment, attachInfo, err := object.VerifyInvitation(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payment, attachInfo)
}
// SendInvitation
// @Title VerifyInvitation
// @Tag Invitation API
// @Description verify invitation
// @Param id query string true "The id ( owner/name ) of the invitation"
// @Param body body []string true "The details of the invitation"
// @Success 200 {object} controllers.Response The Response object
// @router /send-invitation [post]
func (c *ApiController) SendInvitation() {
id := c.Ctx.Input.Query("id")
var destinations []string
err := json.Unmarshal(c.Ctx.Input.RequestBody, &destinations)
if !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
invitation, err := object.GetInvitation(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if invitation == nil {
c.ResponseError(fmt.Sprintf(c.T("invitation:Invitation %s does not exist"), id))
return
}
organization, err := object.GetOrganization(fmt.Sprintf("admin/%s", invitation.Owner))
if err != nil {
c.ResponseError(err.Error())
return
}
if organization == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The organization: %s does not exist"), invitation.Owner))
return
}
var application *object.Application
if invitation.Application != "" {
application, err = object.GetApplication(fmt.Sprintf("admin/%s-org-%s", invitation.Application, invitation.Owner))
if err != nil {
c.ResponseError(err.Error())
return
}
} else {
application, err = object.GetApplicationByOrganizationName(invitation.Owner)
if err != nil {
c.ResponseError(err.Error())
return
}
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The organization: %s should have one application at least"), invitation.Owner))
return
}
if application.IsShared {
application.Name = fmt.Sprintf("%s-org-%s", application.Name, invitation.Owner)
}
provider, err := application.GetEmailProvider("Invitation")
if err != nil {
c.ResponseError(err.Error())
return
}
if provider == nil {
c.ResponseError(fmt.Sprintf(c.T("verification:please add an Email provider to the \"Providers\" list for the application: %s"), invitation.Owner))
return
}
content := provider.Metadata
content = strings.ReplaceAll(content, "%code", invitation.Code)
content = strings.ReplaceAll(content, "%link", invitation.GetInvitationLink(c.Ctx.Request.Host, application.Name))
err = object.SendEmail(provider, provider.Title, content, destinations, organization.DisplayName)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk()
}

105
controllers/kerberos.go Normal file
View File

@@ -0,0 +1,105 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"strings"
"github.com/casdoor/casdoor/form"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// KerberosLogin
// @Title KerberosLogin
// @Tag Login API
// @Description Kerberos/SPNEGO login via Integrated Windows Authentication
// @Param application query string true "application name"
// @Success 200 {object} controllers.Response The Response object
// @router /kerberos-login [get]
func (c *ApiController) KerberosLogin() {
applicationName := c.Ctx.Input.Query("application")
if applicationName == "" {
c.ResponseError(c.T("general:Missing parameter") + ": application")
return
}
application, err := object.GetApplication(fmt.Sprintf("admin/%s", applicationName))
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), applicationName))
return
}
organization, err := object.GetOrganization(util.GetId("admin", application.Organization))
if err != nil {
c.ResponseError(err.Error())
return
}
if organization == nil {
c.ResponseError(fmt.Sprintf("The organization: %s does not exist", application.Organization))
return
}
if organization.KerberosRealm == "" || organization.KerberosKeytab == "" {
c.ResponseError("Kerberos is not configured for this organization")
return
}
authHeader := c.Ctx.Input.Header("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Negotiate ") {
c.Ctx.Output.Header("WWW-Authenticate", "Negotiate")
c.Ctx.Output.SetStatus(401)
c.Ctx.Output.Body([]byte("Kerberos authentication required"))
return
}
spnegoToken := strings.TrimPrefix(authHeader, "Negotiate ")
kerberosUsername, err := object.ValidateKerberosToken(organization, spnegoToken)
if err != nil {
c.Ctx.Output.Header("WWW-Authenticate", "Negotiate")
c.ResponseError(fmt.Sprintf("Kerberos authentication failed: %s", err.Error()))
return
}
user, err := object.GetUserByKerberosName(organization.Name, kerberosUsername)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), kerberosUsername))
return
}
application.OrganizationObj = organization
authForm := &form.AuthForm{
Type: "code",
Application: applicationName,
Organization: organization.Name,
}
resp := c.HandleLoggedIn(application, user, authForm)
if resp != nil {
c.Data["json"] = resp
c.ServeJSON()
}
}

222
controllers/key.go Normal file
View File

@@ -0,0 +1,222 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetKeys
// @Title GetKeys
// @Tag Key API
// @Description get keys
// @Param owner query string true "The owner of keys"
// @Success 200 {array} object.Key The Response object
// @router /get-keys [get]
func (c *ApiController) GetKeys() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
keys, err := object.GetKeys(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
maskedKeys, err := object.GetMaskedKeys(keys, true, nil)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(maskedKeys)
} else {
limit := util.ParseInt(limit)
count, err := object.GetKeyCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
keys, err := object.GetPaginationKeys(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
maskedKeys, err := object.GetMaskedKeys(keys, true, nil)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(maskedKeys, paginator.Nums())
}
}
// GetGlobalKeys
// @Title GetGlobalKeys
// @Tag Key API
// @Description get global keys
// @Success 200 {array} object.Key The Response object
// @router /get-global-keys [get]
func (c *ApiController) GetGlobalKeys() {
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
keys, err := object.GetGlobalKeys()
if err != nil {
c.ResponseError(err.Error())
return
}
maskedKeys, err := object.GetMaskedKeys(keys, true, nil)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(maskedKeys)
} else {
limit := util.ParseInt(limit)
count, err := object.GetGlobalKeyCount(field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
keys, err := object.GetPaginationGlobalKeys(paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
maskedKeys, err := object.GetMaskedKeys(keys, true, nil)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(maskedKeys, paginator.Nums())
}
}
// GetKey
// @Title GetKey
// @Tag Key API
// @Description get key
// @Param id query string true "The id ( owner/name ) of the key"
// @Success 200 {object} object.Key The Response object
// @router /get-key [get]
func (c *ApiController) GetKey() {
id := c.Ctx.Input.Query("id")
key, err := object.GetKey(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(key)
}
// UpdateKey
// @Title UpdateKey
// @Tag Key API
// @Description update key
// @Param id query string true "The id ( owner/name ) of the key"
// @Param body body object.Key true "The details of the key"
// @Success 200 {object} controllers.Response The Response object
// @router /update-key [post]
func (c *ApiController) UpdateKey() {
id := c.Ctx.Input.Query("id")
oldKey, err := object.GetKey(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if oldKey == nil {
c.Data["json"] = wrapActionResponse(false)
c.ServeJSON()
return
}
var key object.Key
err = json.Unmarshal(c.Ctx.Input.RequestBody, &key)
if err != nil {
c.ResponseError(err.Error())
return
}
if !c.IsGlobalAdmin() && oldKey.Owner != key.Owner {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
c.Data["json"] = wrapActionResponse(object.UpdateKey(id, &key))
c.ServeJSON()
}
// AddKey
// @Title AddKey
// @Tag Key API
// @Description add key
// @Param body body object.Key true "The details of the key"
// @Success 200 {object} controllers.Response The Response object
// @router /add-key [post]
func (c *ApiController) AddKey() {
var key object.Key
err := json.Unmarshal(c.Ctx.Input.RequestBody, &key)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddKey(&key))
c.ServeJSON()
}
// DeleteKey
// @Title DeleteKey
// @Tag Key API
// @Description delete key
// @Param body body object.Key true "The details of the key"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-key [post]
func (c *ApiController) DeleteKey() {
var key object.Key
err := json.Unmarshal(c.Ctx.Input.RequestBody, &key)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteKey(&key))
c.ServeJSON()
}

View File

@@ -16,147 +16,174 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
type LdapServer struct {
Host string `json:"host"`
Port int `json:"port"`
Admin string `json:"admin"`
Passwd string `json:"passwd"`
BaseDn string `json:"baseDn"`
}
type LdapResp struct {
// Groups []LdapRespGroup `json:"groups"`
Users []object.LdapRespUser `json:"users"`
Users []object.LdapUser `json:"users"`
ExistUuids []string `json:"existUuids"`
}
//type LdapRespGroup struct {
// type LdapRespGroup struct {
// GroupId string
// GroupName string
//}
// }
type LdapSyncResp struct {
Exist []object.LdapRespUser `json:"exist"`
Failed []object.LdapRespUser `json:"failed"`
Exist []object.LdapUser `json:"exist"`
Failed []object.LdapUser `json:"failed"`
}
// GetLdapUser
// @Tag Account API
// GetLdapUsers
// @Title GetLdapser
// @router /get-ldap-user [post]
func (c *ApiController) GetLdapUser() {
ldapServer := LdapServer{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldapServer)
if err != nil || util.IsStrsEmpty(ldapServer.Host, ldapServer.Admin, ldapServer.Passwd, ldapServer.BaseDn) {
c.ResponseError("Missing parameter")
return
}
// @Tag Account API
// @Description get ldap users
// Param id string true "id"
// @Success 200 {object} controllers.LdapResp The Response object
// @router /get-ldap-users [get]
func (c *ApiController) GetLdapUsers() {
id := c.Ctx.Input.Query("id")
var resp LdapResp
conn, err := object.GetLdapConn(ldapServer.Host, ldapServer.Port, ldapServer.Admin, ldapServer.Passwd)
_, ldapId, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
c.ResponseError(err.Error())
return
}
ldapServer, err := object.GetLdap(ldapId)
if err != nil {
c.ResponseError(err.Error())
return
}
if ldapServer == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The LDAP: %s does not exist"), ldapId))
return
}
//groupsMap, err := conn.GetLdapGroups(ldapServer.BaseDn)
//if err != nil {
conn, err := ldapServer.GetLdapConn()
if err != nil {
c.ResponseError(err.Error())
return
}
defer conn.Close()
// groupsMap, err := conn.GetLdapGroups(ldapServer.BaseDn)
// if err != nil {
// c.ResponseError(err.Error())
// return
//}
// }
//for _, group := range groupsMap {
// for _, group := range groupsMap {
// resp.Groups = append(resp.Groups, LdapRespGroup{
// GroupId: group.GidNumber,
// GroupName: group.Cn,
// })
//}
// }
users, err := conn.GetLdapUsers(ldapServer.BaseDn)
users, err := conn.GetLdapUsers(ldapServer)
if err != nil {
c.ResponseError(err.Error())
return
}
for _, user := range users {
resp.Users = append(resp.Users, object.LdapRespUser{
UidNumber: user.UidNumber,
Uid: user.Uid,
Cn: user.Cn,
GroupId: user.GidNumber,
// GroupName: groupsMap[user.GidNumber].Cn,
Uuid: user.Uuid,
Email: util.GetMaxLenStr(user.Mail, user.Email, user.EmailAddress),
Phone: util.GetMaxLenStr(user.TelephoneNumber, user.Mobile, user.MobileTelephoneNumber),
Address: util.GetMaxLenStr(user.RegisteredAddress, user.PostalAddress),
})
uuids := make([]string, len(users))
for i, user := range users {
uuids[i] = user.GetLdapUuid()
}
c.Data["json"] = Response{Status: "ok", Data: resp}
c.ServeJSON()
}
// GetLdaps
// @Tag Account API
// @Title GetLdaps
// @router /get-ldaps [post]
func (c *ApiController) GetLdaps() {
owner := c.Input().Get("owner")
c.Data["json"] = Response{Status: "ok", Data: object.GetLdaps(owner)}
c.ServeJSON()
}
// GetLdap
// @Tag Account API
// @Title GetLdap
// @router /get-ldap [post]
func (c *ApiController) GetLdap() {
id := c.Input().Get("id")
if util.IsStrsEmpty(id) {
c.ResponseError("Missing parameter")
existUuids, err := object.GetExistUuids(ldapServer.Owner, uuids)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = Response{Status: "ok", Data: object.GetLdap(id)}
c.ServeJSON()
resp := LdapResp{
Users: object.AutoAdjustLdapUser(users),
ExistUuids: existUuids,
}
c.ResponseOk(resp)
}
// GetLdaps
// @Title GetLdaps
// @Tag Account API
// @Description get ldaps
// @Param owner query string false "owner"
// @Success 200 {array} object.Ldap The Response object
// @router /get-ldaps [get]
func (c *ApiController) GetLdaps() {
owner := c.Ctx.Input.Query("owner")
c.ResponseOk(object.GetMaskedLdaps(object.GetLdaps(owner)))
}
// GetLdap
// @Title GetLdap
// @Tag Account API
// @Description get ldap
// @Param id query string true "id"
// @Success 200 {object} object.Ldap The Response object
// @router /get-ldap [get]
func (c *ApiController) GetLdap() {
id := c.Ctx.Input.Query("id")
if util.IsStringsEmpty(id) {
c.ResponseError(c.T("general:Missing parameter"))
return
}
_, name, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
c.ResponseError(err.Error())
return
}
ldap, err := object.GetLdap(name)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedLdap(ldap))
}
// AddLdap
// @Tag Account API
// @Title AddLdap
// @Tag Account API
// @Description add ldap
// @Param body body object.Ldap true "The details of the ldap"
// @Success 200 {object} controllers.Response The Response object
// @router /add-ldap [post]
func (c *ApiController) AddLdap() {
var ldap object.Ldap
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldap)
if err != nil {
c.ResponseError("Missing parameter")
c.ResponseError(err.Error())
return
}
if util.IsStrsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Admin, ldap.Passwd, ldap.BaseDn) {
c.ResponseError("Missing parameter")
if util.IsStringsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Username, ldap.Password, ldap.BaseDn) {
c.ResponseError(c.T("general:Missing parameter"))
return
}
if object.CheckLdapExist(&ldap) {
c.ResponseError("Ldap server exist")
if ok, err := object.CheckLdapExist(&ldap); err != nil {
c.ResponseError(err.Error())
return
} else if ok {
c.ResponseError(c.T("ldap:Ldap server exist"))
return
}
affected := object.AddLdap(&ldap)
resp := wrapActionResponse(affected)
if affected {
resp.Data2 = ldap
}
resp := wrapActionResponse(object.AddLdap(&ldap))
resp.Data2 = ldap
if ldap.AutoSync != 0 {
object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
err = object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
if err != nil {
c.ResponseError(err.Error())
return
}
}
c.Data["json"] = resp
@@ -164,36 +191,52 @@ func (c *ApiController) AddLdap() {
}
// UpdateLdap
// @Tag Account API
// @Title UpdateLdap
// @Tag Account API
// @Description update ldap
// @Param body body object.Ldap true "The details of the ldap"
// @Success 200 {object} controllers.Response The Response object
// @router /update-ldap [post]
func (c *ApiController) UpdateLdap() {
var ldap object.Ldap
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldap)
if err != nil || util.IsStrsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Admin, ldap.Passwd, ldap.BaseDn) {
c.ResponseError("Missing parameter")
if err != nil || util.IsStringsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Username, ldap.Password, ldap.BaseDn) {
c.ResponseError(c.T("general:Missing parameter"))
return
}
prevLdap := object.GetLdap(ldap.Id)
affected := object.UpdateLdap(&ldap)
resp := wrapActionResponse(affected)
if affected {
resp.Data2 = ldap
prevLdap, err := object.GetLdap(ldap.Id)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.UpdateLdap(&ldap)
if err != nil {
c.ResponseError(err.Error())
return
}
if ldap.AutoSync != 0 {
object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
err := object.GetLdapAutoSynchronizer().StartAutoSync(ldap.Id)
if err != nil {
c.ResponseError(err.Error())
return
}
} else if ldap.AutoSync == 0 && prevLdap.AutoSync != 0 {
object.GetLdapAutoSynchronizer().StopAutoSync(ldap.Id)
}
c.Data["json"] = resp
c.Data["json"] = wrapActionResponse(affected)
c.ServeJSON()
}
// DeleteLdap
// @Tag Account API
// @Title DeleteLdap
// @Tag Account API
// @Description delete ldap
// @Param body body object.Ldap true "The details of the ldap"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-ldap [post]
func (c *ApiController) DeleteLdap() {
var ldap object.Ldap
@@ -203,49 +246,54 @@ func (c *ApiController) DeleteLdap() {
return
}
affected, err := object.DeleteLdap(&ldap)
if err != nil {
c.ResponseError(err.Error())
return
}
object.GetLdapAutoSynchronizer().StopAutoSync(ldap.Id)
c.Data["json"] = wrapActionResponse(object.DeleteLdap(&ldap))
c.Data["json"] = wrapActionResponse(affected)
c.ServeJSON()
}
// SyncLdapUsers
// @Tag Account API
// @Title SyncLdapUsers
// @Tag Account API
// @Description sync ldap users
// @Param id query string true "id"
// @Success 200 {object} controllers.LdapSyncResp The Response object
// @router /sync-ldap-users [post]
func (c *ApiController) SyncLdapUsers() {
owner := c.Input().Get("owner")
ldapId := c.Input().Get("ldapId")
var users []object.LdapRespUser
err := json.Unmarshal(c.Ctx.Input.RequestBody, &users)
id := c.Ctx.Input.Query("id")
owner, ldapId, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
c.ResponseError(err.Error())
return
}
var users []object.LdapUser
err = json.Unmarshal(c.Ctx.Input.RequestBody, &users)
if err != nil {
c.ResponseError(err.Error())
return
}
object.UpdateLdapSyncTime(ldapId)
exist, failed := object.SyncLdapUsers(owner, users, ldapId)
c.Data["json"] = &Response{Status: "ok", Data: &LdapSyncResp{
Exist: *exist,
Failed: *failed,
}}
c.ServeJSON()
}
// CheckLdapUsersExist
// @Tag Account API
// @Title CheckLdapUserExist
// @router /check-ldap-users-exist [post]
func (c *ApiController) CheckLdapUsersExist() {
owner := c.Input().Get("owner")
var uuids []string
err := json.Unmarshal(c.Ctx.Input.RequestBody, &uuids)
err = object.UpdateLdapSyncTime(ldapId)
if err != nil {
c.ResponseError(err.Error())
return
}
exist := object.CheckLdapUuidExist(owner, uuids)
c.Data["json"] = &Response{Status: "ok", Data: exist}
c.ServeJSON()
exist, failed, err := object.SyncLdapUsers(owner, users, ldapId)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(&LdapSyncResp{
Exist: exist,
Failed: failed,
})
}

View File

@@ -1,131 +0,0 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/object"
"github.com/forestmgy/ldapserver"
"github.com/lor00x/goldap/message"
)
func StartLdapServer() {
server := ldapserver.NewServer()
routes := ldapserver.NewRouteMux()
routes.Bind(handleBind)
routes.Search(handleSearch).Label(" SEARCH****")
server.Handle(routes)
go server.ListenAndServe("0.0.0.0:" + conf.GetConfigString("ldapServerPort"))
// When CTRL+C, SIGINT and SIGTERM signal occurs
// Then stop server gracefully
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
close(ch)
server.Stop()
}
func handleBind(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetBindRequest()
res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess)
if r.AuthenticationChoice() == "simple" {
bindusername, bindorg, err := object.GetNameAndOrgFromDN(string(r.Name()))
if err != "" {
log.Printf("Bind failed ,ErrMsg=%s", err)
res.SetResultCode(ldapserver.LDAPResultInvalidDNSyntax)
res.SetDiagnosticMessage("bind failed ErrMsg: " + err)
w.Write(res)
return
}
bindpassword := string(r.AuthenticationSimple())
binduser, err := object.CheckUserPassword(bindorg, bindusername, bindpassword)
if err != "" {
log.Printf("Bind failed User=%s, Pass=%#v, ErrMsg=%s", string(r.Name()), r.Authentication(), err)
res.SetResultCode(ldapserver.LDAPResultInvalidCredentials)
res.SetDiagnosticMessage("invalid credentials ErrMsg: " + err)
w.Write(res)
return
}
if bindorg == "built-in" {
m.Client.IsGlobalAdmin, m.Client.IsOrgAdmin = true, true
} else if binduser.IsAdmin {
m.Client.IsOrgAdmin = true
}
m.Client.IsAuthenticated = true
m.Client.UserName = bindusername
m.Client.OrgName = bindorg
} else {
res.SetResultCode(ldapserver.LDAPResultAuthMethodNotSupported)
res.SetDiagnosticMessage("Authentication method not supported,Please use Simple Authentication")
}
w.Write(res)
}
func handleSearch(w ldapserver.ResponseWriter, m *ldapserver.Message) {
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
if !m.Client.IsAuthenticated {
res.SetResultCode(ldapserver.LDAPResultUnwillingToPerform)
w.Write(res)
return
}
r := m.GetSearchRequest()
if r.FilterString() == "(objectClass=*)" {
w.Write(res)
return
}
name, org, errCode := object.GetUserNameAndOrgFromBaseDnAndFilter(string(r.BaseObject()), r.FilterString())
if errCode != ldapserver.LDAPResultSuccess {
res.SetResultCode(errCode)
w.Write(res)
return
}
// Handle Stop Signal (server stop / client disconnected / Abandoned request....)
select {
case <-m.Done:
log.Print("Leaving handleSearch...")
return
default:
}
users, errCode := object.GetFilteredUsers(m, name, org)
if errCode != ldapserver.LDAPResultSuccess {
res.SetResultCode(errCode)
w.Write(res)
return
}
for i := 0; i < len(users); i++ {
user := users[i]
dn := fmt.Sprintf("cn=%s,%s", user.DisplayName, string(r.BaseObject()))
e := ldapserver.NewSearchResultEntry(dn)
e.AddAttribute("cn", message.AttributeValue(user.Name))
e.AddAttribute("uid", message.AttributeValue(user.Name))
e.AddAttribute("email", message.AttributeValue(user.Email))
e.AddAttribute("mobile", message.AttributeValue(user.Phone))
// e.AddAttribute("postalAddress", message.AttributeValue(user.Address[0]))
w.Write(e)
}
w.Write(res)
}

View File

@@ -26,8 +26,10 @@ type LinkForm struct {
}
// Unlink ...
// @router /unlink [post]
// @Tag Login API
// @Title Unlink
// @router /unlink [post]
// @Success 200 {object} object.Userinfo The Response object
func (c *ApiController) Unlink() {
user, ok := c.RequireSignedInUser()
if !ok {
@@ -45,33 +47,37 @@ func (c *ApiController) Unlink() {
// the user will be unlinked from the provider
unlinkedUser := form.User
if user.Id != unlinkedUser.Id && !user.IsGlobalAdmin {
if user.Id != unlinkedUser.Id && !user.IsGlobalAdmin() {
// if the user is not the same as the one we are unlinking, we need to make sure the user is the global admin.
c.ResponseError("You are not the global admin, you can't unlink other users")
c.ResponseError(c.T("link:You are not the global admin, you can't unlink other users"))
return
}
if user.Id == unlinkedUser.Id && !user.IsGlobalAdmin {
if user.Id == unlinkedUser.Id && !user.IsGlobalAdmin() {
// if the user is unlinking themselves, should check the provider can be unlinked, if not, we should return an error.
application := object.GetApplicationByUser(user)
application, err := object.GetApplicationByUser(user)
if err != nil {
c.ResponseError(err.Error())
return
}
if application == nil {
c.ResponseError("You can't unlink yourself, you are not a member of any application")
c.ResponseError(c.T("link:You can't unlink yourself, you are not a member of any application"))
return
}
if len(application.Providers) == 0 {
c.ResponseError("This application has no providers")
c.ResponseError(c.T("link:This application has no providers"))
return
}
provider := application.GetProviderItemByType(providerType)
if provider == nil {
c.ResponseError("This application has no providers of type " + providerType)
c.ResponseError(c.T("link:This application has no providers of type") + providerType)
return
}
if !provider.CanUnlink {
c.ResponseError("This provider can't be unlinked")
c.ResponseError(c.T("link:This provider can't be unlinked"))
return
}
@@ -84,12 +90,21 @@ func (c *ApiController) Unlink() {
value := object.GetUserField(&unlinkedUser, providerType)
if value == "" {
c.ResponseError("Please link first", value)
c.ResponseError(c.T("link:Please link first"), value)
return
}
object.ClearUserOAuthProperties(&unlinkedUser, providerType)
_, err = object.ClearUserOAuthProperties(&unlinkedUser, providerType)
if err != nil {
c.ResponseError(err.Error())
return
}
_, err = object.LinkUserAccount(&unlinkedUser, providerType, "")
if err != nil {
c.ResponseError(err.Error())
return
}
object.LinkUserAccount(&unlinkedUser, providerType, "")
c.ResponseOk()
}

112
controllers/mcp_server.go Normal file
View File

@@ -0,0 +1,112 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"net/http"
"net/http/httputil"
"net/url"
"github.com/casdoor/casdoor/mcpself"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// ProxyServer
// @Title ProxyServer
// @Tag Server API
// @Description proxy request to the upstream MCP server by Server URL
// @Param owner path string true "The owner name of the server"
// @Param name path string true "The name of the server"
// @Success 200 {object} mcp.McpResponse The Response object
// @router /server/:owner/:name [get,post]
func (c *ApiController) ProxyServer() {
owner := c.Ctx.Input.Param(":owner")
name := c.Ctx.Input.Param(":name")
var mcpReq *mcpself.McpRequest
err := json.Unmarshal(c.Ctx.Input.RequestBody, &mcpReq)
if err != nil {
c.McpResponseError(1, -32700, "Parse error", err.Error())
return
}
if util.IsStringsEmpty(owner, name) {
c.McpResponseError(1, -32600, "invalid server identifier", nil)
return
}
server, err := object.GetServer(util.GetId(owner, name))
if err != nil {
c.McpResponseError(mcpReq.ID, -32600, "server not found", err.Error())
return
}
if server == nil {
c.McpResponseError(mcpReq.ID, -32600, "server not found", nil)
return
}
if server.Url == "" {
c.McpResponseError(mcpReq.ID, -32600, "server URL is empty", nil)
return
}
targetUrl, err := url.Parse(server.Url)
if err != nil || !targetUrl.IsAbs() || targetUrl.Host == "" {
c.McpResponseError(mcpReq.ID, -32600, "server URL is invalid", nil)
return
}
if targetUrl.Scheme != "http" && targetUrl.Scheme != "https" {
c.McpResponseError(mcpReq.ID, -32600, "server URL scheme is invalid", nil)
return
}
if mcpReq.Method == "tools/call" {
var params mcpself.McpCallToolParams
err = json.Unmarshal(mcpReq.Params, &params)
if err != nil {
c.McpResponseError(mcpReq.ID, -32600, "Invalid request", err.Error())
return
}
for _, tool := range server.Tools {
if tool.Name == params.Name && !tool.IsAllowed {
c.McpResponseError(mcpReq.ID, -32600, "tool is forbidden", nil)
return
} else if tool.Name == params.Name {
break
}
}
}
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
proxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, proxyErr error) {
c.Ctx.Output.SetStatus(http.StatusBadGateway)
c.McpResponseError(mcpReq.ID, -32603, "failed to proxy server request: %s", proxyErr.Error())
}
proxy.Director = func(request *http.Request) {
request.URL.Scheme = targetUrl.Scheme
request.URL.Host = targetUrl.Host
request.Host = targetUrl.Host
request.URL.Path = targetUrl.Path
request.URL.RawPath = ""
request.URL.RawQuery = targetUrl.RawQuery
if server.Token != "" {
request.Header.Set("Authorization", "Bearer "+server.Token)
}
}
proxy.ServeHTTP(c.Ctx.ResponseWriter, c.Ctx.Request)
}

339
controllers/mfa.go Normal file
View File

@@ -0,0 +1,339 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"net/http"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// MfaSetupInitiate
// @Title MfaSetupInitiate
// @Tag MFA API
// @Description setup MFA
// @param owner form string true "owner of user"
// @param name form string true "name of user"
// @param type form string true "MFA auth type"
// @Success 200 {object} controllers.Response The Response object
// @router /mfa/setup/initiate [post]
func (c *ApiController) MfaSetupInitiate() {
owner := c.Ctx.Request.Form.Get("owner")
name := c.Ctx.Request.Form.Get("name")
mfaType := c.Ctx.Request.Form.Get("mfaType")
userId := util.GetId(owner, name)
if len(userId) == 0 {
c.ResponseError(http.StatusText(http.StatusBadRequest))
return
}
MfaUtil := object.GetMfaUtil(mfaType, nil)
if MfaUtil == nil {
c.ResponseError("Invalid auth type")
}
user, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError("User doesn't exist")
return
}
organization, err := object.GetOrganizationByUser(user)
if err != nil {
c.ResponseError(err.Error())
return
}
issuer := ""
if organization != nil && organization.DisplayName != "" {
issuer = organization.DisplayName
} else if organization != nil {
issuer = organization.Name
}
mfaProps, err := MfaUtil.Initiate(user.GetId(), issuer)
if err != nil {
c.ResponseError(err.Error())
return
}
recoveryCode := util.GenerateUUID()
mfaProps.RecoveryCodes = []string{recoveryCode}
mfaProps.MfaRememberInHours = organization.MfaRememberInHours
resp := mfaProps
c.ResponseOk(resp)
}
// MfaSetupVerify
// @Title MfaSetupVerify
// @Tag MFA API
// @Description setup verify totp
// @param secret form string true "MFA secret"
// @param passcode form string true "MFA passcode"
// @Success 200 {object} controllers.Response The Response object
// @router /mfa/setup/verify [post]
func (c *ApiController) MfaSetupVerify() {
mfaType := c.Ctx.Request.Form.Get("mfaType")
passcode := c.Ctx.Request.Form.Get("passcode")
secret := c.Ctx.Request.Form.Get("secret")
dest := c.Ctx.Request.Form.Get("dest")
countryCode := c.Ctx.Request.Form.Get("countryCode")
if mfaType == "" || passcode == "" {
c.ResponseError("missing auth type or passcode")
return
}
config := &object.MfaProps{
MfaType: mfaType,
}
if mfaType == object.TotpType {
if secret == "" {
c.ResponseError("totp secret is missing")
return
}
config.Secret = secret
} else if mfaType == object.SmsType {
if dest == "" {
c.ResponseError("destination is missing")
return
}
config.Secret = dest
if countryCode == "" {
c.ResponseError("country code is missing")
return
}
config.CountryCode = countryCode
} else if mfaType == object.EmailType {
if dest == "" {
c.ResponseError("destination is missing")
return
}
config.Secret = dest
} else if mfaType == object.RadiusType {
if dest == "" {
c.ResponseError("RADIUS username is missing")
return
}
config.Secret = dest
if secret == "" {
c.ResponseError("RADIUS provider is missing")
return
}
config.URL = secret
} else if mfaType == object.PushType {
if dest == "" {
c.ResponseError("push notification receiver is missing")
return
}
config.Secret = dest
if secret == "" {
c.ResponseError("push notification provider is missing")
return
}
config.URL = secret
}
mfaUtil := object.GetMfaUtil(mfaType, config)
if mfaUtil == nil {
c.ResponseError("Invalid multi-factor authentication type")
return
}
err := mfaUtil.SetupVerify(passcode)
if err != nil {
c.ResponseError(err.Error())
} else {
c.ResponseOk(http.StatusText(http.StatusOK))
}
}
// MfaSetupEnable
// @Title MfaSetupEnable
// @Tag MFA API
// @Description enable totp
// @param owner form string true "owner of user"
// @param name form string true "name of user"
// @param type form string true "MFA auth type"
// @Success 200 {object} controllers.Response The Response object
// @router /mfa/setup/enable [post]
func (c *ApiController) MfaSetupEnable() {
owner := c.Ctx.Request.Form.Get("owner")
name := c.Ctx.Request.Form.Get("name")
mfaType := c.Ctx.Request.Form.Get("mfaType")
secret := c.Ctx.Request.Form.Get("secret")
dest := c.Ctx.Request.Form.Get("dest")
countryCode := c.Ctx.Request.Form.Get("secret")
recoveryCodes := c.Ctx.Request.Form.Get("recoveryCodes")
user, err := object.GetUser(util.GetId(owner, name))
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError("User doesn't exist")
return
}
config := &object.MfaProps{
MfaType: mfaType,
}
if mfaType == object.TotpType {
if secret == "" {
c.ResponseError("totp secret is missing")
return
}
config.Secret = secret
} else if mfaType == object.EmailType {
if user.Email == "" {
if dest == "" {
c.ResponseError("destination is missing")
return
}
user.Email = dest
}
} else if mfaType == object.SmsType {
if user.Phone == "" {
if dest == "" {
c.ResponseError("destination is missing")
return
}
user.Phone = dest
if countryCode == "" {
c.ResponseError("country code is missing")
return
}
user.CountryCode = countryCode
}
} else if mfaType == object.RadiusType {
if dest == "" {
c.ResponseError("RADIUS username is missing")
return
}
config.Secret = dest
if secret == "" {
c.ResponseError("RADIUS provider is missing")
return
}
config.URL = secret
} else if mfaType == object.PushType {
if dest == "" {
c.ResponseError("push notification receiver is missing")
return
}
config.Secret = dest
if secret == "" {
c.ResponseError("push notification provider is missing")
return
}
config.URL = secret
}
if recoveryCodes == "" {
c.ResponseError("recovery codes is missing")
return
}
config.RecoveryCodes = []string{recoveryCodes}
mfaUtil := object.GetMfaUtil(mfaType, config)
if mfaUtil == nil {
c.ResponseError("Invalid multi-factor authentication type")
return
}
err = mfaUtil.Enable(user)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(http.StatusText(http.StatusOK))
}
// DeleteMfa
// @Title DeleteMfa
// @Tag MFA API
// @Description: Delete MFA
// @param owner form string true "owner of user"
// @param name form string true "name of user"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-mfa/ [post]
func (c *ApiController) DeleteMfa() {
owner := c.Ctx.Request.Form.Get("owner")
name := c.Ctx.Request.Form.Get("name")
userId := util.GetId(owner, name)
user, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError("User doesn't exist")
return
}
err = object.DisabledMultiFactorAuth(user)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetAllMfaProps(user, true))
}
// SetPreferredMfa
// @Title SetPreferredMfa
// @Tag MFA API
// @Description: Set specific Mfa Preferred
// @param owner form string true "owner of user"
// @param name form string true "name of user"
// @param id form string true "id of user's MFA props"
// @Success 200 {object} controllers.Response The Response object
// @router /set-preferred-mfa [post]
func (c *ApiController) SetPreferredMfa() {
mfaType := c.Ctx.Request.Form.Get("mfaType")
owner := c.Ctx.Request.Form.Get("owner")
name := c.Ctx.Request.Form.Get("name")
userId := util.GetId(owner, name)
user, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError("User doesn't exist")
return
}
err = object.SetPreferredMultiFactorAuth(user, mfaType)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetAllMfaProps(user, true))
}

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +30,37 @@ import (
// @Success 200 {array} object.Model The Response object
// @router /get-models [get]
func (c *ApiController) GetModels() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetModels(owner)
c.ServeJSON()
models, err := object.GetModels(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(models)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetModelCount(owner, field, value)))
models := object.GetPaginationModels(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetModelCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
models, err := object.GetPaginationModels(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(models, paginator.Nums())
}
}
@@ -52,26 +69,31 @@ func (c *ApiController) GetModels() {
// @Title GetModel
// @Tag Model API
// @Description get model
// @Param id query string true "The id of the model"
// @Param id query string true "The id ( owner/name ) of the model"
// @Success 200 {object} object.Model The Response object
// @router /get-model [get]
func (c *ApiController) GetModel() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetModel(id)
c.ServeJSON()
model, err := object.GetModel(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(model)
}
// UpdateModel
// @Title UpdateModel
// @Tag Model API
// @Description update model
// @Param id query string true "The id of the model"
// @Param id query string true "The id ( owner/name ) of the model"
// @Param body body object.Model true "The details of the model"
// @Success 200 {object} controllers.Response The Response object
// @router /update-model [post]
func (c *ApiController) UpdateModel() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var model object.Model
err := json.Unmarshal(c.Ctx.Input.RequestBody, &model)
@@ -80,7 +102,7 @@ func (c *ApiController) UpdateModel() {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateModel(id, &model))
c.Data["json"] = wrapErrorResponse(object.UpdateModelWithCheck(id, &model))
c.ServeJSON()
}

74
controllers/oauth_dcr.go Normal file
View File

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

195
controllers/order.go Normal file
View File

@@ -0,0 +1,195 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetOrders
// @Title GetOrders
// @Tag Order API
// @Description get orders
// @Param owner query string true "The owner of orders"
// @Success 200 {array} object.Order The Response object
// @router /get-orders [get]
func (c *ApiController) GetOrders() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
var orders []*object.Order
var err error
if c.IsAdmin() {
// If field is "user", filter by that user even for admins
if field == "user" && value != "" {
orders, err = object.GetUserOrders(owner, value)
} else {
orders, err = object.GetOrders(owner)
}
} else {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
orders, err = object.GetUserOrders(owner, userName)
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(orders)
} else {
limit := util.ParseInt(limit)
if !c.IsAdmin() {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
field = "user"
value = userName
}
count, err := object.GetOrderCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
orders, err := object.GetPaginationOrders(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(orders, paginator.Nums())
}
}
// GetUserOrders
// @Title GetUserOrders
// @Tag Order API
// @Description get orders for a user
// @Param owner query string true "The owner of orders"
// @Param user query string true "The username of the user"
// @Success 200 {array} object.Order The Response object
// @router /get-user-orders [get]
func (c *ApiController) GetUserOrders() {
owner := c.Ctx.Input.Query("owner")
user := c.Ctx.Input.Query("user")
orders, err := object.GetUserOrders(owner, user)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(orders)
}
// GetOrder
// @Title GetOrder
// @Tag Order API
// @Description get order
// @Param id query string true "The id ( owner/name ) of the order"
// @Success 200 {object} object.Order The Response object
// @router /get-order [get]
func (c *ApiController) GetOrder() {
id := c.Ctx.Input.Query("id")
order, err := object.GetOrder(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(order)
}
// UpdateOrder
// @Title UpdateOrder
// @Tag Order API
// @Description update order
// @Param id query string true "The id ( owner/name ) of the order"
// @Param body body object.Order true "The details of the order"
// @Success 200 {object} controllers.Response The Response object
// @router /update-order [post]
func (c *ApiController) UpdateOrder() {
id := c.Ctx.Input.Query("id")
var order object.Order
err := json.Unmarshal(c.Ctx.Input.RequestBody, &order)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateOrder(id, &order))
c.ServeJSON()
}
// AddOrder
// @Title AddOrder
// @Tag Order API
// @Description add order
// @Param body body object.Order true "The details of the order"
// @Success 200 {object} controllers.Response The Response object
// @router /add-order [post]
func (c *ApiController) AddOrder() {
var order object.Order
err := json.Unmarshal(c.Ctx.Input.RequestBody, &order)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddOrder(&order))
c.ServeJSON()
}
// DeleteOrder
// @Title DeleteOrder
// @Tag Order API
// @Description delete order
// @Param body body object.Order true "The details of the order"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-order [post]
func (c *ApiController) DeleteOrder() {
var order object.Order
err := json.Unmarshal(c.Ctx.Input.RequestBody, &order)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteOrder(&order))
c.ServeJSON()
}

160
controllers/order_pay.go Normal file
View File

@@ -0,0 +1,160 @@
// Copyright 2025 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// PlaceOrder
// @Title PlaceOrder
// @Tag Order API
// @Description place an order for a product
// @Param productId query string true "The id ( owner/name ) of the product"
// @Param pricingName query string false "The name of the pricing (for subscription)"
// @Param planName query string false "The name of the plan (for subscription)"
// @Param customPrice query number false "Custom price for recharge products"
// @Param userName query string false "The username to place order for (admin only)"
// @Success 200 {object} object.Order The Response object
// @router /place-order [post]
func (c *ApiController) PlaceOrder() {
owner := c.Ctx.Input.Query("owner")
paidUserName := c.Ctx.Input.Query("userName")
var req struct {
ProductInfos []object.ProductInfo `json:"productInfos"`
}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
if err != nil {
c.ResponseError(err.Error())
return
}
productInfos := req.ProductInfos
if len(productInfos) == 0 {
c.ResponseError(c.T("product:Product list cannot be empty"))
return
}
var userId string
if paidUserName != "" {
userId = util.GetId(owner, paidUserName)
if userId != c.GetSessionUsername() && !c.IsAdmin() && userId != c.GetPaidUsername() {
c.ResponseError(c.T("general:Only admin user can specify user"))
return
}
c.SetSession("paidUsername", "")
} else {
userId = c.GetSessionUsername()
}
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
user, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), userId))
return
}
order, err := object.PlaceOrder(owner, productInfos, user)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(order)
}
// PayOrder
// @Title PayOrder
// @Tag Order API
// @Description pay an existing order
// @Param id query string true "The id ( owner/name ) of the order"
// @Param providerName query string true "The name of the provider"
// @Success 200 {object} controllers.Response The Response object
// @router /pay-order [post]
func (c *ApiController) PayOrder() {
id := c.Ctx.Input.Query("id")
host := c.Ctx.Request.Host
providerName := c.Ctx.Input.Query("providerName")
paymentEnv := c.Ctx.Input.Query("paymentEnv")
order, err := object.GetOrder(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if order == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The order: %s does not exist"), id))
return
}
userId := c.GetSessionUsername()
orderUserId := util.GetId(order.Owner, order.User)
if userId != orderUserId && !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
payment, attachInfo, err := object.PayOrder(providerName, host, paymentEnv, order, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payment, attachInfo)
}
// CancelOrder
// @Title CancelOrder
// @Tag Order API
// @Description cancel an order
// @Param id query string true "The id ( owner/name ) of the order"
// @Success 200 {object} controllers.Response The Response object
// @router /cancel-order [post]
func (c *ApiController) CancelOrder() {
id := c.Ctx.Input.Query("id")
order, err := object.GetOrder(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if order == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The order: %s does not exist"), id))
return
}
userId := c.GetSessionUsername()
orderUserId := util.GetId(order.Owner, order.User)
if userId != orderUserId && !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
c.Data["json"] = wrapActionResponse(object.CancelOrder(order))
c.ServeJSON()
}

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,21 +30,56 @@ import (
// @Success 200 {array} object.Organization The Response object
// @router /get-organizations [get]
func (c *ApiController) GetOrganizations() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
organizationName := c.Ctx.Input.Query("organizationName")
isGlobalAdmin := c.IsGlobalAdmin()
if limit == "" || page == "" {
c.Data["json"] = object.GetMaskedOrganizations(object.GetOrganizations(owner))
c.ServeJSON()
var organizations []*object.Organization
var err error
if isGlobalAdmin {
organizations, err = object.GetMaskedOrganizations(object.GetOrganizations(owner))
} else {
organizations, err = object.GetMaskedOrganizations(object.GetOrganizations(owner, c.getCurrentUser().Owner))
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(organizations)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetOrganizationCount(owner, field, value)))
organizations := object.GetMaskedOrganizations(object.GetPaginationOrganizations(owner, paginator.Offset(), limit, field, value, sortField, sortOrder))
c.ResponseOk(organizations, paginator.Nums())
if !isGlobalAdmin {
organizations, err := object.GetMaskedOrganizations(object.GetOrganizations(owner, c.getCurrentUser().Owner))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(organizations)
} else {
limit := util.ParseInt(limit)
count, err := object.GetOrganizationCount(owner, organizationName, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
organizations, err := object.GetMaskedOrganizations(object.GetPaginationOrganizations(owner, organizationName, paginator.Offset(), limit, field, value, sortField, sortOrder))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(organizations, paginator.Nums())
}
}
}
@@ -56,22 +91,30 @@ func (c *ApiController) GetOrganizations() {
// @Success 200 {object} object.Organization The Response object
// @router /get-organization [get]
func (c *ApiController) GetOrganization() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
organization, err := object.GetMaskedOrganization(object.GetOrganization(id))
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.GetMaskedOrganization(object.GetOrganization(id))
c.ServeJSON()
if organization != nil && organization.MfaRememberInHours == 0 {
organization.MfaRememberInHours = 12
}
c.ResponseOk(organization)
}
// UpdateOrganization ...
// @Title UpdateOrganization
// @Tag Organization API
// @Description update organization
// @Param id query string true "The id of the organization"
// @Param id query string true "The id ( owner/name ) of the organization"
// @Param body body object.Organization true "The details of the organization"
// @Success 200 {object} controllers.Response The Response object
// @router /update-organization [post]
func (c *ApiController) UpdateOrganization() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var organization object.Organization
err := json.Unmarshal(c.Ctx.Input.RequestBody, &organization)
@@ -80,7 +123,18 @@ func (c *ApiController) UpdateOrganization() {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateOrganization(id, &organization))
if err = object.CheckIpWhitelist(organization.IpWhitelist, c.GetAcceptLanguage()); err != nil {
c.ResponseError(err.Error())
return
}
isGlobalAdmin, _ := c.isGlobalAdmin()
if organization.BalanceCurrency == "" {
organization.BalanceCurrency = "USD"
}
c.Data["json"] = wrapActionResponse(object.UpdateOrganization(id, &organization, isGlobalAdmin))
c.ServeJSON()
}
@@ -99,6 +153,26 @@ func (c *ApiController) AddOrganization() {
return
}
count, err := object.GetOrganizationCount("", "", "", "")
if err != nil {
c.ResponseError(err.Error())
return
}
if err = checkQuotaForOrganization(int(count)); err != nil {
c.ResponseError(err.Error())
return
}
if err = object.CheckIpWhitelist(organization.IpWhitelist, c.GetAcceptLanguage()); err != nil {
c.ResponseError(err.Error())
return
}
if organization.BalanceCurrency == "" {
organization.BalanceCurrency = "USD"
}
c.Data["json"] = wrapActionResponse(object.AddOrganization(&organization))
c.ServeJSON()
}
@@ -127,17 +201,36 @@ func (c *ApiController) DeleteOrganization() {
// @Tag Organization API
// @Description get default application
// @Param id query string true "organization id"
// @Success 200 {object} Response The Response object
// @Success 200 {object} controllers.Response The Response object
// @router /get-default-application [get]
func (c *ApiController) GetDefaultApplication() {
userId := c.GetSessionUsername()
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
application := object.GetMaskedApplication(object.GetDefaultApplication(id), userId)
if application == nil {
c.ResponseError("Please set a default application for this organization")
application, err := object.GetDefaultApplication(id)
if err != nil {
c.ResponseError(err.Error())
return
}
application = object.GetMaskedApplication(application, userId)
c.ResponseOk(application)
}
// GetOrganizationNames ...
// @Title GetOrganizationNames
// @Tag Organization API
// @Param owner query string true "owner"
// @Description get all organization name and displayName
// @Success 200 {array} object.Organization The Response object
// @router /get-organization-names [get]
func (c *ApiController) GetOrganizationNames() {
owner := c.Ctx.Input.Query("owner")
organizationNames, err := object.GetOrganizationsByFields(owner, []string{"name", "display_name"}...)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(organizationNames)
}

View File

@@ -16,9 +16,8 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -31,20 +30,66 @@ import (
// @Success 200 {array} object.Payment The Response object
// @router /get-payments [get]
func (c *ApiController) GetPayments() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetPayments(owner)
c.ServeJSON()
var payments []*object.Payment
var err error
if c.IsAdmin() {
// If field is "user", filter by that user even for admins
if field == "user" && value != "" {
payments, err = object.GetUserPayments(owner, value)
} else {
payments, err = object.GetPayments(owner)
}
} else {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
payments, err = object.GetUserPayments(owner, userName)
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payments)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetPaymentCount(owner, field, value)))
payments := object.GetPaginationPayments(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if !c.IsAdmin() {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
field = "user"
value = userName
}
count, err := object.GetPaymentCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
payments, err := object.GetPaginationPayments(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payments, paginator.Nums())
}
}
@@ -59,11 +104,15 @@ func (c *ApiController) GetPayments() {
// @Success 200 {array} object.Payment The Response object
// @router /get-user-payments [get]
func (c *ApiController) GetUserPayments() {
owner := c.Input().Get("owner")
organization := c.Input().Get("organization")
user := c.Input().Get("user")
owner := c.Ctx.Input.Query("owner")
user := c.Ctx.Input.Query("user")
payments, err := object.GetUserPayments(owner, user)
if err != nil {
c.ResponseError(err.Error())
return
}
payments := object.GetUserPayments(owner, organization, user)
c.ResponseOk(payments)
}
@@ -71,26 +120,31 @@ func (c *ApiController) GetUserPayments() {
// @Title GetPayment
// @Tag Payment API
// @Description get payment
// @Param id query string true "The id of the payment"
// @Param id query string true "The id ( owner/name ) of the payment"
// @Success 200 {object} object.Payment The Response object
// @router /get-payment [get]
func (c *ApiController) GetPayment() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetPayment(id)
c.ServeJSON()
payment, err := object.GetPayment(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payment)
}
// UpdatePayment
// @Title UpdatePayment
// @Tag Payment API
// @Description update payment
// @Param id query string true "The id of the payment"
// @Param id query string true "The id ( owner/name ) of the payment"
// @Param body body object.Payment true "The details of the payment"
// @Success 200 {object} controllers.Response The Response object
// @router /update-payment [post]
func (c *ApiController) UpdatePayment() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var payment object.Payment
err := json.Unmarshal(c.Ctx.Input.RequestBody, &payment)
@@ -150,35 +204,35 @@ func (c *ApiController) DeletePayment() {
// @router /notify-payment [post]
func (c *ApiController) NotifyPayment() {
owner := c.Ctx.Input.Param(":owner")
providerName := c.Ctx.Input.Param(":provider")
productName := c.Ctx.Input.Param(":product")
paymentName := c.Ctx.Input.Param(":payment")
body := c.Ctx.Input.RequestBody
ok := object.NotifyPayment(c.Ctx.Request, body, owner, providerName, productName, paymentName)
if ok {
_, err := c.Ctx.ResponseWriter.Write([]byte("success"))
if err != nil {
c.ResponseError(err.Error())
return
}
} else {
panic(fmt.Errorf("NotifyPayment() failed: %v", ok))
payment, err := object.NotifyPayment(body, owner, paymentName, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payment)
}
// InvoicePayment
// @Title InvoicePayment
// @Tag Payment API
// @Description invoice payment
// @Param id query string true "The id of the payment"
// @Param id query string true "The id ( owner/name ) of the payment"
// @Success 200 {object} controllers.Response The Response object
// @router /invoice-payment [post]
func (c *ApiController) InvoicePayment() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
payment, err := object.GetPayment(id)
if err != nil {
c.ResponseError(err.Error())
return
}
payment := object.GetPayment(id)
invoiceUrl, err := object.InvoicePayment(payment)
if err != nil {
c.ResponseError(err.Error())

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +30,37 @@ import (
// @Success 200 {array} object.Permission The Response object
// @router /get-permissions [get]
func (c *ApiController) GetPermissions() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetPermissions(owner)
c.ServeJSON()
permissions, err := object.GetPermissions(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(permissions)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetPermissionCount(owner, field, value)))
permissions := object.GetPaginationPermissions(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetPermissionCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
permissions, err := object.GetPaginationPermissions(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(permissions, paginator.Nums())
}
}
@@ -60,35 +77,62 @@ func (c *ApiController) GetPermissionsBySubmitter() {
return
}
permissions := object.GetPermissionsBySubmitter(user.Owner, user.Name)
permissions, err := object.GetPermissionsBySubmitter(user.Owner, user.Name)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(permissions, len(permissions))
}
// GetPermissionsByRole
// @Title GetPermissionsByRole
// @Tag Permission API
// @Description get permissions by role
// @Param id query string true "The id ( owner/name ) of the role"
// @Success 200 {array} object.Permission The Response object
// @router /get-permissions-by-role [get]
func (c *ApiController) GetPermissionsByRole() {
id := c.Ctx.Input.Query("id")
permissions, err := object.GetPermissionsByRole(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(permissions, len(permissions))
return
}
// GetPermission
// @Title GetPermission
// @Tag Permission API
// @Description get permission
// @Param id query string true "The id of the permission"
// @Param id query string true "The id ( owner/name ) of the permission"
// @Success 200 {object} object.Permission The Response object
// @router /get-permission [get]
func (c *ApiController) GetPermission() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetPermission(id)
c.ServeJSON()
permission, err := object.GetPermission(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(permission)
}
// UpdatePermission
// @Title UpdatePermission
// @Tag Permission API
// @Description update permission
// @Param id query string true "The id of the permission"
// @Param id query string true "The id ( owner/name ) of the permission"
// @Param body body object.Permission true "The details of the permission"
// @Success 200 {object} controllers.Response The Response object
// @router /update-permission [post]
func (c *ApiController) UpdatePermission() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var permission object.Permission
err := json.Unmarshal(c.Ctx.Input.RequestBody, &permission)

View File

@@ -0,0 +1,58 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"os"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
func (c *ApiController) UploadPermissions() {
userId := c.GetSessionUsername()
owner, user, err := util.GetOwnerAndNameFromIdWithError(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
file, header, err := c.Ctx.Request.FormFile("file")
if err != nil {
c.ResponseError(err.Error())
return
}
fileId := fmt.Sprintf("%s_%s_%s", owner, user, util.RemoveExt(header.Filename))
path := util.GetUploadXlsxPath(fileId)
defer os.Remove(path)
err = saveFile(path, &file)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.UploadPermissions(owner, path)
if err != nil {
c.ResponseError(err.Error())
}
if affected {
c.ResponseOk()
} else {
c.ResponseError(c.T("general:Failed to import users"))
}
}

187
controllers/plan.go Normal file
View File

@@ -0,0 +1,187 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetPlans
// @Title GetPlans
// @Tag Plan API
// @Description get plans
// @Param owner query string true "The owner of plans"
// @Success 200 {array} object.Plan The Response object
// @router /get-plans [get]
func (c *ApiController) GetPlans() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
plans, err := object.GetPlans(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(plans)
} else {
limit := util.ParseInt(limit)
count, err := object.GetPlanCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
plan, err := object.GetPaginatedPlans(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(plan, paginator.Nums())
}
}
// GetPlan
// @Title GetPlan
// @Tag Plan API
// @Description get plan
// @Param id query string true "The id ( owner/name ) of the plan"
// @Param includeOption query bool false "Should include plan's option"
// @Success 200 {object} object.Plan The Response object
// @router /get-plan [get]
func (c *ApiController) GetPlan() {
id := c.Ctx.Input.Query("id")
includeOption := c.Ctx.Input.Query("includeOption") == "true"
plan, err := object.GetPlan(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if plan != nil && includeOption {
options, err := object.GetPermissionsByRole(plan.Role)
if err != nil {
c.ResponseError(err.Error())
return
}
for _, option := range options {
plan.Options = append(plan.Options, option.DisplayName)
}
}
c.ResponseOk(plan)
}
// UpdatePlan
// @Title UpdatePlan
// @Tag Plan API
// @Description update plan
// @Param id query string true "The id ( owner/name ) of the plan"
// @Param body body object.Plan true "The details of the plan"
// @Success 200 {object} controllers.Response The Response object
// @router /update-plan [post]
func (c *ApiController) UpdatePlan() {
id := c.Ctx.Input.Query("id")
owner := util.GetOwnerFromId(id)
var plan object.Plan
err := json.Unmarshal(c.Ctx.Input.RequestBody, &plan)
if err != nil {
c.ResponseError(err.Error())
return
}
if plan.Product != "" {
productId := util.GetId(owner, plan.Product)
product, err := object.GetProduct(productId)
if err != nil {
c.ResponseError(err.Error())
return
}
if product != nil {
object.UpdateProductForPlan(&plan, product)
_, err = object.UpdateProduct(productId, product)
if err != nil {
c.ResponseError(err.Error())
return
}
}
}
c.Data["json"] = wrapActionResponse(object.UpdatePlan(id, &plan))
c.ServeJSON()
}
// AddPlan
// @Title AddPlan
// @Tag Plan API
// @Description add plan
// @Param body body object.Plan true "The details of the plan"
// @Success 200 {object} controllers.Response The Response object
// @router /add-plan [post]
func (c *ApiController) AddPlan() {
var plan object.Plan
err := json.Unmarshal(c.Ctx.Input.RequestBody, &plan)
if err != nil {
c.ResponseError(err.Error())
return
}
// Create a related product for plan
product := object.CreateProductForPlan(&plan)
_, err = object.AddProduct(product)
if err != nil {
c.ResponseError(err.Error())
return
}
plan.Product = product.Name
c.Data["json"] = wrapActionResponse(object.AddPlan(&plan))
c.ServeJSON()
}
// DeletePlan
// @Title DeletePlan
// @Tag Plan API
// @Description delete plan
// @Param body body object.Plan true "The details of the plan"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-plan [post]
func (c *ApiController) DeletePlan() {
var plan object.Plan
err := json.Unmarshal(c.Ctx.Input.RequestBody, &plan)
if err != nil {
c.ResponseError(err.Error())
return
}
if plan.Product != "" {
_, err = object.DeleteProduct(&object.Product{Owner: plan.Owner, Name: plan.Product})
if err != nil {
c.ResponseError(err.Error())
return
}
}
c.Data["json"] = wrapActionResponse(object.DeletePlan(&plan))
c.ServeJSON()
}

145
controllers/pricing.go Normal file
View File

@@ -0,0 +1,145 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetPricings
// @Title GetPricings
// @Tag Pricing API
// @Description get pricings
// @Param owner query string true "The owner of pricings"
// @Success 200 {array} object.Pricing The Response object
// @router /get-pricings [get]
func (c *ApiController) GetPricings() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
pricings, err := object.GetPricings(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(pricings)
} else {
limit := util.ParseInt(limit)
count, err := object.GetPricingCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
pricing, err := object.GetPaginatedPricings(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(pricing, paginator.Nums())
}
}
// GetPricing
// @Title GetPricing
// @Tag Pricing API
// @Description get pricing
// @Param id query string true "The id ( owner/name ) of the pricing"
// @Success 200 {object} object.Pricing The Response object
// @router /get-pricing [get]
func (c *ApiController) GetPricing() {
id := c.Ctx.Input.Query("id")
pricing, err := object.GetPricing(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(pricing)
}
// UpdatePricing
// @Title UpdatePricing
// @Tag Pricing API
// @Description update pricing
// @Param id query string true "The id ( owner/name ) of the pricing"
// @Param body body object.Pricing true "The details of the pricing"
// @Success 200 {object} controllers.Response The Response object
// @router /update-pricing [post]
func (c *ApiController) UpdatePricing() {
id := c.Ctx.Input.Query("id")
var pricing object.Pricing
err := json.Unmarshal(c.Ctx.Input.RequestBody, &pricing)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdatePricing(id, &pricing))
c.ServeJSON()
}
// AddPricing
// @Title AddPricing
// @Tag Pricing API
// @Description add pricing
// @Param body body object.Pricing true "The details of the pricing"
// @Success 200 {object} controllers.Response The Response object
// @router /add-pricing [post]
func (c *ApiController) AddPricing() {
var pricing object.Pricing
err := json.Unmarshal(c.Ctx.Input.RequestBody, &pricing)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddPricing(&pricing))
c.ServeJSON()
}
// DeletePricing
// @Title DeletePricing
// @Tag Pricing API
// @Description delete pricing
// @Param body body object.Pricing true "The details of the pricing"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-pricing [post]
func (c *ApiController) DeletePricing() {
var pricing object.Pricing
err := json.Unmarshal(c.Ctx.Input.RequestBody, &pricing)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeletePricing(&pricing))
c.ServeJSON()
}

View File

@@ -17,8 +17,9 @@ package controllers
import (
"encoding/json"
"fmt"
"strconv"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -31,20 +32,37 @@ import (
// @Success 200 {array} object.Product The Response object
// @router /get-products [get]
func (c *ApiController) GetProducts() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetProducts(owner)
c.ServeJSON()
products, err := object.GetProducts(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(products)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetProductCount(owner, field, value)))
products := object.GetPaginationProducts(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetProductCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
products, err := object.GetPaginationProducts(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(products, paginator.Nums())
}
}
@@ -53,29 +71,37 @@ func (c *ApiController) GetProducts() {
// @Title GetProduct
// @Tag Product API
// @Description get product
// @Param id query string true "The id of the product"
// @Param id query string true "The id ( owner/name ) of the product"
// @Success 200 {object} object.Product The Response object
// @router /get-product [get]
func (c *ApiController) GetProduct() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
product := object.GetProduct(id)
object.ExtendProductWithProviders(product)
product, err := object.GetProduct(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = product
c.ServeJSON()
err = object.ExtendProductWithProviders(product)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(product)
}
// UpdateProduct
// @Title UpdateProduct
// @Tag Product API
// @Description update product
// @Param id query string true "The id of the product"
// @Param id query string true "The id ( owner/name ) of the product"
// @Param body body object.Product true "The details of the product"
// @Success 200 {object} controllers.Response The Response object
// @router /update-product [post]
func (c *ApiController) UpdateProduct() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var product object.Product
err := json.Unmarshal(c.Ctx.Input.RequestBody, &product)
@@ -127,35 +153,76 @@ func (c *ApiController) DeleteProduct() {
}
// BuyProduct
// @Title BuyProduct
// @Title BuyProduct (Deprecated)
// @Tag Product API
// @Description buy product
// @Param id query string true "The id of the product"
// @Param providerName query string true "The name of the provider"
// @Description buy product using the deprecated compatibility endpoint, prefer place-order plus pay-order for new integrations
// @Param id query string true "The id ( owner/name ) of the product"
// @Param providerName query string true "The name of the provider"
// @Param pricingName query string false "The name of the pricing (for subscription)"
// @Param planName query string false "The name of the plan (for subscription)"
// @Param userName query string false "The username to buy product for (admin only)"
// @Param paymentEnv query string false "The payment environment"
// @Param customPrice query number false "Custom price for recharge products"
// @Success 200 {object} controllers.Response The Response object
// @router /buy-product [post]
func (c *ApiController) BuyProduct() {
id := c.Input().Get("id")
providerName := c.Input().Get("providerName")
id := c.Ctx.Input.Query("id")
host := c.Ctx.Request.Host
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please login first")
return
providerName := c.Ctx.Input.Query("providerName")
paymentEnv := c.Ctx.Input.Query("paymentEnv")
customPriceStr := c.Ctx.Input.Query("customPrice")
if customPriceStr == "" {
customPriceStr = "0"
}
user := object.GetUser(userId)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", userId))
return
}
payUrl, err := object.BuyProduct(id, providerName, user, host)
customPrice, err := strconv.ParseFloat(customPriceStr, 64)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payUrl)
pricingName := c.Ctx.Input.Query("pricingName")
planName := c.Ctx.Input.Query("planName")
paidUserName := c.Ctx.Input.Query("userName")
owner, _, err := util.GetOwnerAndNameFromIdWithError(id)
if err != nil {
c.ResponseError(err.Error())
return
}
var userId string
if paidUserName != "" {
userId = util.GetId(owner, paidUserName)
if userId != c.GetSessionUsername() && !c.IsAdmin() && userId != c.GetPaidUsername() {
c.ResponseError(c.T("general:Only admin user can specify user"))
return
}
c.SetSession("paidUsername", "")
} else {
userId = c.GetSessionUsername()
}
if userId == "" {
c.ResponseError(c.T("general:Please login first"))
return
}
user, err := object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), userId))
return
}
payment, attachInfo, err := object.BuyProduct(id, user, providerName, pricingName, planName, host, paymentEnv, customPrice, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(payment, attachInfo)
}

54
controllers/prometheus.go Normal file
View File

@@ -0,0 +1,54 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"github.com/casdoor/casdoor/object"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// GetPrometheusInfo
// @Title GetPrometheusInfo
// @Tag System API
// @Description get Prometheus Info
// @Success 200 {object} object.PrometheusInfo The Response object
// @router /get-prometheus-info [get]
func (c *ApiController) GetPrometheusInfo() {
_, ok := c.RequireAdmin()
if !ok {
return
}
prometheusInfo, err := object.GetPrometheusInfo()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(prometheusInfo)
}
// GetMetrics
// @Title GetMetrics
// @Tag System API
// @Description get Prometheus metrics
// @Success 200 {string} Prometheus metrics in text format
// @router /metrics [get]
func (c *ApiController) GetMetrics() {
_, ok := c.RequireAdmin()
if !ok {
return
}
promhttp.Handler().ServeHTTP(c.Ctx.ResponseWriter, c.Ctx.Request)
}

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +30,90 @@ import (
// @Success 200 {array} object.Provider The Response object
// @router /get-providers [get]
func (c *ApiController) GetProviders() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
ok, isMaskEnabled := c.IsMaskedEnabled()
if !ok {
return
}
if limit == "" || page == "" {
c.Data["json"] = object.GetMaskedProviders(object.GetProviders(owner))
c.ServeJSON()
providers, err := object.GetProviders(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedProviders(providers, isMaskEnabled))
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetProviderCount(owner, field, value)))
providers := object.GetMaskedProviders(object.GetPaginationProviders(owner, paginator.Offset(), limit, field, value, sortField, sortOrder))
count, err := object.GetProviderCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
paginationProviders, err := object.GetPaginationProviders(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
providers := object.GetMaskedProviders(paginationProviders, isMaskEnabled)
c.ResponseOk(providers, paginator.Nums())
}
}
// GetGlobalProviders
// @Title GetGlobalProviders
// @Tag Provider API
// @Description get Global providers
// @Success 200 {array} object.Provider The Response object
// @router /get-global-providers [get]
func (c *ApiController) GetGlobalProviders() {
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
ok, isMaskEnabled := c.IsMaskedEnabled()
if !ok {
return
}
if limit == "" || page == "" {
globalProviders, err := object.GetGlobalProviders()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedProviders(globalProviders, isMaskEnabled))
} else {
limit := util.ParseInt(limit)
count, err := object.GetGlobalProviderCount(field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
paginationGlobalProviders, err := object.GetPaginationGlobalProviders(paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
providers := object.GetMaskedProviders(paginationGlobalProviders, isMaskEnabled)
c.ResponseOk(providers, paginator.Nums())
}
}
@@ -52,26 +122,49 @@ func (c *ApiController) GetProviders() {
// @Title GetProvider
// @Tag Provider API
// @Description get provider
// @Param id query string true "The id of the provider"
// @Param id query string true "The id ( owner/name ) of the provider"
// @Success 200 {object} object.Provider The Response object
// @router /get-provider [get]
func (c *ApiController) GetProvider() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetMaskedProvider(object.GetProvider(id))
c.ServeJSON()
ok, isMaskEnabled := c.IsMaskedEnabled()
if !ok {
return
}
provider, err := object.GetProvider(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedProvider(provider, isMaskEnabled))
}
func (c *ApiController) requireProviderPermission(provider *object.Provider) bool {
isGlobalAdmin, user := c.isGlobalAdmin()
if isGlobalAdmin {
return true
}
if provider.Owner == "admin" || user.Owner != provider.Owner {
c.ResponseError(c.T("auth:Unauthorized operation"))
return false
}
return true
}
// UpdateProvider
// @Title UpdateProvider
// @Tag Provider API
// @Description update provider
// @Param id query string true "The id of the provider"
// @Param id query string true "The id ( owner/name ) of the provider"
// @Param body body object.Provider true "The details of the provider"
// @Success 200 {object} controllers.Response The Response object
// @router /update-provider [post]
func (c *ApiController) UpdateProvider() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var provider object.Provider
err := json.Unmarshal(c.Ctx.Input.RequestBody, &provider)
@@ -80,6 +173,11 @@ func (c *ApiController) UpdateProvider() {
return
}
ok := c.requireProviderPermission(&provider)
if !ok {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateProvider(id, &provider))
c.ServeJSON()
}
@@ -99,6 +197,23 @@ func (c *ApiController) AddProvider() {
return
}
count, err := object.GetProviderCount("", "", "")
if err != nil {
c.ResponseError(err.Error())
return
}
err = checkQuotaForProvider(int(count))
if err != nil {
c.ResponseError(err.Error())
return
}
ok := c.requireProviderPermission(&provider)
if !ok {
return
}
c.Data["json"] = wrapActionResponse(object.AddProvider(&provider))
c.ServeJSON()
}
@@ -118,6 +233,11 @@ func (c *ApiController) DeleteProvider() {
return
}
ok := c.requireProviderPermission(&provider)
if !ok {
return
}
c.Data["json"] = wrapActionResponse(object.DeleteProvider(&provider))
c.ServeJSON()
}

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -36,20 +36,41 @@ func (c *ApiController) GetRecords() {
return
}
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
organizationName := c.Ctx.Input.Query("organizationName")
if limit == "" || page == "" {
c.Data["json"] = object.GetRecords()
c.ServeJSON()
records, err := object.GetRecords()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(records)
} else {
limit := util.ParseInt(limit)
if c.IsGlobalAdmin() && organizationName != "" {
organization = organizationName
}
filterRecord := &object.Record{Organization: organization}
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetRecordCount(field, value, filterRecord)))
records := object.GetPaginationRecords(paginator.Offset(), limit, field, value, sortField, sortOrder, filterRecord)
count, err := object.GetRecordCount(field, value, filterRecord)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
records, err := object.GetPaginationRecords(paginator.Offset(), limit, field, value, sortField, sortOrder, filterRecord)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(records, paginator.Nums())
}
}
@@ -62,6 +83,11 @@ func (c *ApiController) GetRecords() {
// @Success 200 {object} object.Record The Response object
// @router /get-records-filter [post]
func (c *ApiController) GetRecordsByFilter() {
_, ok := c.RequireAdmin()
if !ok {
return
}
body := string(c.Ctx.Input.RequestBody)
record := &object.Record{}
@@ -71,8 +97,13 @@ func (c *ApiController) GetRecordsByFilter() {
return
}
c.Data["json"] = object.GetRecordsByField(record)
c.ServeJSON()
records, err := object.GetRecordsByField(record)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(records)
}
// AddRecord

View File

@@ -20,33 +20,86 @@ import (
"fmt"
"io"
"mime"
"path"
"path/filepath"
"strings"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetResources
// @router /get-resources [get]
// @Tag Resource API
// @Title GetResources
// @Description get resources
// @Param owner query string true "Owner"
// @Param user query string true "User"
// @Param pageSize query integer false "Page Size"
// @Param p query integer false "Page Number"
// @Param field query string false "Field"
// @Param value query string false "Value"
// @Param sortField query string false "Sort Field"
// @Param sortOrder query string false "Sort Order"
// @Success 200 {array} object.Resource The Response object
// @router /get-resources [get]
func (c *ApiController) GetResources() {
owner := c.Input().Get("owner")
user := c.Input().Get("user")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetResources(owner, user)
c.ServeJSON()
owner := c.Ctx.Input.Query("owner")
user := c.Ctx.Input.Query("user")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
isOrgAdmin, ok := c.IsOrgAdmin()
if !ok {
return
}
if isOrgAdmin {
user = ""
}
if sortField == "Direct" {
provider, err := c.GetProviderFromContext("Storage")
if err != nil {
c.ResponseError(err.Error())
return
}
prefix := sortOrder
resources, err := object.GetDirectResources(owner, user, provider, prefix, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(resources)
} else if limit == "" || page == "" {
resources, err := object.GetResources(owner, user)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(resources)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetResourceCount(owner, user, field, value)))
resources := object.GetPaginationResources(owner, user, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetResourceCount(owner, user, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
resources, err := object.GetPaginationResources(owner, user, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(resources, paginator.Nums())
}
}
@@ -54,20 +107,32 @@ func (c *ApiController) GetResources() {
// GetResource
// @Tag Resource API
// @Title GetResource
// @Description get resource
// @Param id query string true "The id ( owner/name ) of resource"
// @Success 200 {object} object.Resource The Response object
// @router /get-resource [get]
func (c *ApiController) GetResource() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetResource(id)
c.ServeJSON()
resource, err := object.GetResource(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(resource)
}
// UpdateResource
// @Tag Resource API
// @Title UpdateResource
// @Description get resource
// @Param id query string true "The id ( owner/name ) of resource"
// @Param resource body object.Resource true "The resource object"
// @Success 200 {object} controllers.Response Success or error
// @router /update-resource [post]
func (c *ApiController) UpdateResource() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var resource object.Resource
err := json.Unmarshal(c.Ctx.Input.RequestBody, &resource)
@@ -83,6 +148,8 @@ func (c *ApiController) UpdateResource() {
// AddResource
// @Tag Resource API
// @Title AddResource
// @Param resource body object.Resource true "Resource object"
// @Success 200 {object} controllers.Response Success or error
// @router /add-resource [post]
func (c *ApiController) AddResource() {
var resource object.Resource
@@ -99,6 +166,8 @@ func (c *ApiController) AddResource() {
// DeleteResource
// @Tag Resource API
// @Title DeleteResource
// @Param resource body object.Resource true "Resource object"
// @Success 200 {object} controllers.Response Success or error
// @router /delete-resource [post]
func (c *ApiController) DeleteResource() {
var resource object.Resource
@@ -108,12 +177,25 @@ func (c *ApiController) DeleteResource() {
return
}
provider, _, ok := c.GetProviderFromContext("Storage")
if !ok {
if resource.Provider != "" {
inputs, _ := c.Input()
inputs.Set("provider", resource.Provider)
}
inputs, _ := c.Input()
inputs.Set("fullFilePath", resource.Name)
provider, err := c.GetProviderFromContext("Storage")
if err != nil {
c.ResponseError(err.Error())
return
}
_, resource.Name = refineFullFilePath(resource.Name)
err = object.DeleteFile(provider, resource.Name)
tag := c.Ctx.Input.Query("tag")
if tag == "Direct" {
resource.Name = path.Join(provider.PathPrefix, resource.Name)
}
err = object.DeleteFile(provider, resource.Name, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
@@ -126,16 +208,26 @@ func (c *ApiController) DeleteResource() {
// UploadResource
// @Tag Resource API
// @Title UploadResource
// @Param owner query string true "Owner"
// @Param user query string true "User"
// @Param application query string true "Application"
// @Param tag query string false "Tag"
// @Param parent query string false "Parent"
// @Param fullFilePath query string true "Full File Path"
// @Param createdTime query string false "Created Time"
// @Param description query string false "Description"
// @Param file formData file true "Resource file"
// @Success 200 {object} object.Resource FileUrl, objectKey
// @router /upload-resource [post]
func (c *ApiController) UploadResource() {
owner := c.Input().Get("owner")
username := c.Input().Get("user")
application := c.Input().Get("application")
tag := c.Input().Get("tag")
parent := c.Input().Get("parent")
fullFilePath := c.Input().Get("fullFilePath")
createdTime := c.Input().Get("createdTime")
description := c.Input().Get("description")
owner := c.Ctx.Input.Query("owner")
username := c.Ctx.Input.Query("user")
application := c.Ctx.Input.Query("application")
tag := c.Ctx.Input.Query("tag")
parent := c.Ctx.Input.Query("parent")
fullFilePath := c.Ctx.Input.Query("fullFilePath")
createdTime := c.Ctx.Input.Query("createdTime")
description := c.Ctx.Input.Query("description")
file, header, err := c.GetFile("file")
if err != nil {
@@ -145,7 +237,7 @@ func (c *ApiController) UploadResource() {
defer file.Close()
if username == "" || fullFilePath == "" {
c.ResponseError(fmt.Sprintf("username or fullFilePath is empty: username = %s, fullFilePath = %s", username, fullFilePath))
c.ResponseError(fmt.Sprintf(c.T("resource:Username or fullFilePath is empty: username = %s, fullFilePath = %s"), username, fullFilePath))
return
}
@@ -156,27 +248,52 @@ func (c *ApiController) UploadResource() {
return
}
provider, user, ok := c.GetProviderFromContext("Storage")
if !ok {
provider, err := c.GetProviderFromContext("Storage")
if err != nil {
c.ResponseError(err.Error())
return
}
_, fullFilePath = refineFullFilePath(fullFilePath)
fileType := "unknown"
contentType := header.Header.Get("Content-Type")
fileType, _ = util.GetOwnerAndNameFromId(contentType)
fileType, _ = util.GetOwnerAndNameFromIdNoCheck(contentType + "/")
if fileType != "image" && fileType != "video" {
ext := filepath.Ext(filename)
mimeType := mime.TypeByExtension(ext)
fileType, _ = util.GetOwnerAndNameFromId(mimeType)
fileType, _ = util.GetOwnerAndNameFromIdNoCheck(mimeType + "/")
}
fileUrl, objectKey, err := object.UploadFileSafe(provider, fullFilePath, fileBuffer)
fullFilePath = object.GetTruncatedPath(provider, fullFilePath, 450)
if tag != "avatar" && tag != "termsOfUse" && !strings.HasPrefix(tag, "idCard") {
ext := filepath.Ext(filepath.Base(fullFilePath))
index := len(fullFilePath) - len(ext)
for i := 1; ; i++ {
_, objectKey := object.GetUploadFileUrl(provider, fullFilePath, true)
if count, err := object.GetResourceCount(owner, username, "name", objectKey); err != nil {
c.ResponseError(err.Error())
return
} else if count == 0 {
break
}
// duplicated fullFilePath found, change it
fullFilePath = fullFilePath[:index] + fmt.Sprintf("-%d", i) + ext
}
}
fileUrl, objectKey, err := object.UploadFileSafe(provider, fullFilePath, fileBuffer, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
if username == "Built-in-Untracked" {
c.ResponseOk(fileUrl, objectKey)
return
}
if createdTime == "" {
createdTime = util.GetCurrentTime()
}
@@ -198,25 +315,84 @@ func (c *ApiController) UploadResource() {
Url: fileUrl,
Description: description,
}
object.AddOrUpdateResource(resource)
_, err = object.AddOrUpdateResource(resource)
if err != nil {
c.ResponseError(err.Error())
return
}
switch tag {
case "avatar":
user, err := object.GetUserNoCheck(util.GetId(owner, username))
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
user = object.GetUserNoCheck(username)
if user == nil {
c.ResponseError("user is nil for tag: \"avatar\"")
return
}
c.ResponseError(c.T("resource:User is nil for tag: avatar"))
return
}
user.Avatar = fileUrl
object.UpdateUser(user.GetId(), user, []string{"avatar"}, false)
_, err = object.UpdateUser(user.GetId(), user, []string{"avatar"}, false)
if err != nil {
c.ResponseError(err.Error())
return
}
case "termsOfUse":
applicationId := fmt.Sprintf("admin/%s", parent)
app := object.GetApplication(applicationId)
app.TermsOfUse = fileUrl
object.UpdateApplication(applicationId, app)
user, err := object.GetUserNoCheck(util.GetId(owner, username))
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The user: %s doesn't exist"), util.GetId(owner, username)))
return
}
if !user.IsAdminUser() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
_, applicationId := util.GetOwnerAndNameFromIdNoCheck(strings.TrimSuffix(fullFilePath, ".html"))
applicationObj, err := object.GetApplication(applicationId)
if err != nil {
c.ResponseError(err.Error())
return
}
applicationObj.TermsOfUse = fileUrl
_, err = object.UpdateApplication(applicationId, applicationObj, true, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
}
case "idCardFront", "idCardBack", "idCardWithPerson":
user, err := object.GetUserNoCheck(util.GetId(owner, username))
if err != nil {
c.ResponseError(err.Error())
return
}
if user == nil {
c.ResponseError(c.T("resource:User is nil for tag: avatar"))
return
}
if user.Properties == nil {
user.Properties = map[string]string{}
}
user.Properties[tag] = fileUrl
user.Properties["isIdCardVerified"] = "false"
_, err = object.UpdateUser(user.GetId(), user, []string{"properties"}, false)
if err != nil {
c.ResponseError(err.Error())
return
}
}
c.ResponseOk(fileUrl, objectKey)

View File

@@ -17,7 +17,7 @@ package controllers
import (
"encoding/json"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +30,37 @@ import (
// @Success 200 {array} object.Role The Response object
// @router /get-roles [get]
func (c *ApiController) GetRoles() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
c.Data["json"] = object.GetRoles(owner)
c.ServeJSON()
roles, err := object.GetRoles(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(roles)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetRoleCount(owner, field, value)))
roles := object.GetPaginationRoles(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetRoleCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
roles, err := object.GetPaginationRoles(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(roles, paginator.Nums())
}
}
@@ -52,26 +69,31 @@ func (c *ApiController) GetRoles() {
// @Title GetRole
// @Tag Role API
// @Description get role
// @Param id query string true "The id of the role"
// @Param id query string true "The id ( owner/name ) of the role"
// @Success 200 {object} object.Role The Response object
// @router /get-role [get]
func (c *ApiController) GetRole() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetRole(id)
c.ServeJSON()
role, err := object.GetRole(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(role)
}
// UpdateRole
// @Title UpdateRole
// @Tag Role API
// @Description update role
// @Param id query string true "The id of the role"
// @Param id query string true "The id ( owner/name ) of the role"
// @Param body body object.Role true "The details of the role"
// @Success 200 {object} controllers.Response The Response object
// @router /update-role [post]
func (c *ApiController) UpdateRole() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var role object.Role
err := json.Unmarshal(c.Ctx.Input.RequestBody, &role)

View File

@@ -0,0 +1,58 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"fmt"
"os"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
func (c *ApiController) UploadRoles() {
userId := c.GetSessionUsername()
owner, user, err := util.GetOwnerAndNameFromIdWithError(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
file, header, err := c.Ctx.Request.FormFile("file")
if err != nil {
c.ResponseError(err.Error())
return
}
fileId := fmt.Sprintf("%s_%s_%s", owner, user, util.RemoveExt(header.Filename))
path := util.GetUploadXlsxPath(fileId)
defer os.Remove(path)
err = saveFile(path, &file)
if err != nil {
c.ResponseError(err.Error())
return
}
affected, err := object.UploadRoles(owner, path)
if err != nil {
c.ResponseError(err.Error())
}
if affected {
c.ResponseOk()
} else {
c.ResponseError(c.T("general:Failed to import users"))
}
}

229
controllers/rule.go Normal file
View File

@@ -0,0 +1,229 @@
// Copyright 2023 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"errors"
"net"
"strings"
"github.com/beego/beego/v2/server/web/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
"github.com/hsluoyz/modsecurity-go/seclang/parser"
)
// GetRules
// @Title GetRules
// @Tag Rule API
// @Description get rules
// @Param owner query string true "The owner of rules"
// @Success 200 {array} object.Rule The Response object
// @router /get-rules [get]
func (c *ApiController) GetRules() {
owner := c.Ctx.Input.Query("owner")
if owner == "admin" {
owner = ""
}
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
rules, err := object.GetRules(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(rules)
} else {
limit := util.ParseInt(limit)
count, err := object.GetRuleCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limit, count)
rules, err := object.GetPaginationRules(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(rules, paginator.Nums())
}
}
// GetRule
// @Title GetRule
// @Tag Rule API
// @Description get rule
// @Param id query string true "The id ( owner/name ) of the rule"
// @Success 200 {object} object.Rule The Response object
// @router /get-rule [get]
func (c *ApiController) GetRule() {
id := c.Ctx.Input.Query("id")
rule, err := object.GetRule(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(rule)
}
// AddRule
// @Title AddRule
// @Tag Rule API
// @Description add rule
// @Param body body object.Rule true "The details of the rule"
// @Success 200 {object} controllers.Response The Response object
// @router /add-rule [post]
func (c *ApiController) AddRule() {
currentTime := util.GetCurrentTime()
rule := object.Rule{
CreatedTime: currentTime,
UpdatedTime: currentTime,
}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &rule)
if err != nil {
c.ResponseError(err.Error())
return
}
err = checkExpressions(rule.Expressions, rule.Type)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddRule(&rule))
c.ServeJSON()
}
// UpdateRule
// @Title UpdateRule
// @Tag Rule API
// @Description update rule
// @Param id query string true "The id ( owner/name ) of the rule"
// @Param body body object.Rule true "The details of the rule"
// @Success 200 {object} controllers.Response The Response object
// @router /update-rule [post]
func (c *ApiController) UpdateRule() {
var rule object.Rule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &rule)
if err != nil {
c.ResponseError(err.Error())
return
}
err = checkExpressions(rule.Expressions, rule.Type)
if err != nil {
c.ResponseError(err.Error())
return
}
id := c.Ctx.Input.Query("id")
c.Data["json"] = wrapActionResponse(object.UpdateRule(id, &rule))
c.ServeJSON()
}
// DeleteRule
// @Title DeleteRule
// @Tag Rule API
// @Description delete rule
// @Param body body object.Rule true "The details of the rule"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-rule [post]
func (c *ApiController) DeleteRule() {
var rule object.Rule
err := json.Unmarshal(c.Ctx.Input.RequestBody, &rule)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteRule(&rule))
c.ServeJSON()
}
func checkExpressions(expressions []*object.Expression, ruleType string) error {
values := make([]string, len(expressions))
for i, expression := range expressions {
values[i] = expression.Value
}
switch ruleType {
case "WAF":
return checkWafRule(values)
case "IP":
return checkIpRule(values)
case "IP Rate Limiting":
return checkIpRateRule(expressions)
case "Compound":
return checkCompoundRules(values)
}
return nil
}
func checkWafRule(rules []string) error {
for _, rule := range rules {
scanner := parser.NewSecLangScannerFromString(rule)
_, err := scanner.AllDirective()
if err != nil {
return err
}
}
return nil
}
func checkIpRule(ipLists []string) error {
for _, ipList := range ipLists {
for _, ip := range strings.Split(ipList, ",") {
_, _, err := net.ParseCIDR(ip)
if net.ParseIP(ip) == nil && err != nil {
return errors.New("Invalid IP address: " + ip)
}
}
}
return nil
}
func checkIpRateRule(expressions []*object.Expression) error {
if len(expressions) != 1 {
return errors.New("IP Rate Limiting rule must have exactly one expression")
}
expression := expressions[0]
_, err := util.ParseIntWithError(expression.Operator)
if err != nil {
return err
}
_, err = util.ParseIntWithError(expression.Value)
if err != nil {
return err
}
return nil
}
func checkCompoundRules(rules []string) error {
_, err := object.GetRulesByRuleIds(rules)
if err != nil {
return err
}
return nil
}

View File

@@ -16,19 +16,55 @@ package controllers
import (
"fmt"
"net/http"
"net/url"
"github.com/casdoor/casdoor/object"
)
func (c *ApiController) GetSamlMeta() {
host := c.Ctx.Request.Host
paramApp := c.Input().Get("application")
application := object.GetApplication(paramApp)
if application == nil {
c.ResponseError(fmt.Sprintf("err: application %s not found", paramApp))
paramApp := c.Ctx.Input.Query("application")
application, err := object.GetApplication(paramApp)
if err != nil {
c.ResponseError(err.Error())
return
}
metadata, _ := object.GetSamlMeta(application, host)
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("saml:Application %s not found"), paramApp))
return
}
enablePostBinding, err := c.GetBool("enablePostBinding", false)
if err != nil {
c.ResponseError(err.Error())
return
}
metadata, err := object.GetSamlMeta(application, host, enablePostBinding)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["xml"] = metadata
c.ServeXML()
}
func (c *ApiController) HandleSamlRedirect() {
host := c.Ctx.Request.Host
owner := c.Ctx.Input.Param(":owner")
application := c.Ctx.Input.Param(":application")
relayState := c.Ctx.Input.Query("RelayState")
samlRequest := c.Ctx.Input.Query("SAMLRequest")
username := c.Ctx.Input.Query("username")
loginHint := c.Ctx.Input.Query("login_hint")
relayState = url.QueryEscape(relayState)
targetURL := object.GetSamlRedirectAddress(owner, application, relayState, samlRequest, host, username, loginHint)
c.Redirect(targetURL, http.StatusSeeOther)
}

32
controllers/scim.go Normal file
View File

@@ -0,0 +1,32 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"strings"
"github.com/casdoor/casdoor/scim"
)
func (c *RootController) HandleScim() {
_, ok := c.RequireAdmin()
if !ok {
return
}
path := c.Ctx.Request.URL.Path
c.Ctx.Request.URL.Path = strings.TrimPrefix(path, "/scim")
scim.Server.ServeHTTP(c.Ctx.ResponseWriter, c.Ctx.Request)
}

173
controllers/server.go Normal file
View File

@@ -0,0 +1,173 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/server/web/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetServers
// @Title GetServers
// @Tag Server API
// @Description get servers
// @Param owner query string true "The owner of servers"
// @Success 200 {array} object.Server The Response object
// @router /get-servers [get]
func (c *ApiController) GetServers() {
owner := c.Ctx.Input.Query("owner")
if owner == "admin" {
owner = ""
}
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
servers, err := object.GetServers(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(servers)
return
}
limitInt := util.ParseInt(limit)
count, err := object.GetServerCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limitInt, count)
servers, err := object.GetPaginationServers(owner, paginator.Offset(), limitInt, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(servers, paginator.Nums())
}
// GetServer
// @Title GetServer
// @Tag Server API
// @Description get server
// @Param id query string true "The id ( owner/name ) of the server"
// @Success 200 {object} object.Server The Response object
// @router /get-server [get]
func (c *ApiController) GetServer() {
id := c.Ctx.Input.Query("id")
server, err := object.GetServer(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(server)
}
// UpdateServer
// @Title UpdateServer
// @Tag Server API
// @Description update server
// @Param id query string true "The id ( owner/name ) of the server"
// @Param body body object.Server true "The details of the server"
// @Success 200 {object} controllers.Response The Response object
// @router /update-server [post]
func (c *ApiController) UpdateServer() {
id := c.Ctx.Input.Query("id")
var server object.Server
err := json.Unmarshal(c.Ctx.Input.RequestBody, &server)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateServer(id, &server))
c.ServeJSON()
}
// SyncMcpTool
// @Title SyncMcpTool
// @Tag Server API
// @Description sync MCP tools for a server and return sync errors directly
// @Param id query string true "The id ( owner/name ) of the server"
// @Param isCleared query bool false "Whether to clear all tools instead of syncing"
// @Param body body object.Server true "The details of the server"
// @Success 200 {object} controllers.Response The Response object
// @router /sync-mcp-tool [post]
func (c *ApiController) SyncMcpTool() {
id := c.Ctx.Input.Query("id")
isCleared := c.Ctx.Input.Query("isCleared") == "1"
var server object.Server
err := json.Unmarshal(c.Ctx.Input.RequestBody, &server)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.SyncMcpTool(id, &server, isCleared))
c.ServeJSON()
}
// AddServer
// @Title AddServer
// @Tag Server API
// @Description add server
// @Param body body object.Server true "The details of the server"
// @Success 200 {object} controllers.Response The Response object
// @router /add-server [post]
func (c *ApiController) AddServer() {
var server object.Server
err := json.Unmarshal(c.Ctx.Input.RequestBody, &server)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddServer(&server))
c.ServeJSON()
}
// DeleteServer
// @Title DeleteServer
// @Tag Server API
// @Description delete server
// @Param body body object.Server true "The details of the server"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-server [post]
func (c *ApiController) DeleteServer() {
var server object.Server
err := json.Unmarshal(c.Ctx.Input.RequestBody, &server)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteServer(&server))
c.ServeJSON()
}

View File

@@ -0,0 +1,56 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
const onlineServerListUrl = "https://mcp.casdoor.org/registry.json"
// GetOnlineServers
// @Title GetOnlineServers
// @Tag Server API
// @Description get online MCP server list
// @Success 200 {object} controllers.Response The Response object
// @router /get-online-servers [get]
func (c *ApiController) GetOnlineServers() {
httpClient := &http.Client{Timeout: 10 * time.Second}
resp, err := httpClient.Get(onlineServerListUrl)
if err != nil {
c.ResponseError(err.Error())
return
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
c.ResponseError(fmt.Sprintf("failed to get online server list, status code: %d", resp.StatusCode))
return
}
var onlineServers interface{}
err = json.NewDecoder(resp.Body).Decode(&onlineServers)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(onlineServers)
}

170
controllers/server_sync.go Normal file
View File

@@ -0,0 +1,170 @@
// Copyright 2026 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"encoding/json"
"net/http"
"slices"
"strings"
"sync"
"time"
"github.com/casdoor/casdoor/mcp"
)
const (
defaultSyncTimeoutMs = 1200
defaultSyncMaxConcurrency = 32
maxSyncHosts = 1024
)
var (
defaultSyncPorts = []int{3000, 8080, 80}
defaultSyncPaths = []string{"/", "/mcp", "/sse", "/mcp/sse"}
)
type SyncInnerServersRequest struct {
CIDR []string `json:"cidr"`
Scheme string `json:"scheme"`
Ports []string `json:"ports"`
Paths []string `json:"paths"`
TimeoutMs int `json:"timeoutMs"`
MaxConcurrency int `json:"maxConcurrency"`
}
type SyncInnerServersResult struct {
CIDR []string `json:"cidr"`
ScannedHosts int `json:"scannedHosts"`
OnlineHosts []string `json:"onlineHosts"`
Servers []*mcp.InnerMcpServer `json:"servers"`
}
// SyncIntranetServers
// @Title SyncIntranetServers
// @Tag Server API
// @Description scan intranet IP/CIDR targets and detect MCP servers by probing common ports and paths
// @Param body body controllers.SyncInnerServersRequest true "Intranet MCP server scan request"
// @Success 200 {object} controllers.Response The Response object
// @router /sync-intranet-servers [post]
func (c *ApiController) SyncIntranetServers() {
_, ok := c.RequireAdmin()
if !ok {
return
}
var req SyncInnerServersRequest
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
c.ResponseError(err.Error())
return
}
for i := range req.CIDR {
req.CIDR[i] = strings.TrimSpace(req.CIDR[i])
}
if len(req.CIDR) == 0 {
c.ResponseError("scan target (CIDR/IP) is required")
return
}
hosts, err := mcp.ParseScanTargets(req.CIDR, maxSyncHosts)
if err != nil {
c.ResponseError(err.Error())
return
}
timeout := mcp.SanitizeTimeout(req.TimeoutMs, defaultSyncTimeoutMs, 10000)
concurrency := mcp.SanitizeConcurrency(req.MaxConcurrency, defaultSyncMaxConcurrency, 256)
ports := mcp.SanitizePorts(req.Ports, defaultSyncPorts)
paths := mcp.SanitizePaths(req.Paths, defaultSyncPaths)
scheme := mcp.SanitizeScheme(req.Scheme)
client := &http.Client{
Timeout: timeout,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
onlineHostSet := map[string]struct{}{}
serverMap := map[string]*mcp.InnerMcpServer{}
mutex := sync.Mutex{}
waitGroup := sync.WaitGroup{}
sem := make(chan struct{}, concurrency)
for _, host := range hosts {
host := host.String()
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
select {
case sem <- struct{}{}:
case <-ctx.Done():
return
}
defer func() { <-sem }()
isOnline, servers := mcp.ProbeHost(ctx, client, scheme, host, ports, paths, timeout)
if !isOnline {
return
}
mutex.Lock()
onlineHostSet[host] = struct{}{}
for _, server := range servers {
serverMap[server.Url] = server
}
mutex.Unlock()
}()
}
waitGroup.Wait()
onlineHosts := make([]string, 0, len(onlineHostSet))
for host := range onlineHostSet {
onlineHosts = append(onlineHosts, host)
}
slices.Sort(onlineHosts)
servers := make([]*mcp.InnerMcpServer, 0, len(serverMap))
for _, server := range serverMap {
servers = append(servers, server)
}
slices.SortFunc(servers, func(a, b *mcp.InnerMcpServer) int {
if a.Url < b.Url {
return -1
}
if a.Url > b.Url {
return 1
}
return 0
})
c.ResponseOk(&SyncInnerServersResult{
CIDR: req.CIDR,
ScannedHosts: len(hosts),
OnlineHosts: onlineHosts,
Servers: servers,
})
}
func (c *ApiController) SyncInnerServers() {
c.SyncIntranetServers()
}

View File

@@ -20,17 +20,19 @@ package controllers
import (
"encoding/json"
"fmt"
"strings"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
type EmailForm struct {
Title string `json:"title"`
Content string `json:"content"`
Sender string `json:"sender"`
Receivers []string `json:"receivers"`
Provider string `json:"provider"`
Title string `json:"title"`
Content string `json:"content"`
Sender string `json:"sender"`
Receivers []string `json:"receivers"`
Provider string `json:"provider"`
ProviderObject object.Provider `json:"providerObject"`
}
type SmsForm struct {
@@ -39,6 +41,10 @@ type SmsForm struct {
OrgId string `json:"organizationId"` // e.g. "admin/built-in"
}
type NotificationForm struct {
Content string `json:"content"`
}
// SendEmail
// @Title SendEmail
// @Tag Service API
@@ -46,11 +52,15 @@ type SmsForm struct {
// @Param clientId query string true "The clientId of the application"
// @Param clientSecret query string true "The clientSecret of the application"
// @Param from body controllers.EmailForm true "Details of the email request"
// @Success 200 {object} Response object
// @router /api/send-email [post]
// @Success 200 {object} controllers.Response The Response object
// @router /send-email [post]
func (c *ApiController) SendEmail() {
var emailForm EmailForm
userId, ok := c.RequireSignedIn()
if !ok {
return
}
var emailForm EmailForm
err := json.Unmarshal(c.Ctx.Input.RequestBody, &emailForm)
if err != nil {
c.ResponseError(err.Error())
@@ -60,19 +70,30 @@ func (c *ApiController) SendEmail() {
var provider *object.Provider
if emailForm.Provider != "" {
// called by frontend's TestEmailWidget, provider name is set by frontend
provider = object.GetProvider(fmt.Sprintf("admin/%s", emailForm.Provider))
provider, err = object.GetProvider(util.GetId("admin", emailForm.Provider))
if err != nil {
c.ResponseError(err.Error())
return
}
} else {
// called by Casdoor SDK via Client ID & Client Secret, so the used Email provider will be the application' Email provider or the default Email provider
var ok bool
provider, _, ok = c.GetProviderFromContext("Email")
if !ok {
provider, err = c.GetProviderFromContext("Email")
if err != nil {
c.ResponseError(err.Error())
return
}
}
if emailForm.ProviderObject.Name != "" {
if emailForm.ProviderObject.ClientSecret == "***" {
emailForm.ProviderObject.ClientSecret = provider.ClientSecret
}
provider = &emailForm.ProviderObject
}
// when receiver is the reserved keyword: "TestSmtpServer", it means to test the SMTP server instead of sending a real Email
if len(emailForm.Receivers) == 1 && emailForm.Receivers[0] == "TestSmtpServer" {
err := object.DailSmtpServer(provider)
err = object.TestSmtpServer(provider)
if err != nil {
c.ResponseError(err.Error())
return
@@ -80,8 +101,8 @@ func (c *ApiController) SendEmail() {
c.ResponseOk()
}
if util.IsStrsEmpty(emailForm.Title, emailForm.Content, emailForm.Sender) {
c.ResponseError(fmt.Sprintf("Empty parameters for emailForm: %v", emailForm))
if util.IsStringsEmpty(emailForm.Title, emailForm.Content, emailForm.Sender) {
c.ResponseError(fmt.Sprintf(c.T("service:Empty parameters for emailForm: %v"), emailForm))
return
}
@@ -93,12 +114,37 @@ func (c *ApiController) SendEmail() {
}
if len(invalidReceivers) != 0 {
c.ResponseError(fmt.Sprintf("Invalid Email receivers: %s", invalidReceivers))
c.ResponseError(fmt.Sprintf(c.T("service:Invalid Email receivers: %s"), invalidReceivers))
return
}
content := emailForm.Content
if content == "" {
content = provider.Content
}
code := "123456"
// "You have requested a verification code at Casdoor. Here is your code: %s, please enter in 5 minutes."
content = strings.Replace(content, "%s", code, 1)
userString := "Hi"
if !object.IsAppUser(userId) {
var user *object.User
user, err = object.GetUser(userId)
if err != nil {
c.ResponseError(err.Error())
return
}
if user != nil {
userString = user.GetFriendlyName()
}
}
content = strings.Replace(content, "%{user.friendlyName}", userString, 1)
matchContent := object.ResetLinkReg.Find([]byte(content))
content = strings.Replace(content, string(matchContent), "", -1)
for _, receiver := range emailForm.Receivers {
err = object.SendEmail(provider, emailForm.Title, emailForm.Content, receiver, emailForm.Sender)
err = object.SendEmail(provider, emailForm.Title, content, []string{receiver}, emailForm.Sender)
if err != nil {
c.ResponseError(err.Error())
return
@@ -115,34 +161,28 @@ func (c *ApiController) SendEmail() {
// @Param clientId query string true "The clientId of the application"
// @Param clientSecret query string true "The clientSecret of the application"
// @Param from body controllers.SmsForm true "Details of the sms request"
// @Success 200 {object} Response object
// @router /api/send-sms [post]
// @Success 200 {object} controllers.Response The Response object
// @router /send-sms [post]
func (c *ApiController) SendSms() {
provider, _, ok := c.GetProviderFromContext("SMS")
if !ok {
return
}
var smsForm SmsForm
err := json.Unmarshal(c.Ctx.Input.RequestBody, &smsForm)
provider, err := c.GetProviderFromContext("SMS")
if err != nil {
c.ResponseError(err.Error())
return
}
org := object.GetOrganization(smsForm.OrgId)
var invalidReceivers []string
for idx, receiver := range smsForm.Receivers {
if !util.IsPhoneCnValid(receiver) {
invalidReceivers = append(invalidReceivers, receiver)
} else {
smsForm.Receivers[idx] = fmt.Sprintf("+%s%s", org.PhonePrefix, receiver)
}
var smsForm SmsForm
err = json.Unmarshal(c.Ctx.Input.RequestBody, &smsForm)
if err != nil {
c.ResponseError(err.Error())
return
}
if len(invalidReceivers) != 0 {
c.ResponseError(fmt.Sprintf("Invalid phone receivers: %s", invalidReceivers))
return
if provider.Type != "Custom HTTP SMS" {
invalidReceivers := getInvalidSmsReceivers(smsForm)
if len(invalidReceivers) != 0 {
c.ResponseError(fmt.Sprintf(c.T("service:Invalid phone receivers: %s"), strings.Join(invalidReceivers, ", ")))
return
}
}
err = object.SendSms(provider, smsForm.Content, smsForm.Receivers...)
@@ -153,3 +193,33 @@ func (c *ApiController) SendSms() {
c.ResponseOk()
}
// SendNotification
// @Title SendNotification
// @Tag Service API
// @Description This API is not for Casdoor frontend to call, it is for Casdoor SDKs.
// @Param from body controllers.NotificationForm true "Details of the notification request"
// @Success 200 {object} controllers.Response The Response object
// @router /send-notification [post]
func (c *ApiController) SendNotification() {
provider, err := c.GetProviderFromContext("Notification")
if err != nil {
c.ResponseError(err.Error())
return
}
var notificationForm NotificationForm
err = json.Unmarshal(c.Ctx.Input.RequestBody, &notificationForm)
if err != nil {
c.ResponseError(err.Error())
return
}
err = object.SendNotification(provider, notificationForm.Content)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk()
}

178
controllers/session.go Normal file
View File

@@ -0,0 +1,178 @@
// Copyright 2022 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetSessions
// @Title GetSessions
// @Tag Session API
// @Description Get organization user sessions.
// @Param owner query string true "The organization name"
// @Success 200 {array} string The Response object
// @router /get-sessions [get]
func (c *ApiController) GetSessions() {
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
owner := c.Ctx.Input.Query("owner")
if limit == "" || page == "" {
sessions, err := object.GetSessions(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(sessions)
} else {
limit := util.ParseInt(limit)
count, err := object.GetSessionCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
sessions, err := object.GetPaginationSessions(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(sessions, paginator.Nums())
}
}
// GetSingleSession
// @Title GetSingleSession
// @Tag Session API
// @Description Get session for one user in one application.
// @Param sessionPkId query string true "The session ID in format: organization/user/application (e.g., built-in/admin/app-built-in)"
// @Success 200 {array} string The Response object
// @router /get-session [get]
func (c *ApiController) GetSingleSession() {
id := c.Ctx.Input.Query("sessionPkId")
session, err := object.GetSingleSession(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(session)
}
// UpdateSession
// @Title UpdateSession
// @Tag Session API
// @Description Update session for one user in one application.
// @Param body body object.Session true "The session object to update"
// @Success 200 {object} controllers.Response The Response object
// @router /update-session [post]
func (c *ApiController) UpdateSession() {
var session object.Session
err := json.Unmarshal(c.Ctx.Input.RequestBody, &session)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateSession(util.GetSessionId(session.Owner, session.Name, session.Application), &session))
c.ServeJSON()
}
// AddSession
// @Title AddSession
// @Tag Session API
// @Description Add session for one user in one application. If there are other existing sessions, join the session into the list.
// @Param body body object.Session true "The session object to add"
// @Success 200 {object} controllers.Response The Response object
// @router /add-session [post]
func (c *ApiController) AddSession() {
var session object.Session
err := json.Unmarshal(c.Ctx.Input.RequestBody, &session)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddSession(&session))
c.ServeJSON()
}
// DeleteSession
// @Title DeleteSession
// @Tag Session API
// @Description Delete session for one user in one application.
// @Param body body object.Session true "The session object to delete"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-session [post]
func (c *ApiController) DeleteSession() {
var session object.Session
err := json.Unmarshal(c.Ctx.Input.RequestBody, &session)
if err != nil {
c.ResponseError(err.Error())
return
}
curSessionId := c.Ctx.Input.CruSession.SessionID(context.Background())
sessionId := c.Ctx.Input.Query("sessionId")
if curSessionId == sessionId && sessionId != "" {
c.ResponseError(fmt.Sprintf(c.T("session:session id %s is the current session and cannot be deleted"), curSessionId))
return
}
if sessionId != "" {
c.Data["json"] = wrapActionResponse(object.DeleteSessionId(util.GetSessionId(session.Owner, session.Name, session.Application), sessionId))
c.ServeJSON()
return
}
c.Data["json"] = wrapActionResponse(object.DeleteSession(util.GetSessionId(session.Owner, session.Name, session.Application), curSessionId))
c.ServeJSON()
}
// IsSessionDuplicated
// @Title IsSessionDuplicated
// @Tag Session API
// @Description Check if there are other different sessions for one user in one application.
// @Param sessionPkId query string true "The session ID in format: organization/user/application (e.g., built-in/admin/app-built-in)"
// @Param sessionId query string true "The specific session ID to check"
// @Success 200 {array} string The Response object
// @router /is-session-duplicated [get]
func (c *ApiController) IsSessionDuplicated() {
id := c.Ctx.Input.Query("sessionPkId")
sessionId := c.Ctx.Input.Query("sessionId")
isUserSessionDuplicated, err := object.IsSessionDuplicated(id, sessionId)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(isUserSessionDuplicated)
}

165
controllers/site.go Normal file
View File

@@ -0,0 +1,165 @@
// Copyright 2023 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/server/web/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetGlobalSites
// @Title GetGlobalSites
// @Tag Site API
// @Description get global sites
// @Success 200 {array} object.Site The Response object
// @router /get-global-sites [get]
func (c *ApiController) GetGlobalSites() {
sites, err := object.GetGlobalSites()
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedSites(sites, util.GetHostname()))
}
// GetSites
// @Title GetSites
// @Tag Site API
// @Description get sites
// @Param owner query string true "The owner of sites"
// @Success 200 {array} object.Site The Response object
// @router /get-sites [get]
func (c *ApiController) GetSites() {
owner := c.Ctx.Input.Query("owner")
if owner == "admin" {
owner = ""
}
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
sites, err := object.GetSites(owner)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedSites(sites, util.GetHostname()))
return
}
limitInt := util.ParseInt(limit)
count, err := object.GetSiteCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limitInt, count)
sites, err := object.GetPaginationSites(owner, paginator.Offset(), limitInt, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedSites(sites, util.GetHostname()), paginator.Nums())
}
// GetSite
// @Title GetSite
// @Tag Site API
// @Description get site
// @Param id query string true "The id ( owner/name ) of the site"
// @Success 200 {object} object.Site The Response object
// @router /get-site [get]
func (c *ApiController) GetSite() {
id := c.Ctx.Input.Query("id")
site, err := object.GetSite(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(object.GetMaskedSite(site, util.GetHostname()))
}
// UpdateSite
// @Title UpdateSite
// @Tag Site API
// @Description update site
// @Param id query string true "The id ( owner/name ) of the site"
// @Param body body object.Site true "The details of the site"
// @Success 200 {object} controllers.Response The Response object
// @router /update-site [post]
func (c *ApiController) UpdateSite() {
id := c.Ctx.Input.Query("id")
var site object.Site
err := json.Unmarshal(c.Ctx.Input.RequestBody, &site)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateSite(id, &site))
c.ServeJSON()
}
// AddSite
// @Title AddSite
// @Tag Site API
// @Description add site
// @Param body body object.Site true "The details of the site"
// @Success 200 {object} controllers.Response The Response object
// @router /add-site [post]
func (c *ApiController) AddSite() {
var site object.Site
err := json.Unmarshal(c.Ctx.Input.RequestBody, &site)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.AddSite(&site))
c.ServeJSON()
}
// DeleteSite
// @Title DeleteSite
// @Tag Site API
// @Description delete site
// @Param body body object.Site true "The details of the site"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-site [post]
func (c *ApiController) DeleteSite() {
var site object.Site
err := json.Unmarshal(c.Ctx.Input.RequestBody, &site)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteSite(&site))
c.ServeJSON()
}

195
controllers/subscription.go Normal file
View File

@@ -0,0 +1,195 @@
// Copyright 2023 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"fmt"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetSubscriptions
// @Title GetSubscriptions
// @Tag Subscription API
// @Description get subscriptions
// @Param owner query string true "The owner of subscriptions"
// @Success 200 {array} object.Subscription The Response object
// @router /get-subscriptions [get]
func (c *ApiController) GetSubscriptions() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
var subscriptions []*object.Subscription
var err error
if c.IsAdmin() {
// If field is "user", filter by that user even for admins
if field == "user" && value != "" {
subscriptions, err = object.GetSubscriptionsByUser(owner, value)
} else {
subscriptions, err = object.GetSubscriptions(owner)
}
} else {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
subscriptions, err = object.GetSubscriptionsByUser(owner, userName)
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(subscriptions)
} else {
limit := util.ParseInt(limit)
if !c.IsAdmin() {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
field = "user"
value = userName
}
count, err := object.GetSubscriptionCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
subscription, err := object.GetPaginationSubscriptions(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(subscription, paginator.Nums())
}
}
// GetSubscription
// @Title GetSubscription
// @Tag Subscription API
// @Description get subscription
// @Param id query string true "The id ( owner/name ) of the subscription"
// @Success 200 {object} object.Subscription The Response object
// @router /get-subscription [get]
func (c *ApiController) GetSubscription() {
id := c.Ctx.Input.Query("id")
subscription, err := object.GetSubscription(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(subscription)
}
// UpdateSubscription
// @Title UpdateSubscription
// @Tag Subscription API
// @Description update subscription
// @Param id query string true "The id ( owner/name ) of the subscription"
// @Param body body object.Subscription true "The details of the subscription"
// @Success 200 {object} controllers.Response The Response object
// @router /update-subscription [post]
func (c *ApiController) UpdateSubscription() {
id := c.Ctx.Input.Query("id")
var subscription object.Subscription
err := json.Unmarshal(c.Ctx.Input.RequestBody, &subscription)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateSubscription(id, &subscription))
c.ServeJSON()
}
// AddSubscription
// @Title AddSubscription
// @Tag Subscription API
// @Description add subscription
// @Param body body object.Subscription true "The details of the subscription"
// @Success 200 {object} controllers.Response The Response object
// @router /add-subscription [post]
func (c *ApiController) AddSubscription() {
var subscription object.Subscription
err := json.Unmarshal(c.Ctx.Input.RequestBody, &subscription)
if err != nil {
c.ResponseError(err.Error())
return
}
// Check if plan restricts user to one subscription
if subscription.Plan != "" {
plan, err := object.GetPlan(util.GetId(subscription.Owner, subscription.Plan))
if err != nil {
c.ResponseError(err.Error())
return
}
if plan != nil && plan.IsExclusive {
hasSubscription, err := object.HasActiveSubscriptionForPlan(subscription.Owner, subscription.User, subscription.Plan)
if err != nil {
c.ResponseError(err.Error())
return
}
if hasSubscription {
c.ResponseError(fmt.Sprintf("User already has an active subscription for plan: %s", subscription.Plan))
return
}
}
}
c.Data["json"] = wrapActionResponse(object.AddSubscription(&subscription))
c.ServeJSON()
}
// DeleteSubscription
// @Title DeleteSubscription
// @Tag Subscription API
// @Description delete subscription
// @Param body body object.Subscription true "The details of the subscription"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-subscription [post]
func (c *ApiController) DeleteSubscription() {
var subscription object.Subscription
err := json.Unmarshal(c.Ctx.Input.RequestBody, &subscription)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteSubscription(&subscription))
c.ServeJSON()
}

View File

@@ -16,8 +16,9 @@ package controllers
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -30,20 +31,38 @@ import (
// @Success 200 {array} object.Syncer The Response object
// @router /get-syncers [get]
func (c *ApiController) GetSyncers() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
organization := c.Ctx.Input.Query("organization")
if limit == "" || page == "" {
c.Data["json"] = object.GetSyncers(owner)
c.ServeJSON()
syncers, err := object.GetMaskedSyncers(object.GetOrganizationSyncers(owner, organization))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(syncers)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetSyncerCount(owner, field, value)))
syncers := object.GetPaginationSyncers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetSyncerCount(owner, organization, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
syncers, err := object.GetMaskedSyncers(object.GetPaginationSyncers(owner, organization, paginator.Offset(), limit, field, value, sortField, sortOrder))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(syncers, paginator.Nums())
}
}
@@ -52,26 +71,31 @@ func (c *ApiController) GetSyncers() {
// @Title GetSyncer
// @Tag Syncer API
// @Description get syncer
// @Param id query string true "The id of the syncer"
// @Param id query string true "The id ( owner/name ) of the syncer"
// @Success 200 {object} object.Syncer The Response object
// @router /get-syncer [get]
func (c *ApiController) GetSyncer() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
c.Data["json"] = object.GetSyncer(id)
c.ServeJSON()
syncer, err := object.GetMaskedSyncer(object.GetSyncer(id))
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(syncer)
}
// UpdateSyncer
// @Title UpdateSyncer
// @Tag Syncer API
// @Description update syncer
// @Param id query string true "The id of the syncer"
// @Param id query string true "The id ( owner/name ) of the syncer"
// @Param body body object.Syncer true "The details of the syncer"
// @Success 200 {object} controllers.Response The Response object
// @router /update-syncer [post]
func (c *ApiController) UpdateSyncer() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var syncer object.Syncer
err := json.Unmarshal(c.Ctx.Input.RequestBody, &syncer)
@@ -80,7 +104,7 @@ func (c *ApiController) UpdateSyncer() {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateSyncer(id, &syncer))
c.Data["json"] = wrapActionResponse(object.UpdateSyncer(id, &syncer, c.IsGlobalAdmin(), c.GetAcceptLanguage()))
c.ServeJSON()
}
@@ -130,10 +154,39 @@ func (c *ApiController) DeleteSyncer() {
// @Success 200 {object} controllers.Response The Response object
// @router /run-syncer [get]
func (c *ApiController) RunSyncer() {
id := c.Input().Get("id")
syncer := object.GetSyncer(id)
id := c.Ctx.Input.Query("id")
syncer, err := object.GetSyncer(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if syncer == nil {
c.ResponseError(fmt.Sprintf(c.T("general:The syncer: %s does not exist"), id))
return
}
object.RunSyncer(syncer)
err = object.RunSyncer(syncer)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk()
}
func (c *ApiController) TestSyncerDb() {
var syncer object.Syncer
err := json.Unmarshal(c.Ctx.Input.RequestBody, &syncer)
if err != nil {
c.ResponseError(err.Error())
return
}
err = object.TestSyncer(syncer)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk()
}

View File

@@ -15,68 +15,60 @@
package controllers
import (
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
"errors"
type SystemInfo struct {
MemoryUsed uint64 `json:"memory_used"`
MemoryTotal uint64 `json:"memory_total"`
CpuUsage []float64 `json:"cpu_usage"`
}
"github.com/casdoor/casdoor/util"
"github.com/go-git/go-git/v5"
)
// GetSystemInfo
// @Title GetSystemInfo
// @Tag System API
// @Description get user's system info
// @Param id query string true "The id of the user"
// @Success 200 {object} object.SystemInfo The Response object
// @Description get system info like CPU and memory usage
// @Success 200 {object} util.SystemInfo The Response object
// @router /get-system-info [get]
func (c *ApiController) GetSystemInfo() {
id := c.GetString("id")
if id == "" {
id = c.GetSessionUsername()
}
user := object.GetUser(id)
if user == nil || !user.IsGlobalAdmin {
c.ResponseError("You are not authorized to access this resource")
_, ok := c.RequireAdmin()
if !ok {
return
}
cpuUsage, err := util.GetCpuUsage()
systemInfo, err := util.GetSystemInfo()
if err != nil {
c.ResponseError(err.Error())
return
}
memoryUsed, memoryTotal, err := util.GetMemoryUsage()
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = SystemInfo{
CpuUsage: cpuUsage,
MemoryUsed: memoryUsed,
MemoryTotal: memoryTotal,
}
c.ServeJSON()
c.ResponseOk(systemInfo)
}
// GitRepoVersion
// @Title GitRepoVersion
// GetVersionInfo
// @Title GetVersionInfo
// @Tag System API
// @Description get local github repo's latest release version info
// @Success 200 {string} local latest version hash of casdoor
// @router /get-release [get]
func (c *ApiController) GitRepoVersion() {
version, err := util.GetGitRepoVersion()
if err != nil {
// @Description get version info like Casdoor release version and commit ID
// @Success 200 {object} util.VersionInfo The Response object
// @router /get-version-info [get]
func (c *ApiController) GetVersionInfo() {
versionInfo, err := util.GetVersionInfo()
if err != nil && !errors.Is(err, git.ErrRepositoryNotExists) {
c.ResponseError(err.Error())
return
}
c.Data["json"] = version
c.ServeJSON()
if versionInfo.Version != "" {
c.ResponseOk(versionInfo)
return
}
c.ResponseOk(util.GetBuiltInVersionInfo())
}
// Health
// @Title Health
// @Tag System API
// @Description check if the system is live
// @Success 200 {object} controllers.Response The Response object
// @router /health [get]
func (c *ApiController) Health() {
c.ResponseOk()
}

271
controllers/ticket.go Normal file
View File

@@ -0,0 +1,271 @@
// Copyright 2024 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetTickets
// @Title GetTickets
// @Tag Ticket API
// @Description get tickets
// @Param owner query string true "The owner of tickets"
// @Success 200 {array} object.Ticket The Response object
// @router /get-tickets [get]
func (c *ApiController) GetTickets() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
user := c.getCurrentUser()
isAdmin := c.IsAdmin()
var tickets []*object.Ticket
var err error
if limit == "" || page == "" {
if isAdmin {
tickets, err = object.GetTickets(owner)
} else {
tickets, err = object.GetUserTickets(owner, user.GetId())
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(tickets)
} else {
limit := util.ParseInt(limit)
var count int64
if isAdmin {
count, err = object.GetTicketCount(owner, field, value)
} else {
// For non-admin users, only show their own tickets
tickets, err = object.GetUserTickets(owner, user.GetId())
if err != nil {
c.ResponseError(err.Error())
return
}
count = int64(len(tickets))
}
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
if isAdmin {
tickets, err = object.GetPaginationTickets(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(tickets, paginator.Nums())
}
}
// GetTicket
// @Title GetTicket
// @Tag Ticket API
// @Description get ticket
// @Param id query string true "The id ( owner/name ) of the ticket"
// @Success 200 {object} object.Ticket The Response object
// @router /get-ticket [get]
func (c *ApiController) GetTicket() {
id := c.Ctx.Input.Query("id")
ticket, err := object.GetTicket(id)
if err != nil {
c.ResponseError(err.Error())
return
}
// Check permission: user can only view their own tickets unless they are admin
user := c.getCurrentUser()
isAdmin := c.IsAdmin()
if ticket != nil && !isAdmin && ticket.User != user.GetId() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
c.ResponseOk(ticket)
}
// UpdateTicket
// @Title UpdateTicket
// @Tag Ticket API
// @Description update ticket
// @Param id query string true "The id ( owner/name ) of the ticket"
// @Param body body object.Ticket true "The details of the ticket"
// @Success 200 {object} controllers.Response The Response object
// @router /update-ticket [post]
func (c *ApiController) UpdateTicket() {
id := c.Ctx.Input.Query("id")
var ticket object.Ticket
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ticket)
if err != nil {
c.ResponseError(err.Error())
return
}
// Check permission
user := c.getCurrentUser()
isAdmin := c.IsAdmin()
existingTicket, err := object.GetTicket(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if existingTicket == nil {
c.ResponseError(c.T("ticket:Ticket not found"))
return
}
// Normal users can only close their own tickets
if !isAdmin {
if existingTicket.User != user.GetId() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
// Normal users can only change state to "Closed"
if ticket.State != "Closed" && ticket.State != existingTicket.State {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
// Preserve original fields that users shouldn't modify
ticket.Owner = existingTicket.Owner
ticket.Name = existingTicket.Name
ticket.User = existingTicket.User
ticket.CreatedTime = existingTicket.CreatedTime
}
c.Data["json"] = wrapActionResponse(object.UpdateTicket(id, &ticket))
c.ServeJSON()
}
// AddTicket
// @Title AddTicket
// @Tag Ticket API
// @Description add ticket
// @Param body body object.Ticket true "The details of the ticket"
// @Success 200 {object} controllers.Response The Response object
// @router /add-ticket [post]
func (c *ApiController) AddTicket() {
var ticket object.Ticket
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ticket)
if err != nil {
c.ResponseError(err.Error())
return
}
// Set the user field to the current user
user := c.getCurrentUser()
ticket.User = user.GetId()
c.Data["json"] = wrapActionResponse(object.AddTicket(&ticket))
c.ServeJSON()
}
// DeleteTicket
// @Title DeleteTicket
// @Tag Ticket API
// @Description delete ticket
// @Param body body object.Ticket true "The details of the ticket"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-ticket [post]
func (c *ApiController) DeleteTicket() {
var ticket object.Ticket
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ticket)
if err != nil {
c.ResponseError(err.Error())
return
}
// Only admins can delete tickets
if !c.IsAdmin() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
c.Data["json"] = wrapActionResponse(object.DeleteTicket(&ticket))
c.ServeJSON()
}
// AddTicketMessage
// @Title AddTicketMessage
// @Tag Ticket API
// @Description add a message to a ticket
// @Param id query string true "The id ( owner/name ) of the ticket"
// @Param body body object.TicketMessage true "The message to add"
// @Success 200 {object} controllers.Response The Response object
// @router /add-ticket-message [post]
func (c *ApiController) AddTicketMessage() {
id := c.Ctx.Input.Query("id")
var message object.TicketMessage
err := json.Unmarshal(c.Ctx.Input.RequestBody, &message)
if err != nil {
c.ResponseError(err.Error())
return
}
// Check permission
user := c.getCurrentUser()
isAdmin := c.IsAdmin()
ticket, err := object.GetTicket(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if ticket == nil {
c.ResponseError(c.T("ticket:Ticket not found"))
return
}
// Users can only add messages to their own tickets, admins can add to any ticket
if !isAdmin && ticket.User != user.GetId() {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
// Set the author and admin flag
message.Author = user.GetId()
message.IsAdmin = isAdmin
c.Data["json"] = wrapActionResponse(object.AddTicketMessage(id, &message))
c.ServeJSON()
}

View File

@@ -16,9 +16,10 @@ package controllers
import (
"encoding/json"
"net/http"
"fmt"
"time"
"github.com/astaxie/beego/utils/pagination"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@@ -27,26 +28,43 @@ import (
// @Title GetTokens
// @Tag Token API
// @Description get tokens
// @Param owner query string true "The owner of tokens"
// @Param owner query string true "The organization name (e.g., built-in)"
// @Param pageSize query string true "The size of each page"
// @Param p query string true "The number of the page"
// @Success 200 {array} object.Token The Response object
// @router /get-tokens [get]
func (c *ApiController) GetTokens() {
owner := c.Input().Get("owner")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
value := c.Input().Get("value")
sortField := c.Input().Get("sortField")
sortOrder := c.Input().Get("sortOrder")
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
organization := c.Ctx.Input.Query("organization")
if limit == "" || page == "" {
c.Data["json"] = object.GetTokens(owner)
c.ServeJSON()
token, err := object.GetTokens(owner, organization)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(token)
} else {
limit := util.ParseInt(limit)
paginator := pagination.SetPaginator(c.Ctx, limit, int64(object.GetTokenCount(owner, field, value)))
tokens := object.GetPaginationTokens(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
count, err := object.GetTokenCount(owner, organization, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
tokens, err := object.GetPaginationTokens(owner, organization, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(tokens, paginator.Nums())
}
}
@@ -55,26 +73,30 @@ func (c *ApiController) GetTokens() {
// @Title GetToken
// @Tag Token API
// @Description get token
// @Param id query string true "The id of token"
// @Param id query string true "The token ID in format: organization/token-name (e.g., built-in/token-123456)"
// @Success 200 {object} object.Token The Response object
// @router /get-token [get]
func (c *ApiController) GetToken() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
token, err := object.GetToken(id)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = object.GetToken(id)
c.ServeJSON()
c.ResponseOk(token)
}
// UpdateToken
// @Title UpdateToken
// @Tag Token API
// @Description update token
// @Param id query string true "The id of token"
// @Param id query string true "The token ID in format: organization/token-name (e.g., built-in/token-123456)"
// @Param body body object.Token true "Details of the token"
// @Success 200 {object} controllers.Response The Response object
// @router /update-token [post]
func (c *ApiController) UpdateToken() {
id := c.Input().Get("id")
id := c.Ctx.Input.Query("id")
var token object.Token
err := json.Unmarshal(c.Ctx.Input.RequestBody, &token)
@@ -83,7 +105,7 @@ func (c *ApiController) UpdateToken() {
return
}
c.Data["json"] = wrapActionResponse(object.UpdateToken(id, &token))
c.Data["json"] = wrapActionResponse(object.UpdateToken(id, &token, c.IsGlobalAdmin()))
c.ServeJSON()
}
@@ -125,40 +147,6 @@ func (c *ApiController) DeleteToken() {
c.ServeJSON()
}
// GetOAuthCode
// @Title GetOAuthCode
// @Tag Token API
// @Description get OAuth code
// @Param user_id query string true "The id of user"
// @Param client_id query string true "OAuth client id"
// @Param response_type query string true "OAuth response type"
// @Param redirect_uri query string true "OAuth redirect URI"
// @Param scope query string true "OAuth scope"
// @Param state query string true "OAuth state"
// @Success 200 {object} object.TokenWrapper The Response object
// @router /login/oauth/code [post]
func (c *ApiController) GetOAuthCode() {
userId := c.Input().Get("user_id")
clientId := c.Input().Get("client_id")
responseType := c.Input().Get("response_type")
redirectUri := c.Input().Get("redirect_uri")
scope := c.Input().Get("scope")
state := c.Input().Get("state")
nonce := c.Input().Get("nonce")
challengeMethod := c.Input().Get("code_challenge_method")
codeChallenge := c.Input().Get("code_challenge")
if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
c.ResponseError("Challenge method should be S256")
return
}
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, host)
c.ServeJSON()
}
// GetOAuthToken
// @Title GetOAuthToken
// @Tag Token API
@@ -172,39 +160,147 @@ func (c *ApiController) GetOAuthCode() {
// @Success 401 {object} object.TokenError The Response object
// @router /login/oauth/access_token [post]
func (c *ApiController) GetOAuthToken() {
grantType := c.Input().Get("grant_type")
clientId := c.Input().Get("client_id")
clientSecret := c.Input().Get("client_secret")
code := c.Input().Get("code")
verifier := c.Input().Get("code_verifier")
scope := c.Input().Get("scope")
username := c.Input().Get("username")
password := c.Input().Get("password")
tag := c.Input().Get("tag")
avatar := c.Input().Get("avatar")
clientId := c.Ctx.Input.Query("client_id")
clientSecret := c.Ctx.Input.Query("client_secret")
assertion := c.Ctx.Input.Query("assertion")
clientAssertion := c.Ctx.Input.Query("client_assertion")
clientAssertionType := c.Ctx.Input.Query("client_assertion_type")
grantType := c.Ctx.Input.Query("grant_type")
code := c.Ctx.Input.Query("code")
verifier := c.Ctx.Input.Query("code_verifier")
scope := c.Ctx.Input.Query("scope")
nonce := c.Ctx.Input.Query("nonce")
username := c.Ctx.Input.Query("username")
password := c.Ctx.Input.Query("password")
tag := c.Ctx.Input.Query("tag")
avatar := c.Ctx.Input.Query("avatar")
refreshToken := c.Ctx.Input.Query("refresh_token")
deviceCode := c.Ctx.Input.Query("device_code")
subjectToken := c.Ctx.Input.Query("subject_token")
subjectTokenType := c.Ctx.Input.Query("subject_token_type")
audience := c.Ctx.Input.Query("audience")
resource := c.Ctx.Input.Query("resource")
if clientId == "" && clientSecret == "" {
clientId, clientSecret, _ = c.Ctx.Request.BasicAuth()
}
if clientId == "" {
// If clientID is empty, try to read data from RequestBody
if len(c.Ctx.Input.RequestBody) != 0 && grantType != "urn:ietf:params:oauth:grant-type:device_code" {
// If clientId is empty, try to read data from RequestBody
var tokenRequest TokenRequest
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &tokenRequest); err == nil {
clientId = tokenRequest.ClientId
clientSecret = tokenRequest.ClientSecret
grantType = tokenRequest.GrantType
code = tokenRequest.Code
verifier = tokenRequest.Verifier
scope = tokenRequest.Scope
username = tokenRequest.Username
password = tokenRequest.Password
tag = tokenRequest.Tag
avatar = tokenRequest.Avatar
err := json.Unmarshal(c.Ctx.Input.RequestBody, &tokenRequest)
if err == nil {
if clientId == "" {
clientId = tokenRequest.ClientId
}
if clientSecret == "" {
clientSecret = tokenRequest.ClientSecret
}
if clientAssertion == "" {
clientAssertion = tokenRequest.ClientAssertion
}
if clientAssertionType == "" {
clientAssertionType = tokenRequest.ClientAssertionType
}
if grantType == "" {
grantType = tokenRequest.GrantType
}
if code == "" {
code = tokenRequest.Code
}
if verifier == "" {
verifier = tokenRequest.Verifier
}
if scope == "" {
scope = tokenRequest.Scope
}
if nonce == "" {
nonce = tokenRequest.Nonce
}
if username == "" {
username = tokenRequest.Username
}
if password == "" {
password = tokenRequest.Password
}
if tag == "" {
tag = tokenRequest.Tag
}
if avatar == "" {
avatar = tokenRequest.Avatar
}
if refreshToken == "" {
refreshToken = tokenRequest.RefreshToken
}
if subjectToken == "" {
subjectToken = tokenRequest.SubjectToken
}
if subjectTokenType == "" {
subjectTokenType = tokenRequest.SubjectTokenType
}
if audience == "" {
audience = tokenRequest.Audience
}
if resource == "" {
resource = tokenRequest.Resource
}
if assertion == "" {
assertion = tokenRequest.Assertion
}
}
}
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, username, password, host, tag, avatar)
// Extract DPoP proof header (RFC 9449). Empty string when DPoP is not used.
dpopProof := c.Ctx.Request.Header.Get("DPoP")
host := c.Ctx.Request.Host
if deviceCode != "" {
deviceAuthCache, ok := object.DeviceAuthMap.Load(deviceCode)
if !ok {
c.Data["json"] = &object.TokenError{
Error: "expired_token",
ErrorDescription: "token is expired",
}
c.SetTokenErrorHttpStatus()
c.ServeJSON()
c.SetTokenErrorHttpStatus()
return
}
deviceAuthCacheCast := deviceAuthCache.(object.DeviceAuthCache)
if !deviceAuthCacheCast.UserSignIn {
c.Data["json"] = &object.TokenError{
Error: "authorization_pending",
ErrorDescription: "authorization pending",
}
c.SetTokenErrorHttpStatus()
c.ServeJSON()
c.SetTokenErrorHttpStatus()
return
}
if deviceAuthCacheCast.RequestAt.Add(time.Second * 120).Before(time.Now()) {
c.Data["json"] = &object.TokenError{
Error: "expired_token",
ErrorDescription: "token is expired",
}
c.SetTokenErrorHttpStatus()
c.ServeJSON()
c.SetTokenErrorHttpStatus()
return
}
object.DeviceAuthMap.Delete(deviceCode)
username = deviceAuthCacheCast.UserName
}
token, err := object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, nonce, username, password, host, refreshToken, tag, avatar, c.GetAcceptLanguage(), subjectToken, subjectTokenType, assertion, clientAssertion, clientAssertionType, audience, resource, dpopProof)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = token
c.SetTokenErrorHttpStatus()
c.ServeJSON()
}
@@ -223,11 +319,11 @@ func (c *ApiController) GetOAuthToken() {
// @Success 401 {object} object.TokenError The Response object
// @router /login/oauth/refresh_token [post]
func (c *ApiController) RefreshToken() {
grantType := c.Input().Get("grant_type")
refreshToken := c.Input().Get("refresh_token")
scope := c.Input().Get("scope")
clientId := c.Input().Get("client_id")
clientSecret := c.Input().Get("client_secret")
grantType := c.Ctx.Input.Query("grant_type")
refreshToken := c.Ctx.Input.Query("refresh_token")
scope := c.Ctx.Input.Query("scope")
clientId := c.Ctx.Input.Query("client_id")
clientSecret := c.Ctx.Input.Query("client_secret")
host := c.Ctx.Request.Host
if clientId == "" {
@@ -242,40 +338,104 @@ func (c *ApiController) RefreshToken() {
}
}
c.Data["json"] = object.RefreshToken(grantType, refreshToken, scope, clientId, clientSecret, host)
ok, application, clientId, _, err := c.ValidateOAuth(true)
if err != nil || !ok {
return
}
dpopProof := c.Ctx.Request.Header.Get("DPoP")
refreshToken2, err := object.RefreshToken(application, grantType, refreshToken, scope, clientId, clientSecret, host, dpopProof)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = refreshToken2
c.SetTokenErrorHttpStatus()
c.ServeJSON()
}
// TokenLogout
// @Title TokenLogout
// @Tag Token API
// @Description delete token by AccessToken
// @Param id_token_hint query string true "id_token_hint"
// @Param post_logout_redirect_uri query string false "post_logout_redirect_uri"
// @Param state query string true "state"
// @Success 200 {object} controllers.Response The Response object
// @router /login/oauth/logout [get]
func (c *ApiController) TokenLogout() {
token := c.Input().Get("id_token_hint")
flag, application := object.DeleteTokenByAccessToken(token)
redirectUri := c.Input().Get("post_logout_redirect_uri")
state := c.Input().Get("state")
if application != nil && object.CheckRedirectUriValid(application, redirectUri) {
c.Ctx.Redirect(http.StatusFound, redirectUri+"?state="+state)
func (c *ApiController) ResponseTokenError(errorMsg string, errorDescription string) {
c.Data["json"] = &object.TokenError{
Error: errorMsg,
ErrorDescription: errorDescription,
}
c.SetTokenErrorHttpStatus()
c.ServeJSON()
}
func (c *ApiController) ValidateOAuth(ignoreValidSecret bool) (ok bool, application *object.Application, clientId, clientSecret string, err error) {
reqClientId := c.Ctx.Input.Query("client_id")
reqClientSecret := c.Ctx.Input.Query("client_secret")
clientAssertion := c.Ctx.Input.Query("client_assertion")
clientAssertionType := c.Ctx.Input.Query("client_assertion_type")
if reqClientId == "" && clientAssertionType == "" {
var tokenRequest TokenRequest
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &tokenRequest); err == nil {
reqClientId = tokenRequest.ClientId
reqClientSecret = tokenRequest.ClientSecret
clientAssertion = tokenRequest.ClientAssertion
clientAssertionType = tokenRequest.ClientAssertionType
}
}
if clientAssertionType == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" {
ok, application, err = object.ValidateClientAssertion(clientAssertion, c.Ctx.Request.Host)
if err != nil {
c.ResponseTokenError(object.InvalidClient, err.Error())
return
}
if !ok || application == nil {
c.ResponseTokenError(object.InvalidClient, "client_assertion is invalid")
return
}
clientSecret = application.ClientSecret
clientId = application.ClientId
ok = true
return
}
c.Data["json"] = wrapActionResponse(flag)
c.ServeJSON()
if reqClientId == "" && reqClientSecret == "" {
clientId, clientSecret, ok = c.Ctx.Request.BasicAuth()
if !ok {
clientId = c.Ctx.Input.Query("client_id")
clientSecret = c.Ctx.Input.Query("client_secret")
if clientId == "" || clientSecret == "" {
c.ResponseTokenError(object.InvalidRequest, "")
return
}
}
} else {
clientId = reqClientId
clientSecret = reqClientSecret
}
application, err = object.GetApplicationByClientId(clientId)
if err != nil {
c.ResponseTokenError(object.InvalidClient, err.Error())
return
}
if application == nil || (application.ClientSecret != clientSecret && !ignoreValidSecret) {
c.ResponseTokenError(object.InvalidClient, c.T("token:Invalid application or wrong clientSecret"))
return
}
ok = true
return
}
// IntrospectToken
// @Title IntrospectToken
// @Tag Login API
// @Description The introspection endpoint is an OAuth 2.0 endpoint that takes a
// parameter representing an OAuth 2.0 token and returns a JSON document
// representing the meta information surrounding the
// token, including whether this token is currently active.
// This endpoint only support Basic Authorization.
// This endpoint support Basic Authorization and authorization defined in RFC 7523.
//
// @Param token formData string true "access_token's value or refresh_token's value"
// @Param token_type_hint formData string true "the token type access_token or refresh_token"
@@ -284,59 +444,129 @@ func (c *ApiController) TokenLogout() {
// @Success 401 {object} object.TokenError The Response object
// @router /login/oauth/introspect [post]
func (c *ApiController) IntrospectToken() {
tokenValue := c.Input().Get("token")
clientId, clientSecret, ok := c.Ctx.Request.BasicAuth()
if !ok {
clientId = c.Input().Get("client_id")
clientSecret = c.Input().Get("client_secret")
if clientId == "" || clientSecret == "" {
c.ResponseError("empty clientId or clientSecret")
c.Data["json"] = &object.TokenError{
Error: object.InvalidRequest,
}
c.SetTokenErrorHttpStatus()
tokenValue := c.Ctx.Input.Query("token")
ok, application, clientId, _, err := c.ValidateOAuth(false)
if err != nil || !ok {
return
}
respondWithInactiveToken := func() {
c.Data["json"] = &object.IntrospectionResponse{Active: false}
c.ServeJSON()
}
tokenTypeHint := c.Ctx.Input.Query("token_type_hint")
var token *object.Token
if tokenTypeHint != "" {
token, err = object.GetTokenByTokenValue(tokenValue, tokenTypeHint)
if err != nil {
c.ResponseTokenError(object.InvalidRequest, err.Error())
return
}
if token == nil || token.ExpiresIn <= 0 {
respondWithInactiveToken()
return
}
if token.ExpiresIn <= 0 {
c.Data["json"] = &object.IntrospectionResponse{Active: false}
c.ServeJSON()
return
}
}
application := object.GetApplicationByClientId(clientId)
if application == nil || application.ClientSecret != clientSecret {
c.ResponseError("invalid application or wrong clientSecret")
c.Data["json"] = &object.TokenError{
Error: object.InvalidClient,
var introspectionResponse object.IntrospectionResponse
if application.TokenFormat == "JWT-Standard" {
jwtToken, err := object.ParseStandardJwtTokenByApplication(tokenValue, application)
if err != nil {
// and token revoked case. but we not implement
// TODO: 2022-03-03 add token revoked check, when we implemented the Token Revocation(rfc7009) Specs.
// refs: https://tools.ietf.org/html/rfc7009
respondWithInactiveToken()
return
}
introspectionResponse = object.IntrospectionResponse{
Active: true,
Scope: jwtToken.Scope,
ClientId: clientId,
Username: jwtToken.Name,
TokenType: jwtToken.TokenType,
Exp: jwtToken.ExpiresAt.Unix(),
Iat: jwtToken.IssuedAt.Unix(),
Nbf: jwtToken.NotBefore.Unix(),
Sub: jwtToken.Subject,
Aud: jwtToken.Audience,
Iss: jwtToken.Issuer,
Jti: jwtToken.ID,
}
} else {
jwtToken, err := object.ParseJwtTokenByApplication(tokenValue, application)
if err != nil {
// and token revoked case. but we not implement
// TODO: 2022-03-03 add token revoked check, when we implemented the Token Revocation(rfc7009) Specs.
// refs: https://tools.ietf.org/html/rfc7009
respondWithInactiveToken()
return
}
introspectionResponse = object.IntrospectionResponse{
Active: true,
ClientId: clientId,
Exp: jwtToken.ExpiresAt.Unix(),
Iat: jwtToken.IssuedAt.Unix(),
Nbf: jwtToken.NotBefore.Unix(),
Sub: jwtToken.Subject,
Aud: jwtToken.Audience,
Iss: jwtToken.Issuer,
Jti: jwtToken.ID,
}
if jwtToken.Scope != "" {
introspectionResponse.Scope = jwtToken.Scope
}
if jwtToken.Name != "" {
introspectionResponse.Username = jwtToken.Name
}
if jwtToken.TokenType != "" {
introspectionResponse.TokenType = jwtToken.TokenType
}
c.SetTokenErrorHttpStatus()
return
}
token := object.GetTokenByTokenAndApplication(tokenValue, application.Name)
if token == nil {
c.Data["json"] = &object.IntrospectionResponse{Active: false}
c.ServeJSON()
return
}
jwtToken, err := object.ParseJwtTokenByApplication(tokenValue, application)
if err != nil || jwtToken.Valid() != nil {
// and token revoked case. but we not implement
// TODO: 2022-03-03 add token revoked check, when we implemented the Token Revocation(rfc7009) Specs.
// refs: https://tools.ietf.org/html/rfc7009
c.Data["json"] = &object.IntrospectionResponse{Active: false}
c.ServeJSON()
return
}
c.Data["json"] = &object.IntrospectionResponse{
Active: true,
Scope: jwtToken.Scope,
ClientId: clientId,
Username: token.User,
TokenType: token.TokenType,
Exp: jwtToken.ExpiresAt.Unix(),
Iat: jwtToken.IssuedAt.Unix(),
Nbf: jwtToken.NotBefore.Unix(),
Sub: jwtToken.Subject,
Aud: jwtToken.Audience,
Iss: jwtToken.Issuer,
Jti: jwtToken.Id,
if tokenTypeHint == "" {
token, err = object.GetTokenByTokenValue(tokenValue, introspectionResponse.TokenType)
if err != nil {
c.ResponseTokenError(object.InvalidRequest, err.Error())
return
}
if token == nil || token.ExpiresIn <= 0 {
respondWithInactiveToken()
return
}
}
if token != nil {
application, err = object.GetApplication(fmt.Sprintf("%s/%s", token.Owner, token.Application))
if err != nil {
c.ResponseTokenError(object.InvalidClient, err.Error())
return
}
if application == nil {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), token.Application))
return
}
introspectionResponse.TokenType = token.TokenType
introspectionResponse.ClientId = application.ClientId
// Expose DPoP key binding in the introspection response (RFC 9449 §8).
if token.DPoPJkt != "" {
introspectionResponse.Cnf = &object.DPoPConfirmation{JKT: token.DPoPJkt}
}
}
c.Data["json"] = introspectionResponse
c.ServeJSON()
}

213
controllers/transaction.go Normal file
View File

@@ -0,0 +1,213 @@
// Copyright 2024 The Casdoor Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"encoding/json"
"github.com/beego/beego/v2/core/utils/pagination"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
// GetTransactions
// @Title GetTransactions
// @Tag Transaction API
// @Description get transactions
// @Param owner query string true "The owner of transactions"
// @Success 200 {array} object.Transaction The Response object
// @router /get-transactions [get]
func (c *ApiController) GetTransactions() {
owner := c.Ctx.Input.Query("owner")
limit := c.Ctx.Input.Query("pageSize")
page := c.Ctx.Input.Query("p")
field := c.Ctx.Input.Query("field")
value := c.Ctx.Input.Query("value")
sortField := c.Ctx.Input.Query("sortField")
sortOrder := c.Ctx.Input.Query("sortOrder")
if limit == "" || page == "" {
var transactions []*object.Transaction
var err error
if c.IsAdmin() {
// If field is "user", filter by that user even for admins
if field == "user" && value != "" {
transactions, err = object.GetUserTransactions(owner, value)
} else {
transactions, err = object.GetTransactions(owner)
}
} else {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
transactions, err = object.GetUserTransactions(owner, userName)
}
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(transactions)
} else {
limit := util.ParseInt(limit)
// Apply user filter for non-admin users
if !c.IsAdmin() {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
field = "user"
value = userName
}
count, err := object.GetTransactionCount(owner, field, value)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.NewPaginator(c.Ctx.Request, limit, count)
transactions, err := object.GetPaginationTransactions(owner, paginator.Offset(), limit, field, value, sortField, sortOrder)
if err != nil {
c.ResponseError(err.Error())
return
}
c.ResponseOk(transactions, paginator.Nums())
}
}
// GetTransaction
// @Title GetTransaction
// @Tag Transaction API
// @Description get transaction
// @Param id query string true "The id ( owner/name ) of the transaction"
// @Success 200 {object} object.Transaction The Response object
// @router /get-transaction [get]
func (c *ApiController) GetTransaction() {
id := c.Ctx.Input.Query("id")
transaction, err := object.GetTransaction(id)
if err != nil {
c.ResponseError(err.Error())
return
}
if transaction == nil {
c.ResponseOk(nil)
return
}
// Check if non-admin user is trying to access someone else's transaction
if !c.IsAdmin() {
user := c.GetSessionUsername()
_, userName, userErr := util.GetOwnerAndNameFromIdWithError(user)
if userErr != nil {
c.ResponseError(userErr.Error())
return
}
// Only allow users to view their own transactions
if transaction.User != userName {
c.ResponseError(c.T("auth:Unauthorized operation"))
return
}
}
c.ResponseOk(transaction)
}
// UpdateTransaction
// @Title UpdateTransaction
// @Tag Transaction API
// @Description update transaction
// @Param id query string true "The id ( owner/name ) of the transaction"
// @Param body body object.Transaction true "The details of the transaction"
// @Success 200 {object} controllers.Response The Response object
// @router /update-transaction [post]
func (c *ApiController) UpdateTransaction() {
id := c.Ctx.Input.Query("id")
var transaction object.Transaction
err := json.Unmarshal(c.Ctx.Input.RequestBody, &transaction)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.UpdateTransaction(id, &transaction, c.GetAcceptLanguage()))
c.ServeJSON()
}
// AddTransaction
// @Title AddTransaction
// @Tag Transaction API
// @Description add transaction
// @Param body body object.Transaction true "The details of the transaction"
// @Param dryRun query string false "Dry run mode: set to 'true' or '1' to validate without committing"
// @Success 200 {object} controllers.Response The Response object
// @router /add-transaction [post]
func (c *ApiController) AddTransaction() {
var transaction object.Transaction
err := json.Unmarshal(c.Ctx.Input.RequestBody, &transaction)
if err != nil {
c.ResponseError(err.Error())
return
}
dryRunParam := c.Ctx.Input.Query("dryRun")
dryRun := dryRunParam != ""
affected, transactionId, err := object.AddTransaction(&transaction, c.GetAcceptLanguage(), dryRun)
if err != nil {
c.ResponseError(err.Error())
return
}
if !affected {
c.Data["json"] = wrapActionResponse(false)
c.ServeJSON()
return
}
c.ResponseOk(transactionId)
}
// DeleteTransaction
// @Title DeleteTransaction
// @Tag Transaction API
// @Description delete transaction
// @Param body body object.Transaction true "The details of the transaction"
// @Success 200 {object} controllers.Response The Response object
// @router /delete-transaction [post]
func (c *ApiController) DeleteTransaction() {
var transaction object.Transaction
err := json.Unmarshal(c.Ctx.Input.RequestBody, &transaction)
if err != nil {
c.ResponseError(err.Error())
return
}
c.Data["json"] = wrapActionResponse(object.DeleteTransaction(&transaction, c.GetAcceptLanguage()))
c.ServeJSON()
}

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