initial commit
This commit is contained in:
@@ -0,0 +1,6 @@
|
|||||||
|
kotosoft-id-frontend/node_modules
|
||||||
|
kotosoft-id-frontend/.next/
|
||||||
|
kotosoft-id-frontend/.env
|
||||||
|
kotosoft-id-frontend/next-env.d.ts
|
||||||
|
|
||||||
|
kotosoft-id-backend/.env
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/config"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/db"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
||||||
|
apphttp "github.com/dusiburg/kotosoft-id/internal/http"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
cfg, err := config.New()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pg, err := db.ConnectPostgres(cfg.Postgres.URL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, pg.Pool); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rdb, err := db.ConnectRedis(cfg.Redis.URL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
userRepo := repositories.NewUserRepository(pg.Pool)
|
||||||
|
oauthRepo := repositories.NewOAuthRepository(pg.Pool)
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
basicClient, err := ensureBasicClient(ctx, cfg, oauthRepo)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := services.New(userRepo, oauthRepo, rdb.Client, services.TokenConfig{
|
||||||
|
AccessTTL: cfg.JWT.TTL,
|
||||||
|
RefreshTTL: cfg.JWT.TTL * 7,
|
||||||
|
}, basicClient)
|
||||||
|
|
||||||
|
authHandler := handlers.NewAuthHandler(svc)
|
||||||
|
oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL)
|
||||||
|
consentHandler := handlers.NewConsentHandler(svc)
|
||||||
|
|
||||||
|
r := apphttp.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo)
|
||||||
|
log.Fatal(r.Run(cfg.Server.Addr))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureBasicClient(ctx context.Context, cfg *config.Conf, repo *repositories.OAuthRepository) (*models.OAuthClient, error) {
|
||||||
|
client, err := repo.GetOAuthClientByClientID(ctx, cfg.Client.ID)
|
||||||
|
if err == nil {
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
hashedSecret, err := services.HashClientSecret(cfg.Client.Secret)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return repo.CreateOAuthClient(ctx, models.OAuthClient{
|
||||||
|
ClientID: cfg.Client.ID,
|
||||||
|
ClientSecret: hashedSecret,
|
||||||
|
Name: cfg.Client.Name,
|
||||||
|
RedirectURIs: json.RawMessage(cfg.Client.RedirectURIsJSON()),
|
||||||
|
GrantTypes: json.RawMessage(cfg.Client.GrantTypesJSON()),
|
||||||
|
Scopes: json.RawMessage(cfg.Client.ScopesJSON()),
|
||||||
|
Trusted: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
module github.com/dusiburg/kotosoft-id
|
||||||
|
|
||||||
|
go 1.25.3
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/caarlos0/env/v11 v11.4.0
|
||||||
|
github.com/gin-gonic/gin v1.11.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jackc/pgx/v5 v5.8.0
|
||||||
|
github.com/joho/godotenv v1.5.1
|
||||||
|
golang.org/x/crypto v0.48.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/bytedance/sonic v1.14.0 // indirect
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||||
|
github.com/gin-contrib/sse v1.1.0 // 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.27.0 // indirect
|
||||||
|
github.com/goccy/go-json v0.10.2 // indirect
|
||||||
|
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||||
|
github.com/quic-go/qpack v0.5.1 // indirect
|
||||||
|
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||||
|
github.com/redis/go-redis/v9 v9.18.0 // indirect
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
|
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||||
|
go.uber.org/atomic v1.11.0 // indirect
|
||||||
|
go.uber.org/mock v0.5.0 // indirect
|
||||||
|
golang.org/x/arch v0.20.0 // indirect
|
||||||
|
golang.org/x/mod v0.32.0 // indirect
|
||||||
|
golang.org/x/net v0.49.0 // indirect
|
||||||
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
|
golang.org/x/text v0.34.0 // indirect
|
||||||
|
golang.org/x/tools v0.41.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.9 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||||
|
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||||
|
github.com/caarlos0/env/v11 v11.4.0 h1:Kcb6t5kIIr4XkoQC9AF2j+8E1Jsrl3Wz/hhm1LtoGAc=
|
||||||
|
github.com/caarlos0/env/v11 v11.4.0/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||||
|
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||||
|
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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||||
|
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/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||||
|
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||||
|
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||||
|
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||||
|
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=
|
||||||
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||||
|
github.com/go-playground/validator/v10 v10.27.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-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||||
|
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
|
||||||
|
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
|
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.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||||
|
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/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 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
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/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||||
|
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||||
|
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||||
|
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||||
|
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||||
|
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||||
|
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/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=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
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.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||||
|
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
|
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||||
|
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||||
|
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||||
|
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||||
|
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||||
|
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||||
|
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||||
|
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||||
|
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
|
||||||
|
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
|
||||||
|
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||||
|
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||||
|
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||||
|
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||||
|
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||||
|
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||||
|
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||||
|
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||||
|
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||||
|
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||||
|
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=
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/caarlos0/env/v11"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Conf struct {
|
||||||
|
Server Server
|
||||||
|
Postgres Postgres
|
||||||
|
Redis Redis
|
||||||
|
Client Client
|
||||||
|
JWT JWT
|
||||||
|
}
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
Addr string `env:"SERVER_ADDR" envDefault:":8080"`
|
||||||
|
FrontendURL string `env:"FRONTEND_URL,required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Postgres struct {
|
||||||
|
URL string `env:"POSTGRES_URL,required"`
|
||||||
|
MigrationFilePath string `env:"POSTGRES_MIGRATION_FILE_PATH,required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Redis struct {
|
||||||
|
URL string `env:"REDIS_URL,required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
ID string `env:"CLIENT_ID,required"`
|
||||||
|
Secret string `env:"CLIENT_SECRET,required"`
|
||||||
|
Name string `env:"CLIENT_NAME" envDefault:"Basic Client"`
|
||||||
|
RedirectURIs []string `env:"CLIENT_REDIRECT_URIS" envSeparator:","`
|
||||||
|
GrantTypes []string `env:"CLIENT_GRANT_TYPES" envSeparator:"," envDefault:"refresh_token"`
|
||||||
|
Scopes []string `env:"CLIENT_SCOPES" envSeparator:"," envDefault:"profile:read,profile:edit,profile:consent:read,profile:consent:delete,auth:register"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type JWT struct {
|
||||||
|
Secret string `env:"JWT_SECRET,required"`
|
||||||
|
TTL time.Duration `env:"JWT_TTL" envDefault:"24h"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() (*Conf, error) {
|
||||||
|
_ = godotenv.Load()
|
||||||
|
|
||||||
|
var conf Conf
|
||||||
|
if err := env.Parse(&conf); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &conf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) RedirectURIsJSON() string {
|
||||||
|
if len(c.RedirectURIs) == 0 {
|
||||||
|
return "[]"
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("[\"")
|
||||||
|
b.WriteString(strings.Join(c.RedirectURIs, "\",\""))
|
||||||
|
b.WriteString("\"]")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) GrantTypesJSON() string {
|
||||||
|
if len(c.GrantTypes) == 0 {
|
||||||
|
return "[]"
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("[\"")
|
||||||
|
b.WriteString(strings.Join(c.GrantTypes, "\",\""))
|
||||||
|
b.WriteString("\"]")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) ScopesJSON() string {
|
||||||
|
if len(c.Scopes) == 0 {
|
||||||
|
return "[]"
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("[\"")
|
||||||
|
b.WriteString(strings.Join(c.Scopes, "\",\""))
|
||||||
|
b.WriteString("\"]")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RunMigrations(migrationFilePath string, pool *pgxpool.Pool) error {
|
||||||
|
sql, err := os.ReadFile(migrationFilePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to execute migrations: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = pool.Exec(context.Background(), string(sql))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to execute migrations: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type DB struct {
|
||||||
|
Pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConnectPostgres(url string) (*DB, error) {
|
||||||
|
pool, err := pgxpool.New(context.Background(), url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create DB: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to connect to DB: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &DB{Pool: pool}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RedisDB struct {
|
||||||
|
Client *redis.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConnectRedis(url string) (*RedisDB, error) {
|
||||||
|
opt, err := redis.ParseURL(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid Redis URL: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
rdb := redis.NewClient(opt)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &RedisDB{Client: rdb}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthHandler struct {
|
||||||
|
svc *services.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthHandler(svc *services.Service) *AuthHandler {
|
||||||
|
return &AuthHandler{svc: svc}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) Register(c *gin.Context) {
|
||||||
|
var input models.UserRegisterInput
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.Error(models.ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id, secret, ok := c.Request.BasicAuth()
|
||||||
|
if !ok {
|
||||||
|
c.Error(models.ErrUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
service, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{ClientID: id, ClientSecret: secret})
|
||||||
|
if err != nil {
|
||||||
|
c.Error(models.ErrUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !service.Trusted {
|
||||||
|
c.Error(models.ErrForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := h.svc.Register(c.Request.Context(), input)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) Refresh(c *gin.Context) {
|
||||||
|
var input struct {
|
||||||
|
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.Error(models.ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pair, err := h.svc.RefreshTokens(c.Request.Context(), input.RefreshToken)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, pair)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) Profile(c *gin.Context) {
|
||||||
|
userID := mustUserID(c)
|
||||||
|
|
||||||
|
user, err := h.svc.GetUserByID(c.Request.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(models.ErrNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) UpdateProfile(c *gin.Context) {
|
||||||
|
userID := mustUserID(c)
|
||||||
|
|
||||||
|
var input models.UserUpdateInput
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.Error(models.ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := h.svc.UpdateProfile(c.Request.Context(), userID, input)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *AuthHandler) DeleteProfile(c *gin.Context) {
|
||||||
|
userID := mustUserID(c)
|
||||||
|
token, _ := bearerToken(c)
|
||||||
|
|
||||||
|
if err := h.svc.DeleteProfile(c.Request.Context(), userID, token); err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustUserID(c *gin.Context) uuid.UUID {
|
||||||
|
return c.MustGet("user_id").(uuid.UUID)
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConsentHandler struct {
|
||||||
|
svc *services.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConsentHandler(svc *services.Service) *ConsentHandler {
|
||||||
|
return &ConsentHandler{svc: svc}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsentHandler) GetUserConsents(c *gin.Context) {
|
||||||
|
userID := mustUserID(c)
|
||||||
|
|
||||||
|
consents, err := h.svc.GetUserConsents(c.Request.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, consents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsentHandler) RevokeAppAccess(c *gin.Context) {
|
||||||
|
userID := mustUserID(c)
|
||||||
|
clientID := c.Param("clientId")
|
||||||
|
|
||||||
|
if err := h.svc.RevokeConsent(c.Request.Context(), userID, clientID); err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OAuthHandler struct {
|
||||||
|
svc *services.Service
|
||||||
|
frontendURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewOAuthHandler(svc *services.Service, frontendURL string) *OAuthHandler {
|
||||||
|
return &OAuthHandler{svc: svc, frontendURL: frontendURL}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) Authorize(c *gin.Context) {
|
||||||
|
token, err := h.svc.CreateOAuthSession(
|
||||||
|
c.Request.Context(),
|
||||||
|
c.Query("client_id"),
|
||||||
|
c.Query("redirect_uri"),
|
||||||
|
c.Query("scope"),
|
||||||
|
c.Query("state"),
|
||||||
|
c.Query("code_challenge"),
|
||||||
|
c.Query("code_challenge_method"),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Redirect(http.StatusFound, h.frontendURL+"/oauth?session="+token)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) GetSession(c *gin.Context) {
|
||||||
|
sess, err := h.svc.GetOAuthSession(c.Request.Context(), c.Param("token"))
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidGrant)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, sess)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) SessionLogin(c *gin.Context) {
|
||||||
|
var input struct {
|
||||||
|
Session string `json:"session" binding:"required"`
|
||||||
|
Email string `json:"email" binding:"required"`
|
||||||
|
Password string `json:"password" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectURL, err := h.svc.SessionLogin(c.Request.Context(), input.Session, input.Email, input.Password)
|
||||||
|
if err != nil {
|
||||||
|
if err == services.ErrInvalidGrant {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidGrant)
|
||||||
|
} else {
|
||||||
|
oauthErrorJSON(c, services.ErrAccessDenied)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if redirectURL != "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) SessionAttach(c *gin.Context) {
|
||||||
|
var input struct {
|
||||||
|
Session string `json:"session" binding:"required"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
accessToken, ok := bearerToken(c)
|
||||||
|
if !ok {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidClient)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectURL, err := h.svc.SessionAttach(c.Request.Context(), input.Session, accessToken)
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, services.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if redirectURL != "" {
|
||||||
|
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) SessionApprove(c *gin.Context) {
|
||||||
|
var input struct {
|
||||||
|
Session string `json:"session" binding:"required"`
|
||||||
|
Allow bool `json:"allow"`
|
||||||
|
}
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
oauthErrorJSON(c, services.ErrInvalidRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !input.Allow {
|
||||||
|
oauthErrorJSON(c, services.ErrAccessDenied)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectURL, err := h.svc.SessionApprove(c.Request.Context(), input.Session)
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, gin.H{"redirect_url": redirectURL})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) Token(c *gin.Context) {
|
||||||
|
auth := h.extractClientAuth(c)
|
||||||
|
|
||||||
|
switch c.PostForm("grant_type") {
|
||||||
|
case "authorization_code":
|
||||||
|
pair, err := h.svc.ExchangeCode(
|
||||||
|
c.Request.Context(), auth,
|
||||||
|
c.PostForm("code"),
|
||||||
|
c.PostForm("redirect_uri"),
|
||||||
|
c.PostForm("code_verifier"),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pair.User = nil
|
||||||
|
c.JSON(http.StatusOK, pair)
|
||||||
|
|
||||||
|
case "refresh_token":
|
||||||
|
pair, err := h.svc.ExchangeRefreshToken(c.Request.Context(), auth, c.PostForm("refresh_token"))
|
||||||
|
if err != nil {
|
||||||
|
oauthErrorJSON(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pair.User = nil
|
||||||
|
c.JSON(http.StatusOK, pair)
|
||||||
|
|
||||||
|
default:
|
||||||
|
oauthErrorJSON(c, services.ErrUnsupportedGrantType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) Revoke(c *gin.Context) {
|
||||||
|
_ = h.svc.RevokeToken(c.Request.Context(), h.extractClientAuth(c), c.PostForm("token"))
|
||||||
|
c.Status(http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *OAuthHandler) extractClientAuth(c *gin.Context) services.ClientAuth {
|
||||||
|
if id, secret, ok := c.Request.BasicAuth(); ok {
|
||||||
|
return services.ClientAuth{ClientID: id, ClientSecret: secret}
|
||||||
|
}
|
||||||
|
return services.ClientAuth{
|
||||||
|
ClientID: c.PostForm("client_id"),
|
||||||
|
ClientSecret: c.PostForm("client_secret"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearerToken(c *gin.Context) (string, bool) {
|
||||||
|
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func oauthErrorJSON(c *gin.Context, err error) {
|
||||||
|
code, desc, status := oauthErrorDetails(err)
|
||||||
|
if code == "invalid_client" {
|
||||||
|
c.Header("WWW-Authenticate", `Basic realm="oauth"`)
|
||||||
|
}
|
||||||
|
c.JSON(status, gin.H{"error": code, "error_description": desc})
|
||||||
|
}
|
||||||
|
|
||||||
|
func oauthErrorDetails(err error) (code, desc string, status int) {
|
||||||
|
switch err {
|
||||||
|
case services.ErrInvalidRequest:
|
||||||
|
return "invalid_request", "Invalid request parameters", http.StatusBadRequest
|
||||||
|
case services.ErrUnauthorizedClient:
|
||||||
|
return "unauthorized_client", "Client not authorized", http.StatusBadRequest
|
||||||
|
case services.ErrAccessDenied:
|
||||||
|
return "access_denied", "Access denied", http.StatusForbidden
|
||||||
|
case services.ErrInvalidClient:
|
||||||
|
return "invalid_client", "Invalid client credentials", http.StatusUnauthorized
|
||||||
|
case services.ErrInvalidGrant:
|
||||||
|
return "invalid_grant", "Invalid or expired grant", http.StatusBadRequest
|
||||||
|
case services.ErrUnsupportedGrantType:
|
||||||
|
return "unsupported_grant_type", "Grant type not supported", http.StatusBadRequest
|
||||||
|
default:
|
||||||
|
return "server_error", "An unexpected error occurred", http.StatusInternalServerError
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package http
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/handlers"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/repositories"
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/services"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository) *gin.Engine {
|
||||||
|
r := gin.Default()
|
||||||
|
r.Use(errorMiddleware())
|
||||||
|
|
||||||
|
o := r.Group("/oauth")
|
||||||
|
{
|
||||||
|
o.GET("/authorize", oauth.Authorize)
|
||||||
|
o.GET("/session/:token", oauth.GetSession)
|
||||||
|
o.POST("/session/login", oauth.SessionLogin)
|
||||||
|
o.POST("/session/attach", oauth.SessionAttach)
|
||||||
|
o.POST("/session/approve", oauth.SessionApprove)
|
||||||
|
o.POST("/token", oauth.Token)
|
||||||
|
o.POST("/revoke", oauth.Revoke)
|
||||||
|
}
|
||||||
|
|
||||||
|
api := r.Group("/api/v1")
|
||||||
|
{
|
||||||
|
a := api.Group("/auth")
|
||||||
|
a.POST("/register", auth.Register)
|
||||||
|
a.POST("/refresh", auth.Refresh)
|
||||||
|
|
||||||
|
me := api.Group("/me")
|
||||||
|
me.GET("", authMiddleware(svc, repo, "profile:read"), auth.Profile)
|
||||||
|
me.PATCH("", authMiddleware(svc, repo, "profile:edit"), auth.UpdateProfile)
|
||||||
|
me.DELETE("", authMiddleware(svc, repo, "profile:delete"), auth.DeleteProfile)
|
||||||
|
me.GET("/consents", authMiddleware(svc, repo, "profile:consent:read"), consents.GetUserConsents)
|
||||||
|
me.DELETE("/consent/:clientId", authMiddleware(svc, repo, "profile:consent:delete"), consents.RevokeAppAccess)
|
||||||
|
}
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, requiredScopes ...string) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
token, ok := bearerToken(c)
|
||||||
|
if !ok {
|
||||||
|
c.Error(models.ErrUnauthorized)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
info, err := svc.ValidateAccessToken(c.Request.Context(), token)
|
||||||
|
if err != nil {
|
||||||
|
c.Error(models.ErrUnauthorized)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(requiredScopes) > 0 && !services.ScopesContain(info.Scopes, requiredScopes) {
|
||||||
|
c.Error(models.ErrInsufficientScope)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err, _ := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil {
|
||||||
|
c.Error(models.ErrForbidden)
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Set("user_id", info.UserID)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorMiddleware() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
c.Next()
|
||||||
|
if len(c.Errors) == 0 || c.Writer.Written() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err := c.Errors.Last().Err
|
||||||
|
if apiErr, ok := err.(*models.APIError); ok {
|
||||||
|
c.JSON(apiErr.Code, apiErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(500, models.ErrInternal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientAuthFromRequest(c *gin.Context) services.ClientAuth {
|
||||||
|
if id, secret, ok := c.Request.BasicAuth(); ok {
|
||||||
|
return services.ClientAuth{ClientID: id, ClientSecret: secret}
|
||||||
|
}
|
||||||
|
return services.ClientAuth{
|
||||||
|
ClientID: c.PostForm("client_id"),
|
||||||
|
ClientSecret: c.PostForm("client_secret"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearerToken(c *gin.Context) (string, bool) {
|
||||||
|
return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserIDFromContext(c *gin.Context) (uuid.UUID, bool) {
|
||||||
|
v, ok := c.Get("user_id")
|
||||||
|
if !ok {
|
||||||
|
return uuid.Nil, false
|
||||||
|
}
|
||||||
|
id, ok := v.(uuid.UUID)
|
||||||
|
return id, ok
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
type APIError struct {
|
||||||
|
Code int `json:"-"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Slug string `json:"error"`
|
||||||
|
Cause error `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrBadRequest = &APIError{Code: 400, Slug: "bad_request", Message: "Invalid request"}
|
||||||
|
ErrUnauthorized = &APIError{Code: 401, Slug: "unauthorized", Message: "Incorrect credentials"}
|
||||||
|
ErrForbidden = &APIError{Code: 403, Slug: "forbidden", Message: "Forbidden"}
|
||||||
|
ErrInsufficientScope = &APIError{Code: 403, Slug: "insufficient_scope", Message: "The access token does not contain the required scope"}
|
||||||
|
ErrNotFound = &APIError{Code: 404, Slug: "not_found", Message: "Resource not found"}
|
||||||
|
ErrAlreadyExists = &APIError{Code: 409, Slug: "already_exists", Message: "Resource already exists"}
|
||||||
|
ErrInternal = &APIError{Code: 500, Slug: "internal", Message: "Internal server error"}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e *APIError) Error() string {
|
||||||
|
return e.Slug
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *APIError) WithMessage(msg string) *APIError {
|
||||||
|
if e == nil {
|
||||||
|
return (&APIError{Code: 500, Slug: "internal", Message: "Internal server error"}).WithMessage(msg)
|
||||||
|
}
|
||||||
|
cp := *e
|
||||||
|
cp.Message = msg
|
||||||
|
return &cp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *APIError) WithCause(cause error) *APIError {
|
||||||
|
if e == nil {
|
||||||
|
return (&APIError{Code: 500, Slug: "internal", Message: "Internal server error"}).WithCause(cause)
|
||||||
|
}
|
||||||
|
cp := *e
|
||||||
|
cp.Cause = cause
|
||||||
|
return &cp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *APIError) Unwrap() error {
|
||||||
|
if e == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return e.Cause
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OAuthClient struct {
|
||||||
|
ID uuid.UUID `db:"id" json:"id"`
|
||||||
|
ClientID string `db:"client_id" json:"client_id"`
|
||||||
|
ClientSecret string `db:"client_secret" json:"client_secret"`
|
||||||
|
Name string `db:"name" json:"name"`
|
||||||
|
RedirectURIs json.RawMessage `db:"redirect_uris" json:"redirect_uris"`
|
||||||
|
GrantTypes json.RawMessage `db:"grant_types" json:"grant_types"`
|
||||||
|
Scopes json.RawMessage `db:"scopes" json:"scopes,omitempty"`
|
||||||
|
IsActive bool `db:"is_active" json:"is_active"`
|
||||||
|
Trusted bool `db:"trusted" json:"trusted"`
|
||||||
|
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||||
|
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RefreshTokenRow struct {
|
||||||
|
ID uuid.UUID `db:"id"`
|
||||||
|
TokenHash string `db:"token_hash"`
|
||||||
|
UserID uuid.UUID `db:"user_id"`
|
||||||
|
ClientID uuid.UUID `db:"client_id"`
|
||||||
|
Scopes json.RawMessage `db:"scopes"`
|
||||||
|
ExpiresAt time.Time `db:"expires_at"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthorizationCodeRow struct {
|
||||||
|
ID uuid.UUID `db:"id"`
|
||||||
|
CodeHash string `db:"code_hash"`
|
||||||
|
UserID uuid.UUID `db:"user_id"`
|
||||||
|
ClientID uuid.UUID `db:"client_id"`
|
||||||
|
RedirectURI string `db:"redirect_uri"`
|
||||||
|
Scopes json.RawMessage `db:"scopes"`
|
||||||
|
CodeChallenge string `db:"code_challenge"`
|
||||||
|
CodeChallengeMethod string `db:"code_challenge_method"`
|
||||||
|
ExpiresAt time.Time `db:"expires_at"`
|
||||||
|
ConsumedAt *time.Time `db:"consumed_at"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserConsent struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
UserID uuid.UUID `json:"-"`
|
||||||
|
ClientID uuid.UUID `json:"-"`
|
||||||
|
ClientIdentifier string `json:"client_id"`
|
||||||
|
ClientName string `json:"client_name"`
|
||||||
|
Scopes []string `json:"scopes"`
|
||||||
|
AuthorizedAt time.Time `json:"authorized_at"`
|
||||||
|
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||||
|
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID uuid.UUID `db:"id" json:"id"`
|
||||||
|
Email string `db:"email" json:"email"`
|
||||||
|
PasswordHash string `db:"password_hash" json:"-"`
|
||||||
|
FirstName string `db:"first_name" json:"first_name"`
|
||||||
|
SecondName string `db:"second_name" json:"second_name"`
|
||||||
|
BirthDate *time.Time `db:"birth_date" json:"birth_date,omitempty"`
|
||||||
|
Sex string `db:"sex" json:"sex"`
|
||||||
|
CreatedAt time.Time `db:"created_at" json:"created_at"`
|
||||||
|
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRegisterInput struct {
|
||||||
|
Email string `json:"email" binding:"required,min=3"`
|
||||||
|
Password string `json:"password" binding:"required,min=8"`
|
||||||
|
FirstName string `json:"first_name" binding:"required,min=2,max=64"`
|
||||||
|
SecondName string `json:"second_name" binding:"required,min=2,max=64"`
|
||||||
|
BirthDate *time.Time `json:"birth_date" binding:"omitempty"`
|
||||||
|
Sex string `json:"sex" binding:"required,oneof=MALE FEMALE"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserUpdateInput struct {
|
||||||
|
FirstName string `json:"first_name" binding:"omitempty,min=2,max=64"`
|
||||||
|
SecondName string `json:"second_name" binding:"omitempty,min=2,max=64"`
|
||||||
|
BirthDate *time.Time `json:"birth_date"`
|
||||||
|
Sex string `json:"sex" binding:"omitempty,oneof=MALE FEMALE"`
|
||||||
|
Password string `json:"password" binding:"omitempty,min=8"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OAuthRepository struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewOAuthRepository(db *pgxpool.Pool) *OAuthRepository {
|
||||||
|
return &OAuthRepository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) CreateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error) {
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||||
|
RETURNING id, is_active, created_at, updated_at
|
||||||
|
`, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted).
|
||||||
|
Scan(&client.ID, &client.IsActive, &client.CreatedAt, &client.UpdatedAt)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create OAuth client: %w", err)
|
||||||
|
}
|
||||||
|
return &client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error) {
|
||||||
|
var client models.OAuthClient
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
||||||
|
FROM oauth_clients WHERE client_id = $1 AND is_active = true
|
||||||
|
`, clientID).Scan(&client.ID, &client.ClientID, &client.ClientSecret, &client.Name, &client.RedirectURIs, &client.GrantTypes, &client.Scopes, &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error) {
|
||||||
|
var client models.OAuthClient
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at
|
||||||
|
FROM oauth_clients WHERE id = $1 AND is_active = true
|
||||||
|
`, id).Scan(&client.ID, &client.ClientID, &client.ClientSecret, &client.Name, &client.RedirectURIs, &client.GrantTypes, &client.Scopes, &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error) {
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO authorization_codes (code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
|
RETURNING id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at
|
||||||
|
`, row.CodeHash, row.UserID, row.ClientID, row.RedirectURI, row.Scopes, row.CodeChallenge, row.CodeChallengeMethod, row.ExpiresAt, row.ConsumedAt, row.CreatedAt).
|
||||||
|
Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create authorization code: %w", err)
|
||||||
|
}
|
||||||
|
return &row, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error) {
|
||||||
|
var row models.AuthorizationCodeRow
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at
|
||||||
|
FROM authorization_codes WHERE code_hash = $1
|
||||||
|
`, codeHash).Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &row, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := r.db.Exec(ctx, `
|
||||||
|
UPDATE authorization_codes SET consumed_at = now()
|
||||||
|
WHERE id = $1 AND consumed_at IS NULL
|
||||||
|
`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error) {
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO refresh_tokens (token_hash, user_id, client_id, scopes, expires_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
RETURNING id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
||||||
|
`, row.TokenHash, row.UserID, row.ClientID, row.Scopes, row.ExpiresAt, row.CreatedAt).
|
||||||
|
Scan(&row.ID, &row.TokenHash, &row.UserID, &row.ClientID, &row.Scopes, &row.ExpiresAt, &row.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create refresh token: %w", err)
|
||||||
|
}
|
||||||
|
return &row, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error) {
|
||||||
|
var row models.RefreshTokenRow
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, token_hash, user_id, client_id, scopes, expires_at, created_at
|
||||||
|
FROM refresh_tokens WHERE token_hash = $1
|
||||||
|
`, tokenHash).Scan(&row.ID, &row.TokenHash, &row.UserID, &row.ClientID, &row.Scopes, &row.ExpiresAt, &row.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &row, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := r.db.Exec(ctx, `DELETE FROM refresh_tokens WHERE id = $1`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) RecordUserConsent(
|
||||||
|
ctx context.Context,
|
||||||
|
userID, clientID uuid.UUID,
|
||||||
|
scopes []string,
|
||||||
|
) error {
|
||||||
|
|
||||||
|
scopeJSON, err := json.Marshal(scopes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = r.db.Exec(ctx, `
|
||||||
|
INSERT INTO user_consents (
|
||||||
|
user_id,
|
||||||
|
client_id,
|
||||||
|
scopes,
|
||||||
|
authorized_at,
|
||||||
|
last_used_at,
|
||||||
|
revoked_at
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3, now(), now(), NULL)
|
||||||
|
ON CONFLICT (user_id, client_id)
|
||||||
|
WHERE revoked_at IS NULL
|
||||||
|
DO UPDATE SET
|
||||||
|
scopes = EXCLUDED.scopes,
|
||||||
|
last_used_at = now()
|
||||||
|
`, userID, clientID, scopeJSON)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetUserConsents(
|
||||||
|
ctx context.Context,
|
||||||
|
userID uuid.UUID,
|
||||||
|
) ([]models.UserConsent, error) {
|
||||||
|
|
||||||
|
rows, err := r.db.Query(ctx, `
|
||||||
|
SELECT
|
||||||
|
uc.id,
|
||||||
|
uc.user_id,
|
||||||
|
uc.client_id,
|
||||||
|
oc.client_id AS client_identifier,
|
||||||
|
oc.name AS client_name,
|
||||||
|
uc.scopes,
|
||||||
|
uc.authorized_at,
|
||||||
|
uc.last_used_at,
|
||||||
|
uc.revoked_at
|
||||||
|
FROM user_consents uc
|
||||||
|
JOIN oauth_clients oc ON uc.client_id = oc.id
|
||||||
|
WHERE uc.user_id = $1
|
||||||
|
AND uc.revoked_at IS NULL
|
||||||
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
||||||
|
ORDER BY uc.authorized_at DESC
|
||||||
|
`, userID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var consents []models.UserConsent
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var c models.UserConsent
|
||||||
|
var scopeJSON []byte
|
||||||
|
|
||||||
|
err := rows.Scan(
|
||||||
|
&c.ID,
|
||||||
|
&c.UserID,
|
||||||
|
&c.ClientID,
|
||||||
|
&c.ClientIdentifier,
|
||||||
|
&c.ClientName,
|
||||||
|
&scopeJSON,
|
||||||
|
&c.AuthorizedAt,
|
||||||
|
&c.LastUsedAt,
|
||||||
|
&c.RevokedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(scopeJSON, &c.Scopes); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
consents = append(consents, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return consents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) UpdateConsentLastUsed(
|
||||||
|
ctx context.Context,
|
||||||
|
userID, clientID uuid.UUID,
|
||||||
|
) error {
|
||||||
|
|
||||||
|
_, err := r.db.Exec(ctx, `
|
||||||
|
UPDATE user_consents
|
||||||
|
SET last_used_at = now()
|
||||||
|
WHERE user_id = $1
|
||||||
|
AND client_id = $2
|
||||||
|
AND revoked_at IS NULL
|
||||||
|
AND (expires_at IS NULL OR expires_at > now())
|
||||||
|
`, userID, clientID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) GetUserConsentsByClientID(
|
||||||
|
ctx context.Context,
|
||||||
|
userID uuid.UUID,
|
||||||
|
clientID uuid.UUID,
|
||||||
|
) ([]models.UserConsent, error) {
|
||||||
|
|
||||||
|
rows, err := r.db.Query(ctx, `
|
||||||
|
SELECT
|
||||||
|
uc.id,
|
||||||
|
uc.user_id,
|
||||||
|
uc.client_id,
|
||||||
|
oc.client_id AS client_identifier,
|
||||||
|
oc.name AS client_name,
|
||||||
|
uc.scopes,
|
||||||
|
uc.authorized_at,
|
||||||
|
uc.revoked_at
|
||||||
|
FROM user_consents uc
|
||||||
|
JOIN oauth_clients oc ON uc.client_id = oc.id
|
||||||
|
WHERE uc.user_id = $1
|
||||||
|
AND uc.revoked_at IS NULL
|
||||||
|
AND (uc.expires_at IS NULL OR uc.expires_at > now())
|
||||||
|
AND uo.id = $2
|
||||||
|
ORDER BY uc.authorized_at DESC
|
||||||
|
`, userID, clientID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var consents []models.UserConsent
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var c models.UserConsent
|
||||||
|
var scopeJSON []byte
|
||||||
|
|
||||||
|
err := rows.Scan(
|
||||||
|
&c.ID,
|
||||||
|
&c.UserID,
|
||||||
|
&c.ClientID,
|
||||||
|
&c.ClientIdentifier,
|
||||||
|
&c.ClientName,
|
||||||
|
&scopeJSON,
|
||||||
|
&c.AuthorizedAt,
|
||||||
|
&c.LastUsedAt,
|
||||||
|
&c.RevokedAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(scopeJSON, &c.Scopes); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
consents = append(consents, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return consents, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *OAuthRepository) RevokeConsent(
|
||||||
|
ctx context.Context,
|
||||||
|
userID, clientID uuid.UUID,
|
||||||
|
revokedBy *uuid.UUID,
|
||||||
|
) error {
|
||||||
|
|
||||||
|
tx, err := r.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
_, err = tx.Exec(ctx, `
|
||||||
|
UPDATE user_consents
|
||||||
|
SET revoked_at = now(),
|
||||||
|
revoked_by = $3
|
||||||
|
WHERE user_id = $1
|
||||||
|
AND client_id = $2
|
||||||
|
AND revoked_at IS NULL
|
||||||
|
`, userID, clientID, revokedBy)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tx.Exec(ctx, `
|
||||||
|
DELETE FROM refresh_tokens
|
||||||
|
WHERE user_id = $1
|
||||||
|
AND client_id = $2
|
||||||
|
`, userID, clientID)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package repositories
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserRepository struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserRepository(db *pgxpool.Pool) *UserRepository {
|
||||||
|
return &UserRepository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) IsUserExistsByEmail(ctx context.Context, email string) bool {
|
||||||
|
var exists bool
|
||||||
|
_ = r.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE email = $1)`, email).Scan(&exists)
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) CreateUser(ctx context.Context, user models.User) (*models.User, error) {
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO users (email, password_hash, first_name, second_name, birth_date, sex)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
RETURNING id, created_at, updated_at
|
||||||
|
`, user.Email, user.PasswordHash, user.FirstName, user.SecondName, user.BirthDate, user.Sex).
|
||||||
|
Scan(&user.ID, &user.CreatedAt, &user.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create user: %w", err)
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) UpdateUser(ctx context.Context, user models.User) (*models.User, error) {
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
UPDATE users
|
||||||
|
SET first_name = $1,
|
||||||
|
second_name = $2,
|
||||||
|
birth_date = $3,
|
||||||
|
sex = $4,
|
||||||
|
password_hash = $5,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = $6
|
||||||
|
RETURNING updated_at
|
||||||
|
`, user.FirstName, user.SecondName, user.BirthDate, user.Sex, user.PasswordHash, user.ID).
|
||||||
|
Scan(&user.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("update user: %w", err)
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) DeleteUser(ctx context.Context, id uuid.UUID) error {
|
||||||
|
_, err := r.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
|
||||||
|
var u models.User
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||||
|
FROM users WHERE email = $1
|
||||||
|
`, email).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *UserRepository) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
|
||||||
|
var u models.User
|
||||||
|
err := r.db.QueryRow(ctx, `
|
||||||
|
SELECT id, email, password_hash, first_name, second_name, birth_date, sex, created_at, updated_at
|
||||||
|
FROM users WHERE id = $1
|
||||||
|
`, id).Scan(&u.ID, &u.Email, &u.PasswordHash, &u.FirstName, &u.SecondName, &u.BirthDate, &u.Sex, &u.CreatedAt, &u.UpdatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &u, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenInfo struct {
|
||||||
|
UserID uuid.UUID
|
||||||
|
Scopes []string
|
||||||
|
ClientID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error) {
|
||||||
|
return s.users.GetUserByID(ctx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Register(ctx context.Context, input models.UserRegisterInput) (*models.User, error) {
|
||||||
|
if s.users.IsUserExistsByEmail(ctx, input.Email) {
|
||||||
|
return nil, models.ErrAlreadyExists
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.users.CreateUser(ctx, models.User{
|
||||||
|
Email: input.Email,
|
||||||
|
PasswordHash: string(hash),
|
||||||
|
FirstName: input.FirstName,
|
||||||
|
SecondName: input.SecondName,
|
||||||
|
BirthDate: input.BirthDate,
|
||||||
|
Sex: input.Sex,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RefreshTokens(ctx context.Context, rawToken string) (*TokenPair, error) {
|
||||||
|
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
if time.Now().After(row.ExpiresAt) {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.oauth.GetOAuthClientByID(ctx, row.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
scopes := scopesFromJSON(row.Scopes)
|
||||||
|
if !ScopesAllowed(client.Scopes, scopes) {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.issuePair(ctx, user, client.ID, scopes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ValidateAccessToken(ctx context.Context, token string) (*TokenInfo, error) {
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := s.redis.Get(ctx, accessTokenPrefix+token).Bytes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
var info struct {
|
||||||
|
UserID uuid.UUID `json:"user_id"`
|
||||||
|
Scopes []string `json:"scopes"`
|
||||||
|
ClientID uuid.UUID `json:"client_id"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(data, &info); err != nil {
|
||||||
|
return nil, models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TokenInfo{UserID: info.UserID, Scopes: info.Scopes, ClientID: info.ClientID}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input models.UserUpdateInput) (*models.User, error) {
|
||||||
|
user, err := s.users.GetUserByID(ctx, userID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.FirstName != "" {
|
||||||
|
user.FirstName = input.FirstName
|
||||||
|
}
|
||||||
|
if input.SecondName != "" {
|
||||||
|
user.SecondName = input.SecondName
|
||||||
|
}
|
||||||
|
if input.BirthDate != nil {
|
||||||
|
user.BirthDate = input.BirthDate
|
||||||
|
}
|
||||||
|
if input.Sex != "" {
|
||||||
|
user.Sex = input.Sex
|
||||||
|
}
|
||||||
|
if input.Password != "" {
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
user.PasswordHash = string(hash)
|
||||||
|
}
|
||||||
|
user.UpdatedAt = time.Now()
|
||||||
|
|
||||||
|
return s.users.UpdateUser(ctx, *user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) DeleteProfile(ctx context.Context, userID uuid.UUID, accessToken string) error {
|
||||||
|
if err := s.users.DeleteUser(ctx, userID); err != nil {
|
||||||
|
return models.ErrInternal
|
||||||
|
}
|
||||||
|
_ = s.redis.Del(ctx, accessTokenPrefix+accessToken)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Service) GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error) {
|
||||||
|
return s.oauth.GetUserConsents(ctx, userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) HasUserConsent(ctx context.Context, userId uuid.UUID, clientId uuid.UUID, scopes []string) bool {
|
||||||
|
allConsents, err := s.oauth.GetUserConsentsByClientID(ctx, userId, clientId)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
consents := make(map[string]bool)
|
||||||
|
for _, scopes := range allConsents {
|
||||||
|
for _, scope := range scopes.Scopes {
|
||||||
|
consents[scope] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, scope := range scopes {
|
||||||
|
if !consents[scope] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RevokeConsent(ctx context.Context, userID uuid.UUID, clientID string) error {
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
|
||||||
|
if err != nil {
|
||||||
|
return models.ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.oauth.RevokeConsent(ctx, userID, client.ID, &userID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens, _ := s.redis.SMembers(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID)).Result()
|
||||||
|
for _, token := range tokens {
|
||||||
|
s.redis.Del(ctx, accessTokenPrefix+token)
|
||||||
|
}
|
||||||
|
s.redis.Del(ctx, fmt.Sprintf("user_client_tokens:%s:%s", userID, client.ID))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newOpaqueToken(nBytes int) (string, error) {
|
||||||
|
b := make([]byte, nBytes)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sha256Hex(v string) string {
|
||||||
|
h := sha256.Sum256([]byte(v))
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func pkceVerifyS256(verifier, challenge string) bool {
|
||||||
|
sum := sha256.Sum256([]byte(verifier))
|
||||||
|
got := base64.RawURLEncoding.EncodeToString(sum[:])
|
||||||
|
return subtle.ConstantTimeCompare([]byte(got), []byte(challenge)) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseScopes(scope string) []string {
|
||||||
|
scope = strings.TrimSpace(scope)
|
||||||
|
if scope == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{})
|
||||||
|
var out []string
|
||||||
|
for _, p := range strings.Fields(scope) {
|
||||||
|
if _, dup := seen[p]; !dup {
|
||||||
|
seen[p] = struct{}{}
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func ScopesAllowed(clientScopesJSON json.RawMessage, requested []string) bool {
|
||||||
|
if len(requested) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
allowed := scopesFromJSON(clientScopesJSON)
|
||||||
|
set := make(map[string]struct{}, len(allowed))
|
||||||
|
for _, a := range allowed {
|
||||||
|
set[a] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, r := range requested {
|
||||||
|
if _, ok := set[r]; !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func scopesFromJSON(b json.RawMessage) []string {
|
||||||
|
if len(b) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
_ = json.Unmarshal(b, &out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func redirectURIMatches(redirectURIsJSON json.RawMessage, redirectURI string) bool {
|
||||||
|
var uris []string
|
||||||
|
if err := json.Unmarshal(redirectURIsJSON, &uris); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, u := range uris {
|
||||||
|
if u == redirectURI {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyClientSecret(stored, provided string) bool {
|
||||||
|
if stored == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if provided == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(stored, "$2") {
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(stored), []byte(provided)) == nil
|
||||||
|
}
|
||||||
|
return subtle.ConstantTimeCompare([]byte(stored), []byte(provided)) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashClientSecret(secret string) (string, error) {
|
||||||
|
if secret == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
b, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("hash client secret: %w", err)
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func bcryptCompare(hash, password string) error {
|
||||||
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ScopesContain(tokenScopes []string, required []string) bool {
|
||||||
|
if len(required) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
set := make(map[string]struct{}, len(tokenScopes))
|
||||||
|
for _, s := range tokenScopes {
|
||||||
|
set[s] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, r := range required {
|
||||||
|
if _, ok := set[r]; !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type OAuthSession struct {
|
||||||
|
ClientID string `json:"client_id"`
|
||||||
|
ClientName string `json:"client_name"`
|
||||||
|
RedirectURI string `json:"redirect_uri"`
|
||||||
|
Scopes []string `json:"scopes"`
|
||||||
|
State string `json:"state"`
|
||||||
|
CodeChallenge string `json:"code_challenge"`
|
||||||
|
CodeChallengeMethod string `json:"code_challenge_method"`
|
||||||
|
UserID uuid.UUID `json:"user_id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TokenPair struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
RefreshToken string `json:"refresh_token,omitempty"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int64 `json:"expires_in"`
|
||||||
|
Scope string `json:"scope,omitempty"`
|
||||||
|
User *models.User `json:"user,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreateOAuthSession(
|
||||||
|
ctx context.Context,
|
||||||
|
clientID, redirectURI, scope, state, codeChallenge, codeChallengeMethod string,
|
||||||
|
) (string, error) {
|
||||||
|
if clientID == "" || redirectURI == "" || codeChallenge == "" {
|
||||||
|
return "", ErrInvalidRequest
|
||||||
|
}
|
||||||
|
if codeChallengeMethod != "" && codeChallengeMethod != "S256" {
|
||||||
|
return "", ErrInvalidRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, clientID)
|
||||||
|
if err != nil {
|
||||||
|
return "", ErrUnauthorizedClient
|
||||||
|
}
|
||||||
|
if !redirectURIMatches(client.RedirectURIs, redirectURI) {
|
||||||
|
return "", ErrInvalidRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
scopes := parseScopes(scope)
|
||||||
|
if len(scopes) > 0 && !ScopesAllowed(client.Scopes, scopes) {
|
||||||
|
return "", ErrInvalidRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := newOpaqueToken(24)
|
||||||
|
if err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
sess := OAuthSession{
|
||||||
|
ClientID: client.ClientID,
|
||||||
|
ClientName: client.Name,
|
||||||
|
RedirectURI: redirectURI,
|
||||||
|
Scopes: scopes,
|
||||||
|
State: state,
|
||||||
|
CodeChallenge: codeChallenge,
|
||||||
|
CodeChallengeMethod: "S256",
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.saveSession(ctx, token, &sess); err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetOAuthSession(ctx context.Context, token string) (*OAuthSession, error) {
|
||||||
|
data, err := s.redis.Get(ctx, oauthSessionPrefix+token).Bytes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
var sess OAuthSession
|
||||||
|
if err := json.Unmarshal(data, &sess); err != nil {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
return &sess, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) saveSession(ctx context.Context, token string, sess *OAuthSession) error {
|
||||||
|
data, _ := json.Marshal(sess)
|
||||||
|
return s.redis.Set(ctx, oauthSessionPrefix+token, data, oauthSessionTTL).Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) {
|
||||||
|
sess, err := s.GetOAuthSession(ctx, token)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.users.GetUserByEmail(ctx, email)
|
||||||
|
if err != nil || bcryptCompare(user.PasswordHash, password) != nil {
|
||||||
|
return "", models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
sess.UserID = user.ID
|
||||||
|
if err := s.saveSession(ctx, token, sess); err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
return "", ErrInvalidClient
|
||||||
|
}
|
||||||
|
|
||||||
|
if client.Trusted {
|
||||||
|
return s.SessionApprove(ctx, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||||
|
if hasUserConsents {
|
||||||
|
return s.SessionApprove(ctx, token)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) {
|
||||||
|
info, err := s.ValidateAccessToken(ctx, accessToken)
|
||||||
|
if err != nil {
|
||||||
|
return "", models.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
sess, err := s.GetOAuthSession(ctx, sessionToken)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
sess.UserID = info.UserID
|
||||||
|
if err := s.saveSession(ctx, sessionToken, sess); err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
return "", ErrInvalidClient
|
||||||
|
}
|
||||||
|
if client.Trusted {
|
||||||
|
return s.SessionApprove(ctx, sessionToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||||
|
if hasUserConsents {
|
||||||
|
return s.SessionApprove(ctx, sessionToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) {
|
||||||
|
sess, err := s.GetOAuthSession(ctx, token)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if sess.UserID == uuid.Nil {
|
||||||
|
return "", ErrInvalidGrant
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, sess.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
return "", ErrInvalidClient
|
||||||
|
}
|
||||||
|
|
||||||
|
code, err := s.createAuthCode(ctx, sess.UserID, client.ID, sess.RedirectURI, sess.Scopes, sess.CodeChallenge)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = s.redis.Del(ctx, oauthSessionPrefix+token)
|
||||||
|
s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes)
|
||||||
|
|
||||||
|
redirectURL, _ := url.Parse(sess.RedirectURI)
|
||||||
|
q := redirectURL.Query()
|
||||||
|
q.Set("code", code)
|
||||||
|
if sess.State != "" {
|
||||||
|
q.Set("state", sess.State)
|
||||||
|
}
|
||||||
|
redirectURL.RawQuery = q.Encode()
|
||||||
|
|
||||||
|
return redirectURL.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redirectURI, codeVerifier string) (*TokenPair, error) {
|
||||||
|
if auth.ClientID == "" || code == "" || redirectURI == "" || codeVerifier == "" {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.AuthenticateClient(ctx, auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
row, err := s.oauth.GetAuthorizationCodeByHash(ctx, sha256Hex(code))
|
||||||
|
if err != nil || row.ConsumedAt != nil || time.Now().After(row.ExpiresAt) {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
if row.ClientID != client.ID || row.RedirectURI != redirectURI {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
if !pkceVerifyS256(codeVerifier, row.CodeChallenge) {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.oauth.ConsumeAuthorizationCodeByID(ctx, row.ID); err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||||
|
|
||||||
|
return s.issuePair(ctx, user, client.ID, scopesFromJSON(row.Scopes))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ExchangeRefreshToken(ctx context.Context, auth ClientAuth, rawToken string) (*TokenPair, error) {
|
||||||
|
if auth.ClientID == "" || rawToken == "" {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := s.AuthenticateClient(ctx, auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||||
|
if err != nil || time.Now().After(row.ExpiresAt) || row.ClientID != client.ID {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID)
|
||||||
|
|
||||||
|
user, err := s.users.GetUserByID(ctx, row.UserID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
scopes := scopesFromJSON(row.Scopes)
|
||||||
|
if !ScopesAllowed(client.Scopes, scopes) {
|
||||||
|
return nil, ErrInvalidGrant
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.issuePair(ctx, user, client.ID, scopes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken string) error {
|
||||||
|
client, err := s.AuthenticateClient(ctx, auth)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken))
|
||||||
|
if err != nil || row.ClientID != client.ID {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = s.oauth.DeleteRefreshTokenByID(ctx, row.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) createAuthCode(
|
||||||
|
ctx context.Context,
|
||||||
|
userID, clientID uuid.UUID,
|
||||||
|
redirectURI string,
|
||||||
|
scopes []string,
|
||||||
|
codeChallenge string,
|
||||||
|
) (string, error) {
|
||||||
|
rawCode, err := newOpaqueToken(32)
|
||||||
|
if err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
scopeJSON, _ := json.Marshal(scopes)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
_, err = s.oauth.CreateAuthorizationCode(ctx, models.AuthorizationCodeRow{
|
||||||
|
CodeHash: sha256Hex(rawCode),
|
||||||
|
UserID: userID,
|
||||||
|
ClientID: clientID,
|
||||||
|
RedirectURI: redirectURI,
|
||||||
|
Scopes: scopeJSON,
|
||||||
|
CodeChallenge: codeChallenge,
|
||||||
|
CodeChallengeMethod: "S256",
|
||||||
|
ExpiresAt: now.Add(5 * time.Minute),
|
||||||
|
CreatedAt: now,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return rawCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uuid.UUID, scopes []string) (*TokenPair, error) {
|
||||||
|
accessToken, err := newOpaqueToken(32)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
rawRefresh, err := newOpaqueToken(32)
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
scopeJSON, _ := json.Marshal(scopes)
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
accessData := struct {
|
||||||
|
UserID uuid.UUID `json:"user_id"`
|
||||||
|
Scopes []string `json:"scopes"`
|
||||||
|
ClientID uuid.UUID `json:"client_id"`
|
||||||
|
}{
|
||||||
|
UserID: user.ID,
|
||||||
|
Scopes: scopes,
|
||||||
|
ClientID: clientID,
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(accessData)
|
||||||
|
if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = s.oauth.CreateRefreshToken(ctx, models.RefreshTokenRow{
|
||||||
|
TokenHash: sha256Hex(rawRefresh),
|
||||||
|
UserID: user.ID,
|
||||||
|
ClientID: clientID,
|
||||||
|
Scopes: scopeJSON,
|
||||||
|
ExpiresAt: now.Add(s.tokens.RefreshTTL),
|
||||||
|
CreatedAt: now,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, models.ErrInternal
|
||||||
|
}
|
||||||
|
|
||||||
|
return &TokenPair{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: rawRefresh,
|
||||||
|
TokenType: "Bearer",
|
||||||
|
ExpiresIn: int64(s.tokens.AccessTTL.Seconds()),
|
||||||
|
Scope: strings.Join(scopes, " "),
|
||||||
|
User: user,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/dusiburg/kotosoft-id/internal/models"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidRequest = errors.New("invalid_request")
|
||||||
|
ErrUnauthorizedClient = errors.New("unauthorized_client")
|
||||||
|
ErrInvalidClient = errors.New("invalid_client")
|
||||||
|
ErrInvalidGrant = errors.New("invalid_grant")
|
||||||
|
ErrUnsupportedGrantType = errors.New("unsupported_grant_type")
|
||||||
|
ErrAccessDenied = errors.New("access_denied")
|
||||||
|
)
|
||||||
|
|
||||||
|
type UserRepo interface {
|
||||||
|
CreateUser(ctx context.Context, user models.User) (*models.User, error)
|
||||||
|
UpdateUser(ctx context.Context, user models.User) (*models.User, error)
|
||||||
|
DeleteUser(ctx context.Context, id uuid.UUID) error
|
||||||
|
GetUserByEmail(ctx context.Context, email string) (*models.User, error)
|
||||||
|
GetUserByID(ctx context.Context, id uuid.UUID) (*models.User, error)
|
||||||
|
IsUserExistsByEmail(ctx context.Context, email string) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type OAuthRepo interface {
|
||||||
|
GetOAuthClientByClientID(ctx context.Context, clientID string) (*models.OAuthClient, error)
|
||||||
|
GetOAuthClientByID(ctx context.Context, id uuid.UUID) (*models.OAuthClient, error)
|
||||||
|
CreateAuthorizationCode(ctx context.Context, row models.AuthorizationCodeRow) (*models.AuthorizationCodeRow, error)
|
||||||
|
GetAuthorizationCodeByHash(ctx context.Context, codeHash string) (*models.AuthorizationCodeRow, error)
|
||||||
|
ConsumeAuthorizationCodeByID(ctx context.Context, id uuid.UUID) error
|
||||||
|
CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error)
|
||||||
|
GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error)
|
||||||
|
DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error
|
||||||
|
RecordUserConsent(ctx context.Context, userID, clientID uuid.UUID, scopes []string) error
|
||||||
|
GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error)
|
||||||
|
UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error
|
||||||
|
GetUserConsentsByClientID(ctx context.Context, userID uuid.UUID, clientID uuid.UUID) ([]models.UserConsent, error)
|
||||||
|
RevokeConsent(ctx context.Context, userID, clientID uuid.UUID, revokedBy *uuid.UUID) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type TokenConfig struct {
|
||||||
|
AccessTTL time.Duration
|
||||||
|
RefreshTTL time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type ClientAuth struct {
|
||||||
|
ClientID string
|
||||||
|
ClientSecret string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
users UserRepo
|
||||||
|
oauth OAuthRepo
|
||||||
|
redis *redis.Client
|
||||||
|
tokens TokenConfig
|
||||||
|
basicClient *models.OAuthClient
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(
|
||||||
|
users UserRepo,
|
||||||
|
oauth OAuthRepo,
|
||||||
|
rdb *redis.Client,
|
||||||
|
tokenCfg TokenConfig,
|
||||||
|
basicClient *models.OAuthClient,
|
||||||
|
) *Service {
|
||||||
|
return &Service{
|
||||||
|
users: users,
|
||||||
|
oauth: oauth,
|
||||||
|
redis: rdb,
|
||||||
|
tokens: tokenCfg,
|
||||||
|
basicClient: basicClient,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AuthenticateClient(ctx context.Context, auth ClientAuth) (*models.OAuthClient, error) {
|
||||||
|
client, err := s.oauth.GetOAuthClientByClientID(ctx, auth.ClientID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrInvalidClient
|
||||||
|
}
|
||||||
|
if !verifyClientSecret(client.ClientSecret, auth.ClientSecret) {
|
||||||
|
return nil, ErrInvalidClient
|
||||||
|
}
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
oauthSessionPrefix = "oauth_session:"
|
||||||
|
accessTokenPrefix = "access_token:"
|
||||||
|
oauthSessionTTL = 10 * time.Minute
|
||||||
|
)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS public.users (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
email text NOT NULL UNIQUE,
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
first_name text NOT NULL,
|
||||||
|
second_name text NOT NULL,
|
||||||
|
birth_date date,
|
||||||
|
sex text NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.oauth_clients (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
client_id text NOT NULL UNIQUE,
|
||||||
|
client_secret text NOT NULL,
|
||||||
|
name text NOT NULL,
|
||||||
|
redirect_uris JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
grant_types JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
scopes JSONB DEFAULT '[]'::jsonb,
|
||||||
|
is_active boolean DEFAULT TRUE,
|
||||||
|
trusted boolean DEFAULT FALSE,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.authorization_codes (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
code_hash text NOT NULL UNIQUE,
|
||||||
|
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||||
|
client_id uuid NOT NULL REFERENCES public.oauth_clients(id) ON DELETE CASCADE,
|
||||||
|
redirect_uri text NOT NULL,
|
||||||
|
scopes jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
code_challenge text NOT NULL,
|
||||||
|
code_challenge_method text NOT NULL DEFAULT 'S256',
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
consumed_at timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_authorization_codes_code_hash ON public.authorization_codes (code_hash);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_authorization_codes_expires_at ON public.authorization_codes (expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_authorization_codes_consumed_at ON public.authorization_codes (consumed_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.refresh_tokens (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
token_hash text NOT NULL UNIQUE,
|
||||||
|
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||||
|
client_id uuid NOT NULL REFERENCES public.oauth_clients(id) ON DELETE CASCADE,
|
||||||
|
scopes jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_token_hash ON public.refresh_tokens (token_hash);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires_at ON public.refresh_tokens (expires_at);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_authorization_codes_user_id
|
||||||
|
ON public.authorization_codes(user_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_authorization_codes_client_id
|
||||||
|
ON public.authorization_codes(client_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user_id
|
||||||
|
ON public.refresh_tokens(user_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_client_id
|
||||||
|
ON public.refresh_tokens(client_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS public.user_consents (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id uuid NOT NULL REFERENCES public.users(id) ON DELETE CASCADE,
|
||||||
|
client_id uuid NOT NULL REFERENCES public.oauth_clients(id) ON DELETE CASCADE,
|
||||||
|
scopes jsonb NOT NULL,
|
||||||
|
authorized_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
last_used_at timestamptz,
|
||||||
|
expires_at timestamptz,
|
||||||
|
revoked_at timestamptz,
|
||||||
|
revoked_by uuid REFERENCES public.users(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS unique_active_consent
|
||||||
|
ON public.user_consents (user_id, client_id)
|
||||||
|
WHERE revoked_at IS NULL;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_consents_user_id ON public.user_consents(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_consents_client_id ON public.user_consents(client_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_consents_revoked ON public.user_consents(revoked_at) WHERE revoked_at IS NOT NULL;
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
"use server"
|
||||||
|
|
||||||
|
import type { User } from "@/types";
|
||||||
|
import { getTranslations } from "next-intl/server";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { cookieConfig } from "@/lib/cookie-config";
|
||||||
|
|
||||||
|
let refreshPromise: Promise<boolean> | null = null;
|
||||||
|
|
||||||
|
export async function serverBasicAuth() {
|
||||||
|
return (
|
||||||
|
"Basic " +
|
||||||
|
Buffer.from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`).toString("base64")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setTokens(accessToken: string, refreshToken: string, ttl: number) {
|
||||||
|
const store = await cookies();
|
||||||
|
store.set("access_token", accessToken, { ...cookieConfig, path: "/", maxAge: ttl });
|
||||||
|
store.set("refresh_token", refreshToken, { ...cookieConfig, path: "/", maxAge: ttl * 7 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearTokens() {
|
||||||
|
const store = await cookies();
|
||||||
|
store.delete("access_token");
|
||||||
|
store.delete("refresh_token");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function tryRefresh(): Promise<boolean> {
|
||||||
|
if (refreshPromise) return refreshPromise;
|
||||||
|
|
||||||
|
refreshPromise = (async () => {
|
||||||
|
const store = await cookies();
|
||||||
|
const refreshToken = store.get("refresh_token")?.value;
|
||||||
|
if (!refreshToken) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
Authorization: await serverBasicAuth(),
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: refreshToken,
|
||||||
|
}).toString(),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) return false;
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
await setTokens(data.access_token, data.refresh_token, data.expires_in);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
refreshPromise = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function SessionLogin(
|
||||||
|
session: string,
|
||||||
|
email: string,
|
||||||
|
password: string,
|
||||||
|
): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
|
||||||
|
const t = await getTranslations("errors");
|
||||||
|
|
||||||
|
if (!session || !email || !password) {
|
||||||
|
return { success: false, message: t("invalidCredentialsError") };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/login`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ session, email, password }),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (data.error === "invalid_grant") return { success: false, expired: true };
|
||||||
|
return { success: false, message: t("invalidCredentialsError") };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.redirect_url) return { success: true, redirectURL: data.redirect_url };
|
||||||
|
return { success: true };
|
||||||
|
} catch {
|
||||||
|
return { success: false, message: t("serverError") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GetUser(): Promise<User | null> {
|
||||||
|
const store = await cookies();
|
||||||
|
const accessToken = store.get("access_token")?.value;
|
||||||
|
if (!accessToken) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me`, {
|
||||||
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await tryRefresh();
|
||||||
|
if (!refreshed) {
|
||||||
|
await clearTokens();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return GetUser();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return (await response.json()) as User;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function UpdateUser(first_name: string, second_name: string, birth_date: string): Promise<User | null> {
|
||||||
|
const store = await cookies();
|
||||||
|
const accessToken = store.get("access_token")?.value;
|
||||||
|
if (!accessToken) return null;
|
||||||
|
|
||||||
|
let formattedDate: string | undefined;
|
||||||
|
if (birth_date) {
|
||||||
|
const datePart = birth_date.split("T")[0];
|
||||||
|
if (datePart) formattedDate = `${datePart}T00:00:00Z`;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
first_name,
|
||||||
|
second_name,
|
||||||
|
...(formattedDate && { birth_date: formattedDate }),
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 401) {
|
||||||
|
const refreshed = await tryRefresh();
|
||||||
|
if (!refreshed) {
|
||||||
|
await clearTokens();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return UpdateUser(first_name, second_name, birth_date);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return (await response.json()) as User;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function Register(email: string, password: string, first_name: string, second_name: string, sex: string): Promise<{ success: boolean; redirectURL?: string; expired?: boolean; message?: string }> {
|
||||||
|
const t = await getTranslations("errors");
|
||||||
|
if (!email || !password) return { success: false, message: t("allFieldsRequired") }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/api/v1/auth/register`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: await serverBasicAuth(),
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
first_name,
|
||||||
|
second_name,
|
||||||
|
sex
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status == 409) return { success: false, message: t("emailAlreadyExistsError") };
|
||||||
|
return { success: false, message: t("serverError") };
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
} catch {
|
||||||
|
return { success: false, message: t("serverError") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function Logout() {
|
||||||
|
await clearTokens();
|
||||||
|
redirect("/login");
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"use server"
|
||||||
|
|
||||||
|
import { Consent } from "@/types"
|
||||||
|
import { cookies } from "next/headers"
|
||||||
|
|
||||||
|
export async function getConsents() {
|
||||||
|
const store = await cookies()
|
||||||
|
const accessToken = store.get("access_token")?.value
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/consents`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) return []
|
||||||
|
|
||||||
|
var consents = await response.json() as Consent[];
|
||||||
|
consents.forEach((consent: Consent) => {
|
||||||
|
if (consent.client_id == process.env.CLIENT_ID) {
|
||||||
|
consent.isRevokable == false
|
||||||
|
} else {
|
||||||
|
consent.isRevokable == true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return consents
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeConsent(clientId: string) {
|
||||||
|
const store = await cookies()
|
||||||
|
const accessToken = store.get("access_token")?.value
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/applications/${clientId}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"use server"
|
||||||
|
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
|
export async function changeLanguage(language: string) {
|
||||||
|
const store = await cookies();
|
||||||
|
|
||||||
|
store.set("locale", language);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"use server"
|
||||||
|
|
||||||
|
import type { OAuthSession } from "@/types";
|
||||||
|
|
||||||
|
export async function getSession(token: string): Promise<OAuthSession | null> {
|
||||||
|
if (!token) return null;
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/${token}`,
|
||||||
|
{ cache: "no-store" }
|
||||||
|
);
|
||||||
|
if (!response.ok) return null;
|
||||||
|
return await response.json() as OAuthSession;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function Approve(session: string, allow: boolean): Promise<string | null> {
|
||||||
|
if (!session) return null;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/approve`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ session, allow }),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
if (!response.ok) return null;
|
||||||
|
const data = await response.json();
|
||||||
|
return data.redirect_url ?? null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { pkceConfig } from "@/lib/cookie-config";
|
||||||
|
import crypto from "crypto";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const verifier = crypto.randomBytes(32).toString("base64url");
|
||||||
|
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
|
||||||
|
const state = crypto.randomBytes(16).toString("hex");
|
||||||
|
|
||||||
|
const store = await cookies();
|
||||||
|
store.set("pkce_verifier", verifier, pkceConfig);
|
||||||
|
store.set("oauth_state", state, { ...pkceConfig, path: "/api/callback" });
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
client_id: process.env.CLIENT_ID!,
|
||||||
|
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||||
|
scope: "profile:read profile:edit profile:consent:read",
|
||||||
|
response_type: "code",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
state,
|
||||||
|
});
|
||||||
|
|
||||||
|
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params.toString()}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { cookies } from "next/headers";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { setTokens, serverBasicAuth } from "@/actions/auth";
|
||||||
|
import { type NextRequest } from "next/server";
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const code = request.nextUrl.searchParams.get("code");
|
||||||
|
const returnedState = request.nextUrl.searchParams.get("state");
|
||||||
|
if (!code) redirect("/callback/error");
|
||||||
|
|
||||||
|
const store = await cookies();
|
||||||
|
const codeVerifier = store.get("pkce_verifier")?.value;
|
||||||
|
const savedState = store.get("oauth_state")?.value;
|
||||||
|
|
||||||
|
if (!codeVerifier || returnedState !== savedState) redirect("/callback/error");
|
||||||
|
|
||||||
|
store.delete("pkce_verifier");
|
||||||
|
store.delete("oauth_state");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
Authorization: await serverBasicAuth(),
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code,
|
||||||
|
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||||
|
code_verifier: codeVerifier,
|
||||||
|
}).toString(),
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) redirect("/callback/error");
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
await setTokens(data.access_token, data.refresh_token, data.expires_in);
|
||||||
|
} catch {
|
||||||
|
redirect("/callback/error");
|
||||||
|
}
|
||||||
|
|
||||||
|
redirect("/");
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"use client"
|
||||||
|
import Header from "@/components/header";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useSearchParams } from "next/navigation";
|
||||||
|
import { getSession, Approve } from "@/actions/oauth";
|
||||||
|
import { Check } from "lucide-react";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
interface Session {
|
||||||
|
client_name: string;
|
||||||
|
scopes: string[];
|
||||||
|
redirect_uri: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ConsentPage() {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const sessionToken = searchParams.get("session") || "";
|
||||||
|
const t = useTranslations("ConsentPage");
|
||||||
|
|
||||||
|
const [session, setSession] = useState<Session | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
getSession(sessionToken)
|
||||||
|
.then(data => {
|
||||||
|
if (!data) throw new Error();
|
||||||
|
setSession(data);
|
||||||
|
})
|
||||||
|
.catch(() => setError(t("invalidSession")));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleDecision = async (allow: boolean) => {
|
||||||
|
setIsSubmitting(true);
|
||||||
|
if (allow) {
|
||||||
|
const result = await Approve(sessionToken, allow);
|
||||||
|
if (result) {
|
||||||
|
window.location.href = result;
|
||||||
|
} else {
|
||||||
|
setError(t("invalidSession"));
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
window.location.href = session?.redirect_uri || "/";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Header />
|
||||||
|
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
|
||||||
|
<div className="w-full max-w-sm flex flex-col gap-6">
|
||||||
|
{error ? (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<p className="text-destructive">{error}</p>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Link href={session?.redirect_uri || "/"}><Button>{t("toApp")}</Button></Link>
|
||||||
|
<Link href="/"><Button variant="outline">{t("toHome")}</Button></Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : !session ? (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Skeleton className="w-64 h-5" />
|
||||||
|
<Skeleton className="w-86 h-5" />
|
||||||
|
<Skeleton className="w-64 h-5" />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2 my-4">
|
||||||
|
<Skeleton className="w-86 h-4" />
|
||||||
|
<Skeleton className="w-86 h-4" />
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Skeleton className="w-17 h-9" />
|
||||||
|
<Skeleton className="w-17 h-9" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<h1 className="text-xl">{t("title", { service: session.client_name })}</h1>
|
||||||
|
<h2 className="text-lg">{t("subtitle", { service: session.client_name })}</h2>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
{session.scopes.map(scope => (
|
||||||
|
<div key={scope} className="flex flex-row gap-3 items-center">
|
||||||
|
<Check size={18} />
|
||||||
|
<h3 className="text-base">{t(`scopes.${scope}`, { defaultValue: scope })}</h3>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button onClick={() => handleDecision(true)} disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner />}{t("allow")}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => handleDecision(false)} disabled={isSubmitting} variant="outline">
|
||||||
|
{t("deny")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,124 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
@import "tw-animate-css";
|
||||||
|
@import "shadcn/tailwind.css";
|
||||||
|
|
||||||
|
@custom-variant dark (&:is(.dark *));
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
|
--color-ring: var(--ring);
|
||||||
|
--color-input: var(--input);
|
||||||
|
--color-border: var(--border);
|
||||||
|
--color-destructive: var(--destructive);
|
||||||
|
--color-accent-foreground: var(--accent-foreground);
|
||||||
|
--color-accent: var(--accent);
|
||||||
|
--color-muted-foreground: var(--muted-foreground);
|
||||||
|
--color-muted: var(--muted);
|
||||||
|
--color-secondary-foreground: var(--secondary-foreground);
|
||||||
|
--color-secondary: var(--secondary);
|
||||||
|
--color-primary-foreground: var(--primary-foreground);
|
||||||
|
--color-primary: var(--primary);
|
||||||
|
--color-popover-foreground: var(--popover-foreground);
|
||||||
|
--color-popover: var(--popover);
|
||||||
|
--color-card-foreground: var(--card-foreground);
|
||||||
|
--color-card: var(--card);
|
||||||
|
--radius-sm: calc(var(--radius) - 4px);
|
||||||
|
--radius-md: calc(var(--radius) - 2px);
|
||||||
|
--radius-lg: var(--radius);
|
||||||
|
--radius-xl: calc(var(--radius) + 4px);
|
||||||
|
--radius-2xl: calc(var(--radius) + 8px);
|
||||||
|
--radius-3xl: calc(var(--radius) + 12px);
|
||||||
|
--radius-4xl: calc(var(--radius) + 16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--radius: 0.8rem;
|
||||||
|
--background: oklch(1 0 0);
|
||||||
|
--foreground: oklch(0.145 0 0);
|
||||||
|
--card: oklch(1 0 0);
|
||||||
|
--card-foreground: oklch(0.145 0 0);
|
||||||
|
--popover: oklch(1 0 0);
|
||||||
|
--popover-foreground: oklch(0.145 0 0);
|
||||||
|
--primary: oklch(0.205 0 0);
|
||||||
|
--primary-foreground: oklch(0.985 0 0);
|
||||||
|
--secondary: oklch(0.97 0 0);
|
||||||
|
--secondary-foreground: oklch(0.205 0 0);
|
||||||
|
--muted: oklch(0.97 0 0);
|
||||||
|
--muted-foreground: oklch(0.556 0 0);
|
||||||
|
--accent: oklch(0.97 0 0);
|
||||||
|
--accent-foreground: oklch(0.205 0 0);
|
||||||
|
--destructive: oklch(0.577 0.245 27.325);
|
||||||
|
--border: oklch(0.922 0 0);
|
||||||
|
--input: oklch(0.922 0 0);
|
||||||
|
--ring: oklch(0.708 0 0);
|
||||||
|
--chart-1: oklch(0.646 0.222 41.116);
|
||||||
|
--chart-2: oklch(0.6 0.118 184.704);
|
||||||
|
--chart-3: oklch(0.398 0.07 227.392);
|
||||||
|
--chart-4: oklch(0.828 0.189 84.429);
|
||||||
|
--chart-5: oklch(0.769 0.188 70.08);
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.145 0 0);
|
||||||
|
--sidebar-primary: oklch(0.205 0 0);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.97 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||||
|
--sidebar-border: oklch(0.922 0 0);
|
||||||
|
--sidebar-ring: oklch(0.708 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--background: oklch(0.145 0 0);
|
||||||
|
--foreground: oklch(0.985 0 0);
|
||||||
|
--card: oklch(0.205 0 0);
|
||||||
|
--card-foreground: oklch(0.985 0 0);
|
||||||
|
--popover: oklch(0.205 0 0);
|
||||||
|
--popover-foreground: oklch(0.985 0 0);
|
||||||
|
--primary: oklch(0.922 0 0);
|
||||||
|
--primary-foreground: oklch(0.205 0 0);
|
||||||
|
--secondary: oklch(0.269 0 0);
|
||||||
|
--secondary-foreground: oklch(0.985 0 0);
|
||||||
|
--muted: oklch(0.269 0 0);
|
||||||
|
--muted-foreground: oklch(0.708 0 0);
|
||||||
|
--accent: oklch(0.269 0 0);
|
||||||
|
--accent-foreground: oklch(0.985 0 0);
|
||||||
|
--destructive: oklch(0.704 0.191 22.216);
|
||||||
|
--border: oklch(1 0 0 / 10%);
|
||||||
|
--input: oklch(1 0 0 / 15%);
|
||||||
|
--ring: oklch(0.556 0 0);
|
||||||
|
--chart-1: oklch(0.488 0.243 264.376);
|
||||||
|
--chart-2: oklch(0.696 0.17 162.48);
|
||||||
|
--chart-3: oklch(0.769 0.188 70.08);
|
||||||
|
--chart-4: oklch(0.627 0.265 303.9);
|
||||||
|
--chart-5: oklch(0.645 0.246 16.439);
|
||||||
|
--sidebar: oklch(0.205 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.269 0 0);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.556 0 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border outline-ring/50;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
@apply bg-background text-foreground;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import { Golos_Text } from "next/font/google";
|
||||||
|
import "./globals.css";
|
||||||
|
import { NextIntlClientProvider } from "next-intl";
|
||||||
|
import { ThemeProvider } from "@/components/themeProvider";
|
||||||
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
|
|
||||||
|
const golosText = Golos_Text({
|
||||||
|
variable: "--font-geist-sans",
|
||||||
|
weight: ["500"],
|
||||||
|
subsets: ["latin", "cyrillic"],
|
||||||
|
});
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Kotosoft ID",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: Readonly<{
|
||||||
|
children: React.ReactNode;
|
||||||
|
}>) {
|
||||||
|
return (
|
||||||
|
<html lang="en" suppressHydrationWarning>
|
||||||
|
<body className={`${golosText.className} antialiased selection:bg-black/10 dark:selection:bg-blue-300/20`}>
|
||||||
|
<NextIntlClientProvider>
|
||||||
|
<ThemeProvider
|
||||||
|
attribute="class"
|
||||||
|
defaultTheme="system"
|
||||||
|
enableSystem
|
||||||
|
disableTransitionOnChange
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</ThemeProvider>
|
||||||
|
<Toaster richColors />
|
||||||
|
</NextIntlClientProvider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { SessionLogin } from "@/actions/auth";
|
||||||
|
import Header from "@/components/header";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useForm, SubmitHandler } from "react-hook-form";
|
||||||
|
import { useSearchParams, useRouter } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const router = useRouter();
|
||||||
|
const session = searchParams.get("session");
|
||||||
|
const t = useTranslations("LoginPage");
|
||||||
|
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormData>();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!session) {
|
||||||
|
window.location.href = "/api/auth/initiate";
|
||||||
|
}
|
||||||
|
}, [session]);
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const result = await SessionLogin(session!, data.email, data.password);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
if (result.expired) {
|
||||||
|
window.location.href = "/api/auth/initiate";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setError(result.message ?? null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.redirectURL) {
|
||||||
|
window.location.href = result.redirectURL;
|
||||||
|
} else {
|
||||||
|
router.push(`/consent?session=${session}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!session) return (
|
||||||
|
<div className="w-full min-h-svh flex items-center justify-center">
|
||||||
|
<Spinner className="size-6" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Header />
|
||||||
|
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
|
||||||
|
<div className="w-full max-w-sm flex flex-col gap-6">
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<FieldGroup>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
<h1 className="text-xl text-muted-foreground">{t("subtitle")}</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.email}>
|
||||||
|
<FieldLabel htmlFor="email">{t("email.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.email}
|
||||||
|
{...register("email", {
|
||||||
|
required: t("required"),
|
||||||
|
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t("email.invalid") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.email && <FieldError>{errors.email.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.password}>
|
||||||
|
<FieldLabel htmlFor="password">{t("password.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.password}
|
||||||
|
{...register("password", {
|
||||||
|
required: t("required"),
|
||||||
|
minLength: { value: 8, message: t("password.minLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.password && <FieldError>{errors.password.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner />}
|
||||||
|
{t("login")}
|
||||||
|
</Button>
|
||||||
|
{error && <FieldError className="text-center">{error}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
<FieldDescription className="px-6 text-center">
|
||||||
|
{t.rich("noAccountNote", {
|
||||||
|
register: (chunks) => <Link href="/register">{chunks}</Link>
|
||||||
|
})}
|
||||||
|
</FieldDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import Header from "@/components/header";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import type { Consent, User } from "@/types";
|
||||||
|
import { AppWindowMacIcon, BriefcaseBusinessIcon, LogOutIcon, UserIcon } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Logout } from "@/actions/auth";
|
||||||
|
import Profile from "./items/profile";
|
||||||
|
import Applications from "./items/applications";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
userData: User | null;
|
||||||
|
consentsData: Consent[] | [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function MeClient({ userData, consentsData }: Props) {
|
||||||
|
const t = useTranslations("MePage");
|
||||||
|
|
||||||
|
const [user, setUser] = useState(userData);
|
||||||
|
const [consents, setConsents] = useState(consentsData)
|
||||||
|
const [selectedItem, setSelectedItem] = useState(0);
|
||||||
|
|
||||||
|
const items = [
|
||||||
|
{"name": t("items.profile.title"), "icon": <UserIcon />, "component": <Profile user={user} setUser={setUser} />},
|
||||||
|
{"name": t("items.applications.title"), "icon": <AppWindowMacIcon />, "component": <Applications consents={consents} setConsents={setConsents} />},
|
||||||
|
{"name": t("items.positions.title"), "icon": <BriefcaseBusinessIcon />},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Header />
|
||||||
|
<div className="bg-background flex min-h-svh flex-col gap-6">
|
||||||
|
<div className="px-8 lg:px-16 pt-30 pb-16">
|
||||||
|
{!user ? (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Skeleton className="w-64 h-5" />
|
||||||
|
<Skeleton className="w-52 h-4" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col lg:flex-row gap-12">
|
||||||
|
<div className="flex flex-col gap-8">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<h2 className="text-lg">
|
||||||
|
{user.first_name} {user.second_name}
|
||||||
|
</h2>
|
||||||
|
<p className="text-muted-foreground text-base">{user.email}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-0.5 lg:w-64">
|
||||||
|
{
|
||||||
|
items.map((item, index) => (
|
||||||
|
<Button variant="ghost" className={`justify-start -mx-4 ${selectedItem == index && "bg-muted"}`} key={index} onClick={() => setSelectedItem(index)}>{item.icon}<h3 className="text-sm">{item.name}</h3></Button>
|
||||||
|
))
|
||||||
|
}
|
||||||
|
<Button variant="ghost" className="justify-start -mx-4" onClick={async () => Logout()}><LogOutIcon /><h3 className="text-sm">{t("items.logout")}</h3></Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{items[selectedItem].component}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useLocale, useTranslations } from "next-intl";
|
||||||
|
import type { Consent } from "@/types";
|
||||||
|
import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item"
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { localeMap } from "@/types";
|
||||||
|
import { enUS } from "date-fns/locale";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
consents: Consent[] | [];
|
||||||
|
setConsents: (consents: Consent[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Applications({ consents, setConsents }: Props) {
|
||||||
|
const t = useTranslations("MePage.items.applications");
|
||||||
|
|
||||||
|
const locale = useLocale();
|
||||||
|
const dateLocale = localeMap[locale as keyof typeof localeMap] ?? enUS;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="w-full lg:max-w-sm flex flex-col gap-4">
|
||||||
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{consents.map((consent) => (
|
||||||
|
<Item key={consent.client_id}>
|
||||||
|
<ItemContent>
|
||||||
|
<ItemTitle>{consent.client_name}</ItemTitle>
|
||||||
|
<ItemDescription>{t("authorized")} {format(consent.authorized_at, "PPP", { locale: dateLocale }) }</ItemDescription>
|
||||||
|
</ItemContent>
|
||||||
|
<ItemActions>
|
||||||
|
<Button disabled={!consent.isRevokable}>{t("revoke")}</Button>
|
||||||
|
</ItemActions>
|
||||||
|
</Item>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useForm, Controller, SubmitHandler } from "react-hook-form";
|
||||||
|
import type { User } from "@/types";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { BirthdatePicker } from "@/components/ui/birthdate-picker";
|
||||||
|
import { UpdateUser } from "@/actions/auth";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
user: User | null;
|
||||||
|
setUser: (user: User) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
first_name: string;
|
||||||
|
second_name: string;
|
||||||
|
birth_date: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Profile({ user, setUser }: Props) {
|
||||||
|
const t = useTranslations("MePage.items.profile");
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||||
|
defaultValues: {
|
||||||
|
first_name: user?.first_name,
|
||||||
|
second_name: user?.second_name,
|
||||||
|
birth_date: user?.birth_date ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await UpdateUser(data.first_name, data.second_name, data.birth_date);
|
||||||
|
|
||||||
|
if (response == null) setError(t("form.updateError"))
|
||||||
|
else setUser(response)
|
||||||
|
} catch (error) {
|
||||||
|
setError(t("form.updateError"))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="w-full lg:max-w-sm flex flex-col gap-4">
|
||||||
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!errors.first_name}>
|
||||||
|
<FieldLabel htmlFor="first_name">{t("form.firstName.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="first_name"
|
||||||
|
type="text"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.first_name}
|
||||||
|
{...register("first_name", {
|
||||||
|
required: t("form.required"),
|
||||||
|
minLength: { value: 2, message: t("form.firstName.minLength") },
|
||||||
|
maxLength: { value: 64, message: t("form.firstName.maxLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.first_name && <FieldError>{errors.first_name.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.second_name}>
|
||||||
|
<FieldLabel htmlFor="second_name">{t("form.secondName.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="second_name"
|
||||||
|
type="text"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.second_name}
|
||||||
|
{...register("second_name", {
|
||||||
|
required: t("form.required"),
|
||||||
|
minLength: { value: 2, message: t("form.secondName.minLength") },
|
||||||
|
maxLength: { value: 64, message: t("form.secondName.maxLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.second_name && <FieldError>{errors.second_name.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.birth_date}>
|
||||||
|
<FieldLabel htmlFor="birth_date">{t("form.birthdate.title")}</FieldLabel>
|
||||||
|
<Controller
|
||||||
|
name="birth_date"
|
||||||
|
control={control}
|
||||||
|
render={({ field }) => (
|
||||||
|
<BirthdatePicker
|
||||||
|
value={field.value}
|
||||||
|
onChange={field.onChange}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.birth_date}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{errors.birth_date && <FieldError>{errors.birth_date.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner />}
|
||||||
|
{t("form.save")}
|
||||||
|
</Button>
|
||||||
|
{error && <FieldError className="text-center">{error}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { GetUser } from "@/actions/auth";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import MeComponent from "./component";
|
||||||
|
import { getConsents } from "@/actions/consents";
|
||||||
|
|
||||||
|
export default async function Me() {
|
||||||
|
const user = await GetUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
redirect("/api/auth/initiate");
|
||||||
|
}
|
||||||
|
|
||||||
|
var consents = await getConsents();
|
||||||
|
|
||||||
|
return <MeComponent userData={user} consentsData={consents} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { getSession } from "@/actions/oauth";
|
||||||
|
import { isRedirectError } from "next/dist/client/components/redirect-error";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
export default async function OAuthPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const session = (await searchParams).session as string | undefined;
|
||||||
|
if (!session) redirect("/oauth/error");
|
||||||
|
|
||||||
|
const data = await getSession(session);
|
||||||
|
if (!data) redirect("/oauth/error");
|
||||||
|
|
||||||
|
const isAuthenticated =
|
||||||
|
data.user_id && data.user_id !== "00000000-0000-0000-0000-000000000000";
|
||||||
|
|
||||||
|
redirect(isAuthenticated ? `/consent?session=${session}` : `/login?session=${session}`);
|
||||||
|
} catch (error) {
|
||||||
|
if (isRedirectError(error)) throw error;
|
||||||
|
console.error("OAuth page error:", error);
|
||||||
|
redirect("/oauth/error");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
export default function Home() {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Register } from "@/actions/auth";
|
||||||
|
import Header from "@/components/header";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm, SubmitHandler, Controller } from "react-hook-form";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Sex } from "@/types";
|
||||||
|
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
import { ArrowLeft, ArrowRight, Check } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
interface FormData {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
first_name: string;
|
||||||
|
second_name: string;
|
||||||
|
sex: Sex;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RegisterPage() {
|
||||||
|
const router = useRouter();
|
||||||
|
const t = useTranslations("RegisterPage");
|
||||||
|
|
||||||
|
const [step, setStep] = useState<number>(0);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const { register, handleSubmit, control, formState: { errors, isSubmitting } } = useForm<FormData>();
|
||||||
|
|
||||||
|
const onSubmit: SubmitHandler<FormData> = async (data) => {
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
const result = await Register(data.email, data.password, data.first_name, data.second_name, data.sex);
|
||||||
|
if (!result.success) {
|
||||||
|
setError(result.message ?? null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
toast(t("registeredSuccessfully"), { icon: <Check size={16} /> })
|
||||||
|
router.push(`/login`);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Header />
|
||||||
|
<div className="bg-background flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
|
||||||
|
<div className="w-full max-w-sm flex flex-col gap-6">
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<FieldGroup>
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<h1 className="text-xl">{t("title")}</h1>
|
||||||
|
<h2 className="text-lg text-muted-foreground leading-6">{t("subtitle")}</h2>
|
||||||
|
</div>
|
||||||
|
{ step == 0 ? (
|
||||||
|
<>
|
||||||
|
<Field data-invalid={!!errors.email}>
|
||||||
|
<FieldLabel htmlFor="email">{t("email.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.email}
|
||||||
|
{...register("email", {
|
||||||
|
required: t("required"),
|
||||||
|
pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: t("email.invalid") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.email && <FieldError>{errors.email.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.password}>
|
||||||
|
<FieldLabel htmlFor="password">{t("password.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.password}
|
||||||
|
{...register("password", {
|
||||||
|
required: t("required"),
|
||||||
|
minLength: { value: 8, message: t("password.minLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.password && <FieldError>{errors.password.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<Button onClick={(e) => setStep(1)} variant="default" disabled={isSubmitting}>
|
||||||
|
{t("next")}
|
||||||
|
<ArrowRight />
|
||||||
|
</Button>
|
||||||
|
</Field>
|
||||||
|
</>) : (
|
||||||
|
<>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<Field data-invalid={!!errors.first_name}>
|
||||||
|
<FieldLabel htmlFor="first_name">{t("firstName.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="first_name"
|
||||||
|
type="text"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.first_name}
|
||||||
|
{...register("first_name", {
|
||||||
|
required: t("required"),
|
||||||
|
minLength: { value: 2, message: t("firstName.minLength") },
|
||||||
|
maxLength: { value: 64, message: t("firstName.maxLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.first_name && <FieldError>{errors.first_name.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.second_name}>
|
||||||
|
<FieldLabel htmlFor="second_name">{t("secondName.title")}</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="second_name"
|
||||||
|
type="text"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
aria-invalid={!!errors.second_name}
|
||||||
|
{...register("second_name", {
|
||||||
|
required: t("required"),
|
||||||
|
minLength: { value: 2, message: t("secondName.minLength") },
|
||||||
|
maxLength: { value: 64, message: t("secondName.maxLength") },
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
{errors.second_name && <FieldError>{errors.second_name.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Field data-invalid={!!errors.sex}>
|
||||||
|
<FieldLabel htmlFor="sex">{t("sex.title")}</FieldLabel>
|
||||||
|
<Controller
|
||||||
|
name="sex"
|
||||||
|
control={control}
|
||||||
|
rules={{
|
||||||
|
required: t("required"),
|
||||||
|
}}
|
||||||
|
render={({ field }) => (
|
||||||
|
<Select
|
||||||
|
disabled={isSubmitting}
|
||||||
|
value={field.value}
|
||||||
|
onValueChange={field.onChange}
|
||||||
|
>
|
||||||
|
<SelectTrigger aria-invalid={!!errors.sex}>
|
||||||
|
<SelectValue placeholder={t("sex.select")} />
|
||||||
|
</SelectTrigger>
|
||||||
|
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem value="MALE">{t("sex.male")}</SelectItem>
|
||||||
|
<SelectItem value="FEMALE">{t("sex.female")}</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{errors.sex && <FieldError>{errors.sex.message}</FieldError>}
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-4">
|
||||||
|
<Field className="col-span-1">
|
||||||
|
<Button onClick={(e) => {e.preventDefault(); setStep(0)}} variant="outline" disabled={isSubmitting}>
|
||||||
|
<ArrowLeft />
|
||||||
|
{t("back")}
|
||||||
|
</Button>
|
||||||
|
</Field>
|
||||||
|
<Field className="col-span-2">
|
||||||
|
<Button type="submit" disabled={isSubmitting}>
|
||||||
|
{isSubmitting && <Spinner />}
|
||||||
|
{t("register")}
|
||||||
|
</Button>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
{error && <FieldError className="text-center">{error}</FieldError>}
|
||||||
|
</>)
|
||||||
|
}
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
<FieldDescription className="px-6 text-center">
|
||||||
|
{t.rich("hasAccountNote", {
|
||||||
|
login: (chunks) => <Link href="/login">{chunks}</Link>
|
||||||
|
})}
|
||||||
|
</FieldDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://ui.shadcn.com/schema.json",
|
||||||
|
"style": "radix-nova",
|
||||||
|
"rsc": true,
|
||||||
|
"tsx": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "app/globals.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"rtl": false,
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"hooks": "@/hooks"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { ThemeToggler } from "./themeToggler";
|
||||||
|
import { LanguageToggler } from "./languageToggler";
|
||||||
|
|
||||||
|
export default function Header() {
|
||||||
|
return (
|
||||||
|
<header className="fixed top-0 left-0 right-0 flex flex-row items-center justify-between gap-6 px-3 py-2.5">
|
||||||
|
<div />
|
||||||
|
<div className="flex flex-row items-center gap-3">
|
||||||
|
<LanguageToggler />
|
||||||
|
<ThemeToggler />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { changeLanguage } from "@/actions/language"
|
||||||
|
import { LanguageTogglerDropdown } from "./languageTogglerDropdown"
|
||||||
|
|
||||||
|
export function LanguageToggler() {
|
||||||
|
return (
|
||||||
|
<LanguageTogglerDropdown changeLanguage={changeLanguage} />
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { Globe } from "lucide-react"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu"
|
||||||
|
import { useTranslations } from "next-intl"
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
changeLanguage: (lang: string) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LanguageTogglerDropdown({ changeLanguage }: Props) {
|
||||||
|
const t = useTranslations();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button><Globe />{t("ChangeLanguage")}</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent className="mt-2" align="end">
|
||||||
|
<DropdownMenuItem onClick={() => changeLanguage("en")}>
|
||||||
|
English
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => changeLanguage("ru")}>
|
||||||
|
Русский
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => changeLanguage("it")}>
|
||||||
|
Italiano
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||||
|
|
||||||
|
export function ThemeProvider({
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof NextThemesProvider>) {
|
||||||
|
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { LaptopMinimal, Moon, Sun } from "lucide-react"
|
||||||
|
import { useTheme } from "next-themes"
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu"
|
||||||
|
import { useTranslations } from "next-intl"
|
||||||
|
|
||||||
|
export function ThemeToggler() {
|
||||||
|
const { setTheme } = useTheme();
|
||||||
|
const t = useTranslations("theme");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button size="icon">
|
||||||
|
<Sun className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||||
|
<Moon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent className="mt-2" align="end">
|
||||||
|
<DropdownMenuItem onClick={() => setTheme("light")}>
|
||||||
|
<Sun />
|
||||||
|
{t("light")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setTheme("dark")}>
|
||||||
|
<Moon />
|
||||||
|
{t("dark")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setTheme("system")}>
|
||||||
|
<LaptopMinimal />
|
||||||
|
{t("system")}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { Calendar as CalendarIcon } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Calendar } from "@/components/ui/calendar";
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
|
import { useLocale, useTranslations } from "next-intl";
|
||||||
|
import { forwardRef } from "react";
|
||||||
|
import { localeMap } from "@/types";
|
||||||
|
import { enUS } from "date-fns/locale";
|
||||||
|
|
||||||
|
interface BirthdatePickerProps {
|
||||||
|
value?: string;
|
||||||
|
onChange?: (value: string) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
"aria-invalid"?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BirthdatePicker = forwardRef<HTMLButtonElement, BirthdatePickerProps>(
|
||||||
|
({ value, onChange, disabled, "aria-invalid": ariaInvalid }, ref) => {
|
||||||
|
const t = useTranslations("MePage.items.profile.form.birthdate");
|
||||||
|
const date = value ? new Date(value) : undefined;
|
||||||
|
|
||||||
|
const handleSelect = (selected: Date | undefined) => {
|
||||||
|
if (selected && onChange) {
|
||||||
|
onChange(format(selected, "yyyy-MM-dd"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const locale = useLocale();
|
||||||
|
const dateLocale = localeMap[locale as keyof typeof localeMap] ?? enUS;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={disabled}
|
||||||
|
aria-invalid={ariaInvalid}
|
||||||
|
data-empty={!date}
|
||||||
|
className="data-[empty=true]:text-muted-foreground w-full justify-start text-left font-normal"
|
||||||
|
>
|
||||||
|
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||||
|
{date ? format(date, "PPP", { locale: dateLocale }) : <span>{t("pick")}</span>}
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-auto p-0">
|
||||||
|
<Calendar
|
||||||
|
mode="single"
|
||||||
|
selected={date}
|
||||||
|
onSelect={handleSelect}
|
||||||
|
captionLayout="dropdown"
|
||||||
|
disabled={{ after: new Date() }}
|
||||||
|
/>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
BirthdatePicker.displayName = "BirthdatePicker";
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
import { Slot } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-primary text-primary-foreground hover:bg-primary/90 items-center",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
|
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
icon: "size-9",
|
||||||
|
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot.Root : "button"
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants }
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import {
|
||||||
|
DayPicker,
|
||||||
|
getDefaultClassNames,
|
||||||
|
type DayButton,
|
||||||
|
type Locale,
|
||||||
|
} from "react-day-picker"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
|
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Calendar({
|
||||||
|
className,
|
||||||
|
classNames,
|
||||||
|
showOutsideDays = true,
|
||||||
|
captionLayout = "label",
|
||||||
|
buttonVariant = "ghost",
|
||||||
|
locale,
|
||||||
|
formatters,
|
||||||
|
components,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayPicker> & {
|
||||||
|
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||||
|
}) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DayPicker
|
||||||
|
showOutsideDays={showOutsideDays}
|
||||||
|
className={cn(
|
||||||
|
"bg-background group/calendar p-2 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(7)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
|
||||||
|
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||||
|
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
captionLayout={captionLayout}
|
||||||
|
locale={locale}
|
||||||
|
formatters={{
|
||||||
|
formatMonthDropdown: (date) =>
|
||||||
|
date.toLocaleString(locale?.code, { month: "short" }),
|
||||||
|
...formatters,
|
||||||
|
}}
|
||||||
|
classNames={{
|
||||||
|
root: cn("w-fit", defaultClassNames.root),
|
||||||
|
months: cn(
|
||||||
|
"flex gap-4 flex-col md:flex-row relative",
|
||||||
|
defaultClassNames.months
|
||||||
|
),
|
||||||
|
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||||
|
nav: cn(
|
||||||
|
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
|
||||||
|
defaultClassNames.nav
|
||||||
|
),
|
||||||
|
button_previous: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_previous
|
||||||
|
),
|
||||||
|
button_next: cn(
|
||||||
|
buttonVariants({ variant: buttonVariant }),
|
||||||
|
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||||
|
defaultClassNames.button_next
|
||||||
|
),
|
||||||
|
month_caption: cn(
|
||||||
|
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
|
||||||
|
defaultClassNames.month_caption
|
||||||
|
),
|
||||||
|
dropdowns: cn(
|
||||||
|
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
|
||||||
|
defaultClassNames.dropdowns
|
||||||
|
),
|
||||||
|
dropdown_root: cn(
|
||||||
|
"relative rounded-(--cell-radius)",
|
||||||
|
defaultClassNames.dropdown_root
|
||||||
|
),
|
||||||
|
dropdown: cn(
|
||||||
|
"absolute bg-popover inset-0 opacity-0",
|
||||||
|
defaultClassNames.dropdown
|
||||||
|
),
|
||||||
|
caption_label: cn(
|
||||||
|
"select-none font-medium",
|
||||||
|
captionLayout === "label"
|
||||||
|
? "text-sm"
|
||||||
|
: "rounded-(--cell-radius) flex items-center gap-1 text-sm [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||||
|
defaultClassNames.caption_label
|
||||||
|
),
|
||||||
|
table: "w-full border-collapse",
|
||||||
|
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||||
|
weekday: cn(
|
||||||
|
"text-muted-foreground rounded-(--cell-radius) flex-1 font-normal text-[0.8rem] select-none",
|
||||||
|
defaultClassNames.weekday
|
||||||
|
),
|
||||||
|
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||||
|
week_number_header: cn(
|
||||||
|
"select-none w-(--cell-size)",
|
||||||
|
defaultClassNames.week_number_header
|
||||||
|
),
|
||||||
|
week_number: cn(
|
||||||
|
"text-[0.8rem] select-none text-muted-foreground",
|
||||||
|
defaultClassNames.week_number
|
||||||
|
),
|
||||||
|
day: cn(
|
||||||
|
"relative w-full rounded-(--cell-radius) h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-(--cell-radius) group/day aspect-square select-none",
|
||||||
|
props.showWeekNumber
|
||||||
|
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-(--cell-radius)"
|
||||||
|
: "[&:first-child[data-selected=true]_button]:rounded-l-(--cell-radius)",
|
||||||
|
defaultClassNames.day
|
||||||
|
),
|
||||||
|
range_start: cn(
|
||||||
|
"rounded-l-(--cell-radius) bg-muted relative after:bg-muted after:absolute after:inset-y-0 after:w-4 after:right-0 z-0 isolate",
|
||||||
|
defaultClassNames.range_start
|
||||||
|
),
|
||||||
|
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||||
|
range_end: cn(
|
||||||
|
"rounded-r-(--cell-radius) bg-muted relative after:bg-muted after:absolute after:inset-y-0 after:w-4 after:left-0 z-0 isolate",
|
||||||
|
defaultClassNames.range_end
|
||||||
|
),
|
||||||
|
today: cn(
|
||||||
|
"bg-muted text-foreground rounded-(--cell-radius) data-[selected=true]:rounded-none",
|
||||||
|
defaultClassNames.today
|
||||||
|
),
|
||||||
|
outside: cn(
|
||||||
|
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||||
|
defaultClassNames.outside
|
||||||
|
),
|
||||||
|
disabled: cn(
|
||||||
|
"text-muted-foreground opacity-50",
|
||||||
|
defaultClassNames.disabled
|
||||||
|
),
|
||||||
|
hidden: cn("invisible", defaultClassNames.hidden),
|
||||||
|
...classNames,
|
||||||
|
}}
|
||||||
|
components={{
|
||||||
|
Root: ({ className, rootRef, ...props }) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="calendar"
|
||||||
|
ref={rootRef}
|
||||||
|
className={cn(className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Chevron: ({ className, orientation, ...props }) => {
|
||||||
|
if (orientation === "left") {
|
||||||
|
return (
|
||||||
|
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (orientation === "right") {
|
||||||
|
return (
|
||||||
|
<ChevronRightIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||||
|
)
|
||||||
|
},
|
||||||
|
DayButton: ({ ...props }) => (
|
||||||
|
<CalendarDayButton locale={locale} {...props} />
|
||||||
|
),
|
||||||
|
WeekNumber: ({ children, ...props }) => {
|
||||||
|
return (
|
||||||
|
<td {...props}>
|
||||||
|
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
...components,
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function CalendarDayButton({
|
||||||
|
className,
|
||||||
|
day,
|
||||||
|
modifiers,
|
||||||
|
locale,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
|
||||||
|
const defaultClassNames = getDefaultClassNames()
|
||||||
|
|
||||||
|
const ref = React.useRef<HTMLButtonElement>(null)
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (modifiers.focused) ref.current?.focus()
|
||||||
|
}, [modifiers.focused])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
ref={ref}
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-day={day.date.toLocaleDateString(locale?.code)}
|
||||||
|
data-selected-single={
|
||||||
|
modifiers.selected &&
|
||||||
|
!modifiers.range_start &&
|
||||||
|
!modifiers.range_end &&
|
||||||
|
!modifiers.range_middle
|
||||||
|
}
|
||||||
|
data-range-start={modifiers.range_start}
|
||||||
|
data-range-end={modifiers.range_end}
|
||||||
|
data-range-middle={modifiers.range_middle}
|
||||||
|
className={cn(
|
||||||
|
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-foreground relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-(--cell-radius) data-[range-end=true]:rounded-r-(--cell-radius) data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-(--cell-radius) data-[range-start=true]:rounded-l-(--cell-radius) [&>span]:text-xs [&>span]:opacity-70",
|
||||||
|
defaultClassNames.day,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Calendar, CalendarDayButton }
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||||
|
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function DropdownMenu({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||||
|
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Trigger
|
||||||
|
data-slot="dropdown-menu-trigger"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuContent({
|
||||||
|
className,
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Portal>
|
||||||
|
<DropdownMenuPrimitive.Content
|
||||||
|
data-slot="dropdown-menu-content"
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</DropdownMenuPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuItem({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||||
|
inset?: boolean
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Item
|
||||||
|
data-slot="dropdown-menu-item"
|
||||||
|
data-inset={inset}
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuCheckboxItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
checked,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.CheckboxItem
|
||||||
|
data-slot="dropdown-menu-checkbox-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
checked={checked}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.CheckboxItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioGroup({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioGroup
|
||||||
|
data-slot="dropdown-menu-radio-group"
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuRadioItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.RadioItem
|
||||||
|
data-slot="dropdown-menu-radio-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||||
|
<DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
<CircleIcon className="size-2 fill-current" />
|
||||||
|
</DropdownMenuPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
{children}
|
||||||
|
</DropdownMenuPrimitive.RadioItem>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuLabel({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Label
|
||||||
|
data-slot="dropdown-menu-label"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.Separator
|
||||||
|
data-slot="dropdown-menu-separator"
|
||||||
|
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuShortcut({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span">) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
data-slot="dropdown-menu-shortcut"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSub({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||||
|
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubTrigger({
|
||||||
|
className,
|
||||||
|
inset,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||||
|
inset?: boolean
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubTrigger
|
||||||
|
data-slot="dropdown-menu-sub-trigger"
|
||||||
|
data-inset={inset}
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronRightIcon className="ml-auto size-4" />
|
||||||
|
</DropdownMenuPrimitive.SubTrigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function DropdownMenuSubContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||||
|
return (
|
||||||
|
<DropdownMenuPrimitive.SubContent
|
||||||
|
data-slot="dropdown-menu-sub-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuPortal,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuGroup,
|
||||||
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuCheckboxItem,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
|
DropdownMenuSeparator,
|
||||||
|
DropdownMenuShortcut,
|
||||||
|
DropdownMenuSub,
|
||||||
|
DropdownMenuSubTrigger,
|
||||||
|
DropdownMenuSubContent,
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useMemo } from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Label } from "@/components/ui/label"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
|
||||||
|
return (
|
||||||
|
<fieldset
|
||||||
|
data-slot="field-set"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col gap-6",
|
||||||
|
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLegend({
|
||||||
|
className,
|
||||||
|
variant = "legend",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
|
||||||
|
return (
|
||||||
|
<legend
|
||||||
|
data-slot="field-legend"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(
|
||||||
|
"mb-3 font-medium",
|
||||||
|
"data-[variant=legend]:text-base",
|
||||||
|
"data-[variant=label]:text-sm",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-group"
|
||||||
|
className={cn(
|
||||||
|
"group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fieldVariants = cva(
|
||||||
|
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
orientation: {
|
||||||
|
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
|
||||||
|
horizontal: [
|
||||||
|
"flex-row items-center",
|
||||||
|
"[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
responsive: [
|
||||||
|
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
|
||||||
|
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
|
||||||
|
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
orientation: "vertical",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Field({
|
||||||
|
className,
|
||||||
|
orientation = "vertical",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="group"
|
||||||
|
data-slot="field"
|
||||||
|
data-orientation={orientation}
|
||||||
|
className={cn(fieldVariants({ orientation }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-content"
|
||||||
|
className={cn(
|
||||||
|
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Label>) {
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
|
||||||
|
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
|
||||||
|
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-label"
|
||||||
|
className={cn(
|
||||||
|
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="field-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||||
|
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
|
||||||
|
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldSeparator({
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
children?: React.ReactNode
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="field-separator"
|
||||||
|
data-content={!!children}
|
||||||
|
className={cn(
|
||||||
|
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<Separator className="absolute inset-0 top-1/2" />
|
||||||
|
{children && (
|
||||||
|
<span
|
||||||
|
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
|
||||||
|
data-slot="field-separator-content"
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FieldError({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
errors,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & {
|
||||||
|
errors?: Array<{ message?: string } | undefined>
|
||||||
|
}) {
|
||||||
|
const content = useMemo(() => {
|
||||||
|
if (children) {
|
||||||
|
return children
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!errors?.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniqueErrors = [
|
||||||
|
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||||
|
]
|
||||||
|
|
||||||
|
if (uniqueErrors?.length == 1) {
|
||||||
|
return uniqueErrors[0]?.message
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||||
|
{uniqueErrors.map(
|
||||||
|
(error, index) =>
|
||||||
|
error?.message && <li key={index}>{error.message}</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}, [children, errors])
|
||||||
|
|
||||||
|
if (!content) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
data-slot="field-error"
|
||||||
|
className={cn("text-destructive text-sm font-normal", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Field,
|
||||||
|
FieldLabel,
|
||||||
|
FieldDescription,
|
||||||
|
FieldError,
|
||||||
|
FieldGroup,
|
||||||
|
FieldLegend,
|
||||||
|
FieldSeparator,
|
||||||
|
FieldSet,
|
||||||
|
FieldContent,
|
||||||
|
FieldTitle,
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
data-slot="input"
|
||||||
|
className={cn(
|
||||||
|
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||||
|
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Input }
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
import { Slot } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
|
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role="list"
|
||||||
|
data-slot="item-group"
|
||||||
|
className={cn(
|
||||||
|
"group/item-group flex w-full flex-col gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof Separator>) {
|
||||||
|
return (
|
||||||
|
<Separator
|
||||||
|
data-slot="item-separator"
|
||||||
|
orientation="horizontal"
|
||||||
|
className={cn("my-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemVariants = cva(
|
||||||
|
"[a]:hover:bg-muted rounded-lg border text-sm w-full group/item focus-visible:border-ring focus-visible:ring-ring/50 flex items-center flex-wrap outline-none transition-colors duration-100 focus-visible:ring-[3px] [a]:transition-colors",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "border-transparent",
|
||||||
|
outline: "border-border",
|
||||||
|
muted: "bg-muted/50 border-transparent",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: "gap-2.5 px-3 py-2.5",
|
||||||
|
sm: "gap-2.5 px-3 py-2.5",
|
||||||
|
xs: "gap-2 px-2.5 py-2 in-data-[slot=dropdown-menu-content]:p-0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Item({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
size = "default",
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> &
|
||||||
|
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot.Root : "div"
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="item"
|
||||||
|
data-variant={variant}
|
||||||
|
data-size={size}
|
||||||
|
className={cn(itemVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemMediaVariants = cva(
|
||||||
|
"gap-2 group-has-data-[slot=item-description]/item:translate-y-0.5 group-has-data-[slot=item-description]/item:self-start flex shrink-0 items-center justify-center [&_svg]:pointer-events-none",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "[&_svg:not([class*='size-'])]:size-4",
|
||||||
|
image:
|
||||||
|
"size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function ItemMedia({
|
||||||
|
className,
|
||||||
|
variant = "default",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-media"
|
||||||
|
data-variant={variant}
|
||||||
|
className={cn(itemMediaVariants({ variant, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-content"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-1 flex-col gap-1 group-data-[size=xs]/item:gap-0 [&+[data-slot=item-content]]:flex-none",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-title"
|
||||||
|
className={cn(
|
||||||
|
"line-clamp-1 flex w-fit items-center gap-2 text-sm leading-snug font-medium underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="item-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground [&>a:hover]:text-primary line-clamp-4 text-left text-sm leading-normal font-normal group-data-[size=xs]/item:text-xs [&>a]:underline [&>a]:underline-offset-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-actions"
|
||||||
|
className={cn("flex items-center gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-header"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="item-footer"
|
||||||
|
className={cn(
|
||||||
|
"flex basis-full items-center justify-between gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Item,
|
||||||
|
ItemMedia,
|
||||||
|
ItemContent,
|
||||||
|
ItemActions,
|
||||||
|
ItemGroup,
|
||||||
|
ItemSeparator,
|
||||||
|
ItemTitle,
|
||||||
|
ItemDescription,
|
||||||
|
ItemHeader,
|
||||||
|
ItemFooter,
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Label as LabelPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Label({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
data-slot="label"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Label }
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Popover as PopoverPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Popover({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||||
|
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||||
|
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverContent({
|
||||||
|
className,
|
||||||
|
align = "center",
|
||||||
|
sideOffset = 4,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<PopoverPrimitive.Portal>
|
||||||
|
<PopoverPrimitive.Content
|
||||||
|
data-slot="popover-content"
|
||||||
|
align={align}
|
||||||
|
sideOffset={sideOffset}
|
||||||
|
className={cn(
|
||||||
|
"bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg p-2.5 text-sm shadow-md ring-1 outline-hidden duration-100",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</PopoverPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverAnchor({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||||
|
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="popover-header"
|
||||||
|
className={cn("flex flex-col gap-0.5 text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="popover-title"
|
||||||
|
className={cn("font-medium", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PopoverDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"p">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="popover-description"
|
||||||
|
className={cn("text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Popover,
|
||||||
|
PopoverAnchor,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverDescription,
|
||||||
|
PopoverHeader,
|
||||||
|
PopoverTitle,
|
||||||
|
PopoverTrigger,
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Select as SelectPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
|
||||||
|
|
||||||
|
function Select({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||||
|
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectGroup({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Group
|
||||||
|
data-slot="select-group"
|
||||||
|
className={cn("scroll-my-1 p-1", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectValue({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||||
|
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectTrigger({
|
||||||
|
className,
|
||||||
|
size = "default",
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||||
|
size?: "sm" | "default"
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Trigger
|
||||||
|
data-slot="select-trigger"
|
||||||
|
data-size={size}
|
||||||
|
className={cn(
|
||||||
|
"border-input data-placeholder:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 flex w-fit items-center justify-between gap-1.5 rounded-lg border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<SelectPrimitive.Icon asChild>
|
||||||
|
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4" />
|
||||||
|
</SelectPrimitive.Icon>
|
||||||
|
</SelectPrimitive.Trigger>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
position = "item-aligned",
|
||||||
|
align = "center",
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Portal>
|
||||||
|
<SelectPrimitive.Content
|
||||||
|
data-slot="select-content"
|
||||||
|
data-align-trigger={position === "item-aligned"}
|
||||||
|
className={cn("bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg shadow-md ring-1 duration-100 data-[align-trigger=true]:animate-none", position ==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", className )}
|
||||||
|
position={position}
|
||||||
|
align={align}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<SelectScrollUpButton />
|
||||||
|
<SelectPrimitive.Viewport
|
||||||
|
data-position={position}
|
||||||
|
className={cn(
|
||||||
|
"data-[position=popper]:h-(--radix-select-trigger-height) data-[position=popper]:w-full data-[position=popper]:min-w-(--radix-select-trigger-width)",
|
||||||
|
position === "popper" && ""
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</SelectPrimitive.Viewport>
|
||||||
|
<SelectScrollDownButton />
|
||||||
|
</SelectPrimitive.Content>
|
||||||
|
</SelectPrimitive.Portal>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectLabel({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Label
|
||||||
|
data-slot="select-label"
|
||||||
|
className={cn("text-muted-foreground px-1.5 py-1 text-xs", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectItem({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Item
|
||||||
|
data-slot="select-item"
|
||||||
|
className={cn(
|
||||||
|
"focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center">
|
||||||
|
<SelectPrimitive.ItemIndicator>
|
||||||
|
<CheckIcon className="pointer-events-none" />
|
||||||
|
</SelectPrimitive.ItemIndicator>
|
||||||
|
</span>
|
||||||
|
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||||
|
</SelectPrimitive.Item>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectSeparator({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.Separator
|
||||||
|
data-slot="select-separator"
|
||||||
|
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollUpButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollUpButton
|
||||||
|
data-slot="select-scroll-up-button"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronUpIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollUpButton>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectScrollDownButton({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||||
|
return (
|
||||||
|
<SelectPrimitive.ScrollDownButton
|
||||||
|
data-slot="select-scroll-down-button"
|
||||||
|
className={cn(
|
||||||
|
"bg-popover z-10 flex cursor-default items-center justify-center py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<ChevronDownIcon
|
||||||
|
/>
|
||||||
|
</SelectPrimitive.ScrollDownButton>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectGroup,
|
||||||
|
SelectItem,
|
||||||
|
SelectLabel,
|
||||||
|
SelectScrollDownButton,
|
||||||
|
SelectScrollUpButton,
|
||||||
|
SelectSeparator,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import { Separator as SeparatorPrimitive } from "radix-ui"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Separator({
|
||||||
|
className,
|
||||||
|
orientation = "horizontal",
|
||||||
|
decorative = true,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<SeparatorPrimitive.Root
|
||||||
|
data-slot="separator"
|
||||||
|
decorative={decorative}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Separator }
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="skeleton"
|
||||||
|
className={cn("bg-muted animate-pulse rounded-md", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Skeleton }
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useTheme } from "next-themes"
|
||||||
|
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||||
|
import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
|
||||||
|
|
||||||
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
|
const { theme = "system" } = useTheme()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Sonner
|
||||||
|
theme={theme as ToasterProps["theme"]}
|
||||||
|
className="toaster group"
|
||||||
|
icons={{
|
||||||
|
success: (
|
||||||
|
<CircleCheckIcon className="size-4" />
|
||||||
|
),
|
||||||
|
info: (
|
||||||
|
<InfoIcon className="size-4" />
|
||||||
|
),
|
||||||
|
warning: (
|
||||||
|
<TriangleAlertIcon className="size-4" />
|
||||||
|
),
|
||||||
|
error: (
|
||||||
|
<OctagonXIcon className="size-4" />
|
||||||
|
),
|
||||||
|
loading: (
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
style={
|
||||||
|
{
|
||||||
|
"--normal-bg": "var(--popover)",
|
||||||
|
"--normal-text": "var(--popover-foreground)",
|
||||||
|
"--normal-border": "var(--border)",
|
||||||
|
"--border-radius": "var(--radius)",
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
|
toastOptions={{
|
||||||
|
classNames: {
|
||||||
|
toast: "cn-toast",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Toaster }
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Loader2Icon } from "lucide-react"
|
||||||
|
|
||||||
|
function Spinner({ className, ...props }: React.ComponentProps<"svg">) {
|
||||||
|
return (
|
||||||
|
<Loader2Icon role="status" aria-label="Loading" className={cn("size-4 animate-spin", className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Spinner }
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig, globalIgnores } from "eslint/config";
|
||||||
|
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||||
|
import nextTs from "eslint-config-next/typescript";
|
||||||
|
|
||||||
|
const eslintConfig = defineConfig([
|
||||||
|
...nextVitals,
|
||||||
|
...nextTs,
|
||||||
|
// Override default ignores of eslint-config-next.
|
||||||
|
globalIgnores([
|
||||||
|
// Default ignores of eslint-config-next:
|
||||||
|
".next/**",
|
||||||
|
"out/**",
|
||||||
|
"build/**",
|
||||||
|
"next-env.d.ts",
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export default eslintConfig;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { getRequestConfig } from "next-intl/server";
|
||||||
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
|
export default getRequestConfig(async () => {
|
||||||
|
const store = await cookies();
|
||||||
|
const locale = store.get("locale")?.value || 'en';
|
||||||
|
|
||||||
|
return {
|
||||||
|
locale,
|
||||||
|
messages: (await import(`../messages/${locale}.json`)).default
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export const cookieConfig = {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
sameSite: "lax" as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const pkceConfig = {
|
||||||
|
...cookieConfig,
|
||||||
|
path: "/api/callback",
|
||||||
|
maxAge: 60 * 10,
|
||||||
|
};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { clsx, type ClassValue } from "clsx"
|
||||||
|
import { twMerge } from "tailwind-merge"
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs))
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
{
|
||||||
|
"ChangeLanguage": "Change language",
|
||||||
|
"LoginPage": {
|
||||||
|
"title": "Welcome to Kotosoft ID",
|
||||||
|
"subtitle": "Unified ID system of Dusiburg",
|
||||||
|
"email": {
|
||||||
|
"title": "Email",
|
||||||
|
"invalid": "Please enter a correct email"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Password",
|
||||||
|
"minLength": "Password must have at least 8 symbols"
|
||||||
|
},
|
||||||
|
"required": "This field is required",
|
||||||
|
"login": "Login",
|
||||||
|
"noAccountNote": "You don't have a Kotosoft ID account? You can register <register>here</register>."
|
||||||
|
},
|
||||||
|
"RegisterPage":{
|
||||||
|
"title": "Sign up in Kotosoft ID",
|
||||||
|
"subtitle": "Create an account in the unified ID system of Dusiburg",
|
||||||
|
"email": {
|
||||||
|
"title": "Email",
|
||||||
|
"invalid": "Please enter a correct email"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Password",
|
||||||
|
"minLength": "Password must have at least 8 symbols"
|
||||||
|
},
|
||||||
|
"firstName": {
|
||||||
|
"title": "Your first name",
|
||||||
|
"minLength": "First name must have at least 2 characters",
|
||||||
|
"maxLength": "First name must contain no more than 64 characters"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Your last name",
|
||||||
|
"minLength": "Last name must have at least 2 characters",
|
||||||
|
"maxLength": "Last name must contain no more than 64 characters"
|
||||||
|
},
|
||||||
|
"sex": {
|
||||||
|
"title": "Sex",
|
||||||
|
"select": "Specify Your sex",
|
||||||
|
"male": "Male",
|
||||||
|
"female": "Female"
|
||||||
|
},
|
||||||
|
"required": "This field is required",
|
||||||
|
"next": "Next",
|
||||||
|
"back": "Back",
|
||||||
|
"register": "Sign in",
|
||||||
|
"hasAccountNote": "You already have a Kotosoft ID account? You can log in <login>here</login>."
|
||||||
|
},
|
||||||
|
"MePage": {
|
||||||
|
"loadError": "Something has gone wrong. It's impossible to load user.",
|
||||||
|
"items": {
|
||||||
|
"profile": {
|
||||||
|
"title": "Profile",
|
||||||
|
"form": {
|
||||||
|
"firstName": {
|
||||||
|
"title": "Your first name",
|
||||||
|
"minLength": "First name must have at least 2 characters",
|
||||||
|
"maxLength": "First name must contain no more than 64 characters"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Your last name",
|
||||||
|
"minLength": "Last name must have at least 2 characters",
|
||||||
|
"maxLength": "Last name must contain no more than 64 characters"
|
||||||
|
},
|
||||||
|
"birthdate": {
|
||||||
|
"title": "Date of birth",
|
||||||
|
"pick": "Select Your date of birth"
|
||||||
|
},
|
||||||
|
"required": "This field is required",
|
||||||
|
"save": "Save",
|
||||||
|
"successfullyUpdated": "Your profile is updated successfully!",
|
||||||
|
"updateError": "An error occurred during the update. Please try again later."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"applications": {
|
||||||
|
"title": "Applications",
|
||||||
|
"authorized": "Autorized on",
|
||||||
|
"revoke": "Revoke"
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Positions"
|
||||||
|
},
|
||||||
|
"logout": "Logout"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConsentPage": {
|
||||||
|
"title": "Access to {service}",
|
||||||
|
"subtitle": "{service} wants to access Your Kotosoft ID account to:",
|
||||||
|
"invalidSession": "This session is invalid. Please go back to Your application and try again.",
|
||||||
|
"scopes": {
|
||||||
|
"profile:read": "See information of Your profile",
|
||||||
|
"profile:edit": "Edit information of Your profile"
|
||||||
|
},
|
||||||
|
"allow": "Allow",
|
||||||
|
"deny": "Deny",
|
||||||
|
"toApp": "Back to application",
|
||||||
|
"toHome": "Back to home page"
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"light": "Light",
|
||||||
|
"dark": "Dark",
|
||||||
|
"system": "System"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"serverError": "Server error. Please try again later.",
|
||||||
|
"invalidCredentialsError": "Incorrect email or password",
|
||||||
|
"emailAlreadyExistsError": "This email is already in use",
|
||||||
|
"allFieldsRequired": "Please fill in all the fields"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
{
|
||||||
|
"ChangeLanguage": "Cambia lingua",
|
||||||
|
"LoginPage": {
|
||||||
|
"title": "Benvenuto in Kotosoft ID",
|
||||||
|
"subtitle": "Il sistema ID unificato di Kotosoft",
|
||||||
|
"email": {
|
||||||
|
"title": "Email",
|
||||||
|
"invalid": "Inserisci un indirizzo email valido"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Password",
|
||||||
|
"minLength": "La password deve contenere almeno 8 caratteri"
|
||||||
|
},
|
||||||
|
"required": "Questo campo è obbligatorio",
|
||||||
|
"login": "Accedi",
|
||||||
|
"noAccountNote": "Non hai ancora un account Kotosoft ID? Registrati <register>qui</register>."
|
||||||
|
},
|
||||||
|
"RegisterPage": {
|
||||||
|
"title": "Registrati a Kotosoft ID",
|
||||||
|
"subtitle": "Crea un account nel sistema ID unificato di Kotosoft",
|
||||||
|
"email": {
|
||||||
|
"title": "Email",
|
||||||
|
"invalid": "Inserisci un indirizzo email valido"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Password",
|
||||||
|
"minLength": "La password deve contenere almeno 8 caratteri"
|
||||||
|
},
|
||||||
|
"firstName": {
|
||||||
|
"title": "Il tuo nome",
|
||||||
|
"minLength": "Il nome deve contenere almeno 2 caratteri",
|
||||||
|
"maxLength": "Il nome deve contenere al massimo 64 caratteri"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Il tuo cognome",
|
||||||
|
"minLength": "Il cognome deve contenere almeno 2 caratteri",
|
||||||
|
"maxLength": "Il cognome deve contenere al massimo 64 caratteri"
|
||||||
|
},
|
||||||
|
"sex": {
|
||||||
|
"title": "Sesso",
|
||||||
|
"select": "Scegli il tuo sesso",
|
||||||
|
"male": "Maschile",
|
||||||
|
"female": "Femminile"
|
||||||
|
},
|
||||||
|
"required": "Questo campo è obbligatorio",
|
||||||
|
"next": "Avanti",
|
||||||
|
"back": "Indietro",
|
||||||
|
"register": "Registrati",
|
||||||
|
"hasAccountNote": "Hai già un account Kotosoft ID? Accedi <login>qui</login>."
|
||||||
|
},
|
||||||
|
"MePage": {
|
||||||
|
"loadError": "Qualcosa è andato storto. Impossibile caricare l'utente.",
|
||||||
|
"items": {
|
||||||
|
"profile": {
|
||||||
|
"title": "Profilo",
|
||||||
|
"form": {
|
||||||
|
"firstName": {
|
||||||
|
"title": "Il tuo nome",
|
||||||
|
"minLength": "Il nome deve contenere almeno 2 caratteri",
|
||||||
|
"maxLength": "Il nome deve contenere al massimo 64 caratteri"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Il tuo cognome",
|
||||||
|
"minLength": "Il cognome deve contenere almeno 2 caratteri",
|
||||||
|
"maxLength": "Il cognome deve contenere al massimo 64 caratteri"
|
||||||
|
},
|
||||||
|
"birthdate": {
|
||||||
|
"title": "Data di nascita",
|
||||||
|
"pick": "Seleziona la tua data di nascita"
|
||||||
|
},
|
||||||
|
"required": "Questo campo è obbligatorio",
|
||||||
|
"save": "Salva",
|
||||||
|
"successfullyUpdated": "Il tuo profilo è aggiornato con successo!",
|
||||||
|
"updateError": "Si è verificato un errore durante l'aggiornamento. Riprova più tardi."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"applications": {
|
||||||
|
"title": "Applicazioni",
|
||||||
|
"authorized": "Autorizzato il",
|
||||||
|
"revoke": "Revoca"
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Posizioni"
|
||||||
|
},
|
||||||
|
"logout": "Esci"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConsentPage": {
|
||||||
|
"title": "Accesso a {service}",
|
||||||
|
"subtitle": "{service} vuole accedere al tuo account Kotosoft ID per:",
|
||||||
|
"invalidSession": "Questa sessione non è valida. Torna all'applicazione e riprova.",
|
||||||
|
"scopes": {
|
||||||
|
"profile:read": "Visualizzare le informazioni del tuo profilo",
|
||||||
|
"profile:edit": "Modificare le informazioni del tuo profilo"
|
||||||
|
},
|
||||||
|
"allow": "Consenti",
|
||||||
|
"deny": "Annulla",
|
||||||
|
"toApp": "Torna all'applicazione",
|
||||||
|
"toHome": "Torna alla home"
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"light": "Chiaro",
|
||||||
|
"dark": "Scuro",
|
||||||
|
"system": "Sistema"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"serverError": "Errore del server. Riprova più tardi.",
|
||||||
|
"invalidCredentialsError": "Email o password non corretti",
|
||||||
|
"emailAlreadyExistsError": "Questa email è già in uso",
|
||||||
|
"allFieldsRequired": "Inserisci tutti i campi, per favore"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
{
|
||||||
|
"ChangeLanguage": "Поменять язык",
|
||||||
|
"LoginPage": {
|
||||||
|
"title": "Приветствуем в Kotosoft ID",
|
||||||
|
"subtitle": "Единой ID системе Дусибурга",
|
||||||
|
"email": {
|
||||||
|
"title": "Почта",
|
||||||
|
"invalid": "Пожалуйста, напишите правильный адрес почты"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Пароль",
|
||||||
|
"minLength": "Пароль должен содержать не менее 8 символов"
|
||||||
|
},
|
||||||
|
"required": "Это поле является обязательным",
|
||||||
|
"login": "Вход",
|
||||||
|
"noAccountNote": "У Вас нет аккаунта в Kotosoft ID? Зарегистрируйтесь <register>здесь</register>."
|
||||||
|
},
|
||||||
|
"RegisterPage":{
|
||||||
|
"title": "Регистрация в Kotosoft ID",
|
||||||
|
"subtitle": "Создайте аккаунт в Единой ID системе Дусибурга",
|
||||||
|
"email": {
|
||||||
|
"title": "Почта",
|
||||||
|
"invalid": "Пожалуйста, напишите правильный адрес почты"
|
||||||
|
},
|
||||||
|
"password": {
|
||||||
|
"title": "Пароль",
|
||||||
|
"minLength": "Пароль должен содержать не менее 8 символов"
|
||||||
|
},
|
||||||
|
"firstName": {
|
||||||
|
"title": "Ваше имя",
|
||||||
|
"minLength": "Имя должно содержать не менее 2 символов",
|
||||||
|
"maxLength": "Имя должно содержать не более 64 символов"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Ваша фамилия",
|
||||||
|
"minLength": "Фамилия должна содержать не менее 2 символов",
|
||||||
|
"maxLength": "Фамилия должна содержать не более 64 символов"
|
||||||
|
},
|
||||||
|
"sex": {
|
||||||
|
"title": "Пол",
|
||||||
|
"select": "Выберите Ваш пол",
|
||||||
|
"male": "Мужской",
|
||||||
|
"female": "Женский"
|
||||||
|
},
|
||||||
|
"required": "Это поле является обязательным",
|
||||||
|
"next": "Дальше",
|
||||||
|
"back": "Назад",
|
||||||
|
"register": "Зарегистрироваться",
|
||||||
|
"hasAccountNote": "У Вас уже есть аккаунт в Kotosoft ID? Войти можно <login>тут</login>."
|
||||||
|
},
|
||||||
|
"MePage": {
|
||||||
|
"loadError": "Что-то пошло не так. Не получилось загрузить пользователя.",
|
||||||
|
"items": {
|
||||||
|
"profile": {
|
||||||
|
"title": "Профиль",
|
||||||
|
"form": {
|
||||||
|
"firstName": {
|
||||||
|
"title": "Ваше имя",
|
||||||
|
"minLength": "Имя должно содержать не менее 2 символов",
|
||||||
|
"maxLength": "Имя должно содержать не более 64 символов"
|
||||||
|
},
|
||||||
|
"secondName": {
|
||||||
|
"title": "Ваша фамилия",
|
||||||
|
"minLength": "Фамилия должна содержать не менее 2 символов",
|
||||||
|
"maxLength": "Фамилия должна содержать не более 64 символов"
|
||||||
|
},
|
||||||
|
"birthdate": {
|
||||||
|
"title": "Дата рождения",
|
||||||
|
"pick": "Выберите Вашу дату рождения"
|
||||||
|
},
|
||||||
|
"required": "Это поле является обязательным",
|
||||||
|
"save": "Сохранить",
|
||||||
|
"successfullyUpdated": "Профиль успешно обновлён!",
|
||||||
|
"updateError": "Произошла ошибка при обновлении. Попробуйте ещё раз позже."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"applications": {
|
||||||
|
"title": "Приложения",
|
||||||
|
"authorized": "Авторизировано",
|
||||||
|
"revoke": "Отозвать"
|
||||||
|
},
|
||||||
|
"positions": {
|
||||||
|
"title": "Должности"
|
||||||
|
},
|
||||||
|
"logout": "Выйти"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConsentPage": {
|
||||||
|
"title": "Вход в {service}",
|
||||||
|
"subtitle": "{service} хочет получить доступ к Вашему аккаунту Kotosoft ID, чтобы:",
|
||||||
|
"invalidSession": "Эта сессия недействительна. Пожалуйста, вернитесь в своё приложение и попробуйте ещё раз.",
|
||||||
|
"scopes": {
|
||||||
|
"profile:read": "Видеть данные Вашего профиля",
|
||||||
|
"profile:edit": "Изменять данные в Вашем профиле"
|
||||||
|
},
|
||||||
|
"allow": "Разрешить",
|
||||||
|
"deny": "Запретить",
|
||||||
|
"toApp": "Назад в приложение",
|
||||||
|
"toHome": "На главную"
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"light": "Светлая",
|
||||||
|
"dark": "Тёмная",
|
||||||
|
"system": "Как в системе"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"serverError": "Ошибка сервера. Пожалуйста, попробуйте ещё раз позже.",
|
||||||
|
"invalidCredentialsError": "Неправильный адрес почты или пароль",
|
||||||
|
"emailAlreadyExistsError": "Аккаунт с такой почтой уже существует",
|
||||||
|
"allFieldsRequired": "Пожалуйста, заполните все поля"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { NextConfig } from "next";
|
||||||
|
import createNextIntlPlugin from "next-intl/plugin";
|
||||||
|
|
||||||
|
const nextConfig: NextConfig = {
|
||||||
|
/* config options here */
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const withNextIntl = createNextIntlPlugin();
|
||||||
|
export default withNextIntl(nextConfig);
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"name": "kotosoft-id-frontend",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "eslint"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"date-fns": "^4.1.0",
|
||||||
|
"lucide-react": "^0.575.0",
|
||||||
|
"next": "16.1.6",
|
||||||
|
"next-intl": "^4.8.3",
|
||||||
|
"next-themes": "^0.4.6",
|
||||||
|
"radix-ui": "^1.4.3",
|
||||||
|
"react": "19.2.3",
|
||||||
|
"react-day-picker": "^9.14.0",
|
||||||
|
"react-dom": "19.2.3",
|
||||||
|
"react-hook-form": "^7.71.2",
|
||||||
|
"sonner": "^2.0.7",
|
||||||
|
"tailwind-merge": "^3.5.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/node": "^20",
|
||||||
|
"@types/react": "^19",
|
||||||
|
"@types/react-dom": "^19",
|
||||||
|
"eslint": "^9",
|
||||||
|
"eslint-config-next": "16.1.6",
|
||||||
|
"shadcn": "^3.8.5",
|
||||||
|
"tailwindcss": "^4",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
|
"typescript": "^5"
|
||||||
|
},
|
||||||
|
"ignoreScripts": [
|
||||||
|
"sharp",
|
||||||
|
"unrs-resolver"
|
||||||
|
],
|
||||||
|
"trustedDependencies": [
|
||||||
|
"sharp",
|
||||||
|
"unrs-resolver"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const config = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
|
const PUBLIC_PATHS = ["/login", "/register", "/callback", "/oauth/error", "/callback/error"];
|
||||||
|
|
||||||
|
export async function proxy(request: NextRequest) {
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
const hasRefreshToken = request.cookies.has("refresh_token");
|
||||||
|
const isPublicPath = PUBLIC_PATHS.includes(pathname);
|
||||||
|
const session = request.nextUrl.searchParams.get("session");
|
||||||
|
|
||||||
|
if (hasRefreshToken && session && pathname === "/login") {
|
||||||
|
const accessToken = request.cookies.get("access_token")?.value;
|
||||||
|
try {
|
||||||
|
await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/attach`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ session }),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to attach session:", error);
|
||||||
|
return NextResponse.redirect(new URL("/callback/error", request.url));
|
||||||
|
}
|
||||||
|
return NextResponse.redirect(new URL(`/consent?session=${session}`, request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasRefreshToken && (isPublicPath || pathname === "/")) {
|
||||||
|
return NextResponse.redirect(new URL("/me", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasRefreshToken && !isPublicPath && !session || (!hasRefreshToken && pathname === "/")) {
|
||||||
|
return NextResponse.redirect(new URL("/login", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
|
||||||
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2017",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [
|
||||||
|
{
|
||||||
|
"name": "next"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"next-env.d.ts",
|
||||||
|
"**/*.ts",
|
||||||
|
"**/*.tsx",
|
||||||
|
".next/types/**/*.ts",
|
||||||
|
".next/dev/types/**/*.ts",
|
||||||
|
"**/*.mts"
|
||||||
|
],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { enUS, it, ru } from "date-fns/locale";
|
||||||
|
|
||||||
|
export enum Sex {
|
||||||
|
MALE = "MALE",
|
||||||
|
FEMALE = "FEMALE"
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
email: string;
|
||||||
|
first_name: string;
|
||||||
|
second_name: string;
|
||||||
|
birth_date: string;
|
||||||
|
sex: Sex;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OAuthSession {
|
||||||
|
client_id: string;
|
||||||
|
client_name: string;
|
||||||
|
redirect_uri: string;
|
||||||
|
scopes: string[];
|
||||||
|
state: string;
|
||||||
|
user_id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Consent {
|
||||||
|
client_id: string
|
||||||
|
client_name: string
|
||||||
|
scopes: string[]
|
||||||
|
authorized_at: string
|
||||||
|
last_used_at: string | null
|
||||||
|
isRevokable: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const localeMap = {
|
||||||
|
ru,
|
||||||
|
en: enUS,
|
||||||
|
it
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user