From 4682fe3eb4277e4dce52ea14aa087104dbaf6600 Mon Sep 17 00:00:00 2001 From: fanmuchen Date: Wed, 7 May 2025 22:53:15 +0800 Subject: [PATCH] Logto Integration Attempt 1. --- .env.dev | 4 +- AI_RULES.md | 2 + backend/.env.example | 0 backend/go.mod | 45 +++++--- backend/go.sum | 63 +++++++++++ backend/internal/handlers/logto.go | 110 +++++++++++++++++++ backend/internal/middleware/cors.go | 29 +++++ backend/internal/routes/router.go | 15 ++- backend/main.go | 10 ++ docker-compose.yml | 3 +- frontend/next.config.ts | 12 -- frontend/src/app/components/AuthStatus.tsx | 98 +++++++++++++++++ frontend/src/app/components/HealthStatus.tsx | 4 +- frontend/src/app/contexts/AuthContext.tsx | 85 ++++++++++++++ frontend/src/app/layout.tsx | 5 +- frontend/src/app/page.tsx | 29 ++++- frontend/src/app/providers.tsx | 8 ++ sh/Caddyfile.sample | 2 +- 18 files changed, 487 insertions(+), 37 deletions(-) create mode 100644 backend/.env.example create mode 100644 backend/internal/handlers/logto.go create mode 100644 backend/internal/middleware/cors.go create mode 100644 frontend/src/app/components/AuthStatus.tsx create mode 100644 frontend/src/app/contexts/AuthContext.tsx create mode 100644 frontend/src/app/providers.tsx diff --git a/.env.dev b/.env.dev index 8864d32..7834b96 100644 --- a/.env.dev +++ b/.env.dev @@ -5,13 +5,13 @@ BACKEND_PORT=8080 FRONTEND_PORT=3000 BASE_URL=http://localhost:3000 -API_URL=http://localhost:8080/service +NEXT_PUBLIC_BACKEND_URL=http://localhost:8080/service # Logto Authentication Configuration LOGTO_ENDPOINT=https://auth.muchen.fan LOGTO_APP_ID=nm3btt4j9v26rtt82t64e LOGTO_APP_SECRET=2no3Gml080KbIGqAihfc0G8uRtk0DVQv -LOGTO_REDIRECT_URI=http://localhost:3000/service/auth/callback +LOGTO_REDIRECT_URI=http://localhost:8080/service/auth/callback LOGTO_POST_SIGN_OUT_REDIRECT_URI=http://localhost:3000 COOKIE_SECRET=2QEzOcjnHej7wLMlbh57Hkhnzaqcddx8 diff --git a/AI_RULES.md b/AI_RULES.md index 18f6961..cf811d9 100644 --- a/AI_RULES.md +++ b/AI_RULES.md @@ -25,6 +25,8 @@ starter/ ├── internal/ │ └── ... ├── main.go + ├── go.mod + ├── go.sum └── ... ``` diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..e69de29 diff --git a/backend/go.mod b/backend/go.mod index 1fc81a1..f8db8f9 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -2,31 +2,42 @@ module starter/backend go 1.23.9 -require github.com/gin-gonic/gin v1.9.1 +require github.com/gin-gonic/gin v1.10.0 require ( - github.com/bytedance/sonic v1.9.1 // indirect + github.com/bytedance/sonic v1.13.2 // indirect + github.com/bytedance/sonic/loader v0.2.4 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect - github.com/gabriel-vasile/mimetype v1.4.2 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect + github.com/cloudwego/base64x v0.1.5 // indirect + github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/gin-contrib/cors v1.7.5 // indirect + github.com/gin-contrib/sessions v1.0.3 // indirect + github.com/gin-contrib/sse v1.0.0 // indirect + github.com/go-jose/go-jose/v4 v4.0.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.14.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect + github.com/go-playground/validator/v10 v10.26.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/gorilla/context v1.1.2 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/gorilla/sessions v1.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/cpuid/v2 v2.2.4 // indirect - github.com/leodido/go-urn v1.2.4 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect + github.com/klauspost/cpuid/v2 v2.2.10 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/logto-io/go v1.0.6 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/ugorji/go/codec v1.2.11 // indirect - golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.9.0 // indirect - golang.org/x/net v0.10.0 // indirect - golang.org/x/sys v0.8.0 // indirect - golang.org/x/text v0.9.0 // indirect - google.golang.org/protobuf v1.30.0 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.16.0 // indirect + golang.org/x/crypto v0.37.0 // indirect + golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 // indirect + golang.org/x/net v0.38.0 // indirect + golang.org/x/sys v0.32.0 // indirect + golang.org/x/text v0.24.0 // indirect + google.golang.org/protobuf v1.36.6 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/backend/go.sum b/backend/go.sum index 1a77fa1..dea38e3 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,18 +1,38 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ= +github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY= +github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4= +github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= +github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/gin-contrib/cors v1.7.5 h1:cXC9SmofOrRg0w9PigwGlHG3ztswH6bqq4vJVXnvYMk= +github.com/gin-contrib/cors v1.7.5/go.mod h1:4q3yi7xBEDDWKapjT2o1V7mScKDDr8k+jZ0fSquGoy0= +github.com/gin-contrib/sessions v1.0.3 h1:AZ4j0AalLsGqdrKNbbrKcXx9OJZqViirvNGsJTxcQps= +github.com/gin-contrib/sessions v1.0.3/go.mod h1:5i4XMx4KPtQihnzxEqG9u1K446lO3G19jAi2GtbfsAI= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E= +github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-jose/go-jose/v4 v4.0.2 h1:R3l3kkBds16bO7ZFAEEcofK0MkrAJt3jlJznWZG0nvk= +github.com/go-jose/go-jose/v4 v4.0.2/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -21,21 +41,40 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k= +github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o= +github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= +github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ= +github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/logto-io/go v1.0.6 h1:p+KHiXk6v0vIuq+1sYabjbgsnHQP5lV4t2ZnkLNtRkM= +github.com/logto-io/go v1.0.6/go.mod h1:owKJJjlaiQxbBGeIDFQTTtufp7ANb9odBXyqUheqWFI= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -43,11 +82,16 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b h1:aUNXCGgukb4gtY99imuIeoh8Vr0GSwAlYxPAhqZrpFc= +github.com/quasoft/memstore v0.0.0-20191010062613-2bce066d2b0b/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -56,31 +100,50 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.16.0 h1:foMtLTdyOmIniqWCHjY6+JxuC54XP1fDwx4N0ASyW+U= +golang.org/x/arch v0.16.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE= golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= +golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= +golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY= +golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8= +golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= +golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/backend/internal/handlers/logto.go b/backend/internal/handlers/logto.go new file mode 100644 index 0000000..ff30d74 --- /dev/null +++ b/backend/internal/handlers/logto.go @@ -0,0 +1,110 @@ +package handlers + +import ( + "net/http" + "os" + + "github.com/gin-contrib/sessions" + "github.com/gin-gonic/gin" + "github.com/logto-io/go/client" +) + +// SessionStorage implements Logto's Storage interface using Gin sessions +// Avoid cookie-based sessions due to size limits; use memory-based sessions for demo +// In production, use Redis/MongoDB + +type SessionStorage struct { + session sessions.Session +} + +func (s *SessionStorage) GetItem(key string) string { + value := s.session.Get(key) + if value == nil { + return "" + } + str, ok := value.(string) + if !ok { + return "" + } + return str +} + +func (s *SessionStorage) SetItem(key, value string) { + s.session.Set(key, value) + s.session.Save() +} + +// getLogtoConfig returns Logto config from environment variables +func getLogtoConfig() *client.LogtoConfig { + return &client.LogtoConfig{ + Endpoint: os.Getenv("LOGTO_ENDPOINT"), + AppId: os.Getenv("LOGTO_APP_ID"), + AppSecret: os.Getenv("LOGTO_APP_SECRET"), + } +} + +// HomeHandler shows auth state and sign-in/sign-out links +func HomeHandler(ctx *gin.Context) { + session := sessions.Default(ctx) + logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session}) + authState := "You are not logged in to this website. :(" + if logtoClient.IsAuthenticated() { + authState = "You are logged in to this website! :)" + } + homePage := "

