initial commit
This commit is contained in:
@@ -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;
|
||||
Reference in New Issue
Block a user