Hello Logto

" + + "
" + authState + "
" + + `
Sign In
` + + `
Sign Out
` + ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage)) +} + +// SignInHandler starts the Logto sign-in flow +func SignInHandler(ctx *gin.Context) { + session := sessions.Default(ctx) + logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session}) + redirectUri := os.Getenv("LOGTO_REDIRECT_URI") + signInUri, err := logtoClient.SignIn(redirectUri) + if err != nil { + ctx.String(http.StatusInternalServerError, err.Error()) + return + } + ctx.Redirect(http.StatusTemporaryRedirect, signInUri) +} + +// CallbackHandler handles the Logto sign-in callback +func CallbackHandler(ctx *gin.Context) { + session := sessions.Default(ctx) + logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session}) + err := logtoClient.HandleSignInCallback(ctx.Request) + if err != nil { + ctx.String(http.StatusInternalServerError, err.Error()) + return + } + // Redirect to the frontend page instead of the backend auth page + ctx.Redirect(http.StatusTemporaryRedirect, os.Getenv("BASE_URL")) +} + +// SignOutHandler starts the Logto sign-out flow +func SignOutHandler(ctx *gin.Context) { + session := sessions.Default(ctx) + logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session}) + postSignOutRedirectUri := os.Getenv("LOGTO_POST_SIGN_OUT_REDIRECT_URI") + signOutUri, err := logtoClient.SignOut(postSignOutRedirectUri) + if err != nil { + ctx.String(http.StatusOK, err.Error()) + return + } + ctx.Redirect(http.StatusTemporaryRedirect, signOutUri) +} + +// UserIdTokenClaimsHandler returns the user's ID token claims as JSON +func UserIdTokenClaimsHandler(ctx *gin.Context) { + session := sessions.Default(ctx) + logtoClient := client.NewLogtoClient(getLogtoConfig(), &SessionStorage{session: session}) + idTokenClaims, err := logtoClient.GetIdTokenClaims() + if err != nil { + ctx.String(http.StatusOK, err.Error()) + return + } + ctx.JSON(http.StatusOK, idTokenClaims) +} diff --git a/backend/internal/middleware/cors.go b/backend/internal/middleware/cors.go new file mode 100644 index 0000000..080d23d --- /dev/null +++ b/backend/internal/middleware/cors.go @@ -0,0 +1,29 @@ +package middleware + +import ( + "os" + + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" +) + +// CORS returns a middleware that handles CORS requests +// It only enables CORS in development mode +func CORS() gin.HandlerFunc { + // Check if we're in development mode (you can use an environment variable for this) + if os.Getenv("GIN_MODE") != "release" { + // CORS configuration for development + config := cors.DefaultConfig() + config.AllowOrigins = []string{"http://localhost:3000"} // Frontend URL + config.AllowCredentials = true // Important for cookies/auth + config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"} + config.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization"} + + return cors.New(config) + } + + // In production, no CORS middleware is needed if frontend and backend are served from the same domain + return func(c *gin.Context) { + c.Next() + } +} \ No newline at end of file diff --git a/backend/internal/routes/router.go b/backend/internal/routes/router.go index 1567d44..6ee8085 100644 --- a/backend/internal/routes/router.go +++ b/backend/internal/routes/router.go @@ -9,6 +9,19 @@ import ( // RegisterRoutes registers all API routes under the given group func RegisterRoutes(rg *gin.RouterGroup) { + // Apply CORS middleware first (before any other middleware) + rg.Use(middleware.CORS()) + + // Then apply other middlewares rg.Use(middleware.Logger()) + + // Define routes rg.GET("/health", handlers.HealthCheck) -} \ No newline at end of file + + // Logto authentication routes + rg.GET("/auth/", handlers.HomeHandler) + rg.GET("/auth/sign-in", handlers.SignInHandler) + rg.GET("/auth/callback", handlers.CallbackHandler) + rg.GET("/auth/sign-out", handlers.SignOutHandler) + rg.GET("/auth/user-id-token-claims", handlers.UserIdTokenClaimsHandler) +} diff --git a/backend/main.go b/backend/main.go index 9b99e79..93cd471 100644 --- a/backend/main.go +++ b/backend/main.go @@ -6,12 +6,22 @@ import ( "starter/backend/internal/routes" + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() + // Add memory-based session store for Logto + cookieSecret := os.Getenv("COOKIE_SECRET") + if cookieSecret == "" { + cookieSecret = "default_session_secret" // fallback for local dev + } + store := memstore.NewStore([]byte(cookieSecret)) + r.Use(sessions.Sessions("logto-session", store)) + // Register all routes under /service/ serviceGroup := r.Group("/service") routes.RegisterRoutes(serviceGroup) diff --git a/docker-compose.yml b/docker-compose.yml index f3eeef2..8e86ad6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: ports: - "${BACKEND_PORT}:8080" environment: - - BACKEND_PORT=${BACKEND_PORT} + - GIN_MODE=release networks: - starter_network @@ -20,6 +20,7 @@ services: - "${FRONTEND_PORT}:3000" environment: - NODE_ENV=production + - NEXT_PUBLIC_BACKEND_URL=${NEXT_PUBLIC_BACKEND_URL} # depends_on: # - backend networks: diff --git a/frontend/next.config.ts b/frontend/next.config.ts index 8c8b6ff..e9ffa30 100644 --- a/frontend/next.config.ts +++ b/frontend/next.config.ts @@ -2,18 +2,6 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ - async rewrites() { - // Only apply proxy in development environment - if (process.env.NODE_ENV === "development") { - return [ - { - source: "/service/:path*", - destination: "http://localhost:8080/service/:path*", // assuming Go backend runs on port 8080 - }, - ]; - } - return []; - }, }; export default nextConfig; diff --git a/frontend/src/app/components/AuthStatus.tsx b/frontend/src/app/components/AuthStatus.tsx new file mode 100644 index 0000000..ab9a78b --- /dev/null +++ b/frontend/src/app/components/AuthStatus.tsx @@ -0,0 +1,98 @@ +"use client"; +import { useAuth } from "../contexts/AuthContext"; + +export default function AuthStatus() { + const { isAuthenticated, user, login, logout, loading } = useAuth(); + + if (loading) { + return ( +
+

Loading authentication status...

+
+ ); + } + + return ( +
+
+ {isAuthenticated ? ( + <> +

Authenticated ✅

+ {user && ( +
+

Name: {user.name || "N/A"}

+

Email: {user.email || "N/A"}

+
+ )} + + ) : ( +

Not authenticated ❌

+ )} +
+ +
+ {isAuthenticated ? ( + + ) : ( + + )} +
+ + +
+ ); +} diff --git a/frontend/src/app/components/HealthStatus.tsx b/frontend/src/app/components/HealthStatus.tsx index e0d60ac..1bf27ee 100644 --- a/frontend/src/app/components/HealthStatus.tsx +++ b/frontend/src/app/components/HealthStatus.tsx @@ -10,7 +10,9 @@ export default function HealthStatus() { const checkHealth = async () => { try { setLoading(true); - const response = await fetch("/service/health"); + const response = await fetch( + `${process.env.NEXT_PUBLIC_BACKEND_URL}/health` + ); if (!response.ok) { throw new Error(`Server responded with status: ${response.status}`); diff --git a/frontend/src/app/contexts/AuthContext.tsx b/frontend/src/app/contexts/AuthContext.tsx new file mode 100644 index 0000000..45b0d2f --- /dev/null +++ b/frontend/src/app/contexts/AuthContext.tsx @@ -0,0 +1,85 @@ +import { + createContext, + useContext, + useState, + useEffect, + ReactNode, +} from "react"; + +interface UserData { + id?: string; + email?: string; + name?: string; + [key: string]: unknown; +} + +interface AuthContextType { + isAuthenticated: boolean; + user: UserData | null; + login: () => void; + logout: () => void; + loading: boolean; +} + +const AuthContext = createContext(undefined); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [isAuthenticated, setIsAuthenticated] = useState(false); + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + // Check authentication status on mount + checkAuthStatus(); + }, []); + + const checkAuthStatus = async () => { + try { + const response = await fetch( + `${process.env.NEXT_PUBLIC_BACKEND_URL}/auth/user-id-token-claims`, + { + credentials: "include", + } + ); + + if (response.ok) { + const userData = await response.json(); + setUser(userData); + setIsAuthenticated(true); + } else { + setUser(null); + setIsAuthenticated(false); + } + } catch (error) { + console.error("Error checking auth status:", error); + setIsAuthenticated(false); + setUser(null); + } finally { + setLoading(false); + } + }; + + const login = () => { + window.location.href = `${process.env.NEXT_PUBLIC_BACKEND_URL}/auth/sign-in`; + }; + + const logout = () => { + window.location.href = `${process.env.NEXT_PUBLIC_BACKEND_URL}/auth/sign-out`; + }; + + return ( + + {children} + + ); +} + +export function useAuth() { + const context = useContext(AuthContext); + if (context === undefined) { + throw new Error("useAuth must be used within an AuthProvider"); + } + return context; +} diff --git a/frontend/src/app/layout.tsx b/frontend/src/app/layout.tsx index 56ed191..099fc9f 100644 --- a/frontend/src/app/layout.tsx +++ b/frontend/src/app/layout.tsx @@ -1,4 +1,5 @@ import type { Metadata } from "next"; +import { Providers } from "./providers"; import "./globals.css"; export const metadata: Metadata = { @@ -13,7 +14,9 @@ export default function RootLayout({ }) { return ( - {children} + + {children} + ); } diff --git a/frontend/src/app/page.tsx b/frontend/src/app/page.tsx index cbda622..8868c56 100644 --- a/frontend/src/app/page.tsx +++ b/frontend/src/app/page.tsx @@ -1,11 +1,22 @@ "use client"; import HealthStatus from "./components/HealthStatus"; +import AuthStatus from "./components/AuthStatus"; export default function Home() { return (

Welcome to Starter App

- + +
+

Authentication

+ +
+ +
+

Backend Health

+ +
+
diff --git a/frontend/src/app/providers.tsx b/frontend/src/app/providers.tsx new file mode 100644 index 0000000..a091b53 --- /dev/null +++ b/frontend/src/app/providers.tsx @@ -0,0 +1,8 @@ +"use client"; + +import { ReactNode } from "react"; +import { AuthProvider } from "./contexts/AuthContext"; + +export function Providers({ children }: { children: ReactNode }) { + return {children}; +} diff --git a/sh/Caddyfile.sample b/sh/Caddyfile.sample index 6fd32e0..ea0b7b1 100644 --- a/sh/Caddyfile.sample +++ b/sh/Caddyfile.sample @@ -1,6 +1,6 @@ ---.-----.--- { # Handle API requests first - handle_path /api/* { + handle /service/* { reverse_proxy ---.---.---.---:---- { header_up Host {host} header_up X-Real-IP {remote}