implement auth using Auth0
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
DROP TABLE oauth_login_states;
|
||||||
|
DROP TABLE oauth_tokens;
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
CREATE TABLE oauth_login_states (
|
||||||
|
state BYTEA NOT NULL,
|
||||||
|
expiration TIMESTAMPTZ NOT NULL DEFAULT (NOW() + 10 'minute'),
|
||||||
|
|
||||||
|
PRIMARY KEY (state)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE oauth_tokens (
|
||||||
|
access_token TEXT NOT NULL,
|
||||||
|
token_type TEXT NOT NULL,
|
||||||
|
refresh_token TEXT NOT NULL,
|
||||||
|
expiry TIMESTAMPTZ NOT NULL,
|
||||||
|
|
||||||
|
id_token_issuer TEXT NOT NULL,
|
||||||
|
id_token_audience TEXT[] NOT NULL,
|
||||||
|
id_token_subject TEXT NOT NULL,
|
||||||
|
id_token_expiry TIMESTAMPTZ NOT NULL,
|
||||||
|
id_token_issued_at TIMESTAMPTZ NOT NULL,
|
||||||
|
id_token_nonce TEXT NOT NULL,
|
||||||
|
id_token_access_token_hash TEXT NOT NULL,
|
||||||
|
|
||||||
|
claims JSONB NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (access_token)
|
||||||
|
);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
HOST TYPE PRIORITY TTL DATA
|
||||||
|
-----------------------------------------------------
|
||||||
|
@ A 0 4 hrs 198.185.159.145
|
||||||
|
|
||||||
|
@ A 0 4 hrs 198.49.23.145
|
||||||
|
|
||||||
|
@ A 0 4 hrs 198.49.23.144
|
||||||
|
|
||||||
|
@ A 0 4 hrs 198.185.159.144
|
||||||
|
|
||||||
|
www CNAME 0 4 hrs ext-sq.squarespace.com
|
||||||
|
|
||||||
|
@ HTTPS 0 4 hrs 1 . alpn="h2,http/1.1" ipv4hint="198.185.159.144,198.185.159.145,198.49.23.144,198.49.23.145"
|
||||||
@@ -8,8 +8,10 @@ require github.com/jackc/pgx/v5 v5.7.6
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/angelbeltran/templater v0.1.0
|
github.com/angelbeltran/templater v0.1.0
|
||||||
|
github.com/coreos/go-oidc/v3 v3.8.0
|
||||||
github.com/google/uuid v1.5.0
|
github.com/google/uuid v1.5.0
|
||||||
github.com/oapi-codegen/runtime v1.1.2
|
github.com/oapi-codegen/runtime v1.1.2
|
||||||
|
golang.org/x/oauth2 v0.15.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -20,8 +22,10 @@ require (
|
|||||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
|
||||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
|
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect
|
||||||
github.com/getkin/kin-openapi v0.133.0 // indirect
|
github.com/getkin/kin-openapi v0.133.0 // indirect
|
||||||
|
github.com/go-jose/go-jose/v3 v3.0.0 // indirect
|
||||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||||
github.com/go-openapi/swag v0.23.0 // indirect
|
github.com/go-openapi/swag v0.23.0 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
@@ -44,6 +48,8 @@ require (
|
|||||||
golang.org/x/sync v0.19.0 // indirect
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
golang.org/x/text v0.32.0 // indirect
|
golang.org/x/text v0.32.0 // indirect
|
||||||
golang.org/x/tools v0.39.0 // indirect
|
golang.org/x/tools v0.39.0 // indirect
|
||||||
|
google.golang.org/appengine v1.6.8 // indirect
|
||||||
|
google.golang.org/protobuf v1.31.0 // indirect
|
||||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvF
|
|||||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.8.0 h1:s3e30r6VEl3/M7DTSCEuImmrfu1/1WBgA0cXkdzkrAY=
|
||||||
|
github.com/coreos/go-oidc/v3 v3.8.0/go.mod h1:yQzSCqBnK3e6Fs5l+f5i0F8Kwf0zpH9bPEsbY00KanM=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@@ -24,6 +26,8 @@ github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWo
|
|||||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||||
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
|
github.com/getkin/kin-openapi v0.133.0 h1:pJdmNohVIJ97r4AUFtEXRXwESr8b0bD721u/Tz6k8PQ=
|
||||||
github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
|
github.com/getkin/kin-openapi v0.133.0/go.mod h1:boAciF6cXk5FhPqe/NQeBTeenbjqU4LhWBf09ILVvWE=
|
||||||
|
github.com/go-jose/go-jose/v3 v3.0.0 h1:s6rrhirfEP/CGIoc6p+PZAeogN2SxKav6Wp7+dyMWVo=
|
||||||
|
github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8=
|
||||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||||
@@ -40,9 +44,12 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
|
|||||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
@@ -117,6 +124,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
|||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
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/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
@@ -127,12 +135,16 @@ github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN
|
|||||||
github.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0=
|
github.com/woodsbury/decimal128 v1.3.0 h1:8pffMNWIlC0O5vbyHWFZAt5yWvWcrHA+3ovIIjVWss0=
|
||||||
github.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds=
|
github.com/woodsbury/decimal128 v1.3.0/go.mod h1:C5UTmyTjW3JftjUFzOVhC20BEQa2a4ZKOB5I6Zjb+ds=
|
||||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
||||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
||||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
@@ -140,13 +152,18 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
|
|||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
||||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||||
|
golang.org/x/oauth2 v0.15.0 h1:s8pnnxNVzjWyrvYdFUQq5llS1PX2zhPXmccZv99h7uQ=
|
||||||
|
golang.org/x/oauth2 v0.15.0/go.mod h1:q48ptWNTY5XWf+JNten23lcvHpLJ0ZSxF5ttTHKVCAM=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
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/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
@@ -163,6 +180,8 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
@@ -171,17 +190,21 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
|||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||||
|
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
@@ -190,6 +213,8 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi
|
|||||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||||
|
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
|||||||
@@ -0,0 +1,313 @@
|
|||||||
|
package authentication
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coreos/go-oidc/v3/oidc"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
|
||||||
|
"ruben/inventory2/internal/consts"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TODO: move these to a config?
|
||||||
|
const (
|
||||||
|
// The URL of our Auth0 Tenant Domain.
|
||||||
|
// If you're using a Custom Domain, be sure to set this to that value instead.
|
||||||
|
AUTH0_DOMAIN = "dev-uq3gqy5bdnwxmr6d.us.auth0.com"
|
||||||
|
|
||||||
|
// Our Auth0 application"s Client ID.
|
||||||
|
AUTH0_CLIENT_ID = "JEjrXTQ9fxlTLgp9RgTIACpUk8a2lqNT"
|
||||||
|
|
||||||
|
// Our Auth0 application"s Client Secret.
|
||||||
|
AUTH0_CLIENT_SECRET = "83U-iWdVaNnwk9XDzteo_2VMyOq_l1siKYqg1_2E7jCzgL8MnkaxlysPMcPMGlxA"
|
||||||
|
|
||||||
|
// The Callback URL of our application.
|
||||||
|
AUTH0_CALLBACK_URL = "https://inventory-plus-plus.com/login/callback"
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
// Authenticator is used to authenticate our users.
|
||||||
|
Authenticator struct {
|
||||||
|
*oidc.Provider
|
||||||
|
oauth2.Config
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
// AccessTokenClaims is the claims Auth0 provides in access tokens
|
||||||
|
AccessTokenClaims struct {
|
||||||
|
Audience string `json:"aud"`
|
||||||
|
Expires int64 `json:"exp"`
|
||||||
|
FamilyName string `json:"family_name"`
|
||||||
|
GivenName string `json:"given_name"`
|
||||||
|
IssuedAt int64 `json:"iat"`
|
||||||
|
Issuer string `json:"iss"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Nickname string `json:"nickname"`
|
||||||
|
Picture string `json:"picture"`
|
||||||
|
SessionID string `json:"sid"`
|
||||||
|
Subject string `json:"sub"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// New instantiates the *Authenticator.
|
||||||
|
func New(ctx context.Context, db *pgxpool.Pool) (*Authenticator, error) {
|
||||||
|
provider, err := oidc.NewProvider(
|
||||||
|
ctx,
|
||||||
|
"https://"+AUTH0_DOMAIN+"/",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Authenticator{
|
||||||
|
Provider: provider,
|
||||||
|
Config: oauth2.Config{
|
||||||
|
ClientID: AUTH0_CLIENT_ID,
|
||||||
|
ClientSecret: AUTH0_CLIENT_SECRET,
|
||||||
|
RedirectURL: AUTH0_CALLBACK_URL,
|
||||||
|
Endpoint: provider.Endpoint(),
|
||||||
|
Scopes: []string{oidc.ScopeOpenID, "profile"},
|
||||||
|
},
|
||||||
|
db: db,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken.
|
||||||
|
func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) {
|
||||||
|
rawIDToken, ok := token.Extra("id_token").(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("no id_token field in oauth2 token")
|
||||||
|
}
|
||||||
|
|
||||||
|
oidcConfig := &oidc.Config{
|
||||||
|
ClientID: a.ClientID,
|
||||||
|
}
|
||||||
|
|
||||||
|
return a.Verifier(oidcConfig).Verify(ctx, rawIDToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewState creates a new state for logging in, saving it in the database.
|
||||||
|
func (a *Authenticator) NewState(ctx context.Context) ([32]byte, error) {
|
||||||
|
state, err := generateRandomState()
|
||||||
|
if err != nil {
|
||||||
|
return state, fmt.Errorf("failed to generate random state: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = a.db.Exec(
|
||||||
|
ctx,
|
||||||
|
"INSERT INTO oauth_login_states (state) VALUES (@state)",
|
||||||
|
pgx.NamedArgs{
|
||||||
|
"state": state[:],
|
||||||
|
},
|
||||||
|
); err != nil {
|
||||||
|
return state, fmt.Errorf("failed to execute query: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return state, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateRandomState() ([32]byte, error) {
|
||||||
|
var b [32]byte
|
||||||
|
_, err := rand.Read(b[:])
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStateExpiration get's the oauth state's expiration
|
||||||
|
// func (a *Authenticator) GetStateExpiration(ctx context.Context, state [32]byte) (time.Time, error) {
|
||||||
|
func (a *Authenticator) GetStateExpiration(ctx context.Context, state string) (time.Time, error) {
|
||||||
|
rows, err := a.db.Query(
|
||||||
|
ctx,
|
||||||
|
`SELECT expiration from oauth_login_states WHERE state = ('\x' || @state)::BYTEA`,
|
||||||
|
pgx.NamedArgs{
|
||||||
|
//"state": state[:],
|
||||||
|
"state": state,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return time.Time{}, fmt.Errorf("failed to perform query: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
exp, err := pgx.CollectExactlyOneRow(rows, pgx.RowTo[time.Time])
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return time.Time{}, consts.ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return time.Time{}, fmt.Errorf("failed to scan row: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Authenticator) GetLogoutURL(requestHost string) *url.URL {
|
||||||
|
return &url.URL{
|
||||||
|
Scheme: "https",
|
||||||
|
Host: AUTH0_DOMAIN,
|
||||||
|
Path: "/v2/logout",
|
||||||
|
RawQuery: url.Values{
|
||||||
|
"returnTo": {
|
||||||
|
(&url.URL{
|
||||||
|
Scheme: "https",
|
||||||
|
Host: requestHost,
|
||||||
|
}).String(),
|
||||||
|
},
|
||||||
|
"client_id": {AUTH0_CLIENT_ID},
|
||||||
|
}.Encode(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Authenticator) Exchange(ctx context.Context, state, code string) (accessToken string, expiration time.Time, err error) {
|
||||||
|
// validate state
|
||||||
|
|
||||||
|
if exp, err := a.GetStateExpiration(ctx, state); errors.Is(err, consts.ErrNotFound) {
|
||||||
|
return "", time.Time{}, fmt.Errorf("invalid state: %w", consts.ErrNotFound)
|
||||||
|
} else if err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("failed to load state expiration: %w", err)
|
||||||
|
} else if exp.Before(time.Now()) {
|
||||||
|
return "", time.Time{}, fmt.Errorf("invalid state: state expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
// obtain token and profile
|
||||||
|
|
||||||
|
token, err := a.Config.Exchange(ctx, code)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("failed to exchange an authorization code for a token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("TOKEN:", token)
|
||||||
|
|
||||||
|
idToken, err := a.VerifyIDToken(ctx, token)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("failed to verify ID Token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("ID TOKEN:", idToken)
|
||||||
|
|
||||||
|
// claims []byte
|
||||||
|
|
||||||
|
var claims map[string]any
|
||||||
|
if err := idToken.Claims(&claims); err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("Failed to obtain id token claims: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("CUSTOM CLAIMS / PROFILE:", claims)
|
||||||
|
|
||||||
|
claimsJSON, _ := json.Marshal(claims)
|
||||||
|
|
||||||
|
if _, err := a.db.Exec(
|
||||||
|
ctx,
|
||||||
|
`
|
||||||
|
INSERT INTO oauth_tokens (
|
||||||
|
access_token,
|
||||||
|
token_type,
|
||||||
|
refresh_token,
|
||||||
|
expiry,
|
||||||
|
|
||||||
|
id_token_issuer,
|
||||||
|
id_token_audience,
|
||||||
|
id_token_subject,
|
||||||
|
id_token_expiry,
|
||||||
|
id_token_issued_at,
|
||||||
|
id_token_nonce,
|
||||||
|
id_token_access_token_hash,
|
||||||
|
|
||||||
|
claims
|
||||||
|
)
|
||||||
|
VALUES (
|
||||||
|
@access_token,
|
||||||
|
@token_type,
|
||||||
|
@refresh_token,
|
||||||
|
@expiry,
|
||||||
|
|
||||||
|
@id_token_issuer,
|
||||||
|
@id_token_audience,
|
||||||
|
@id_token_subject,
|
||||||
|
@id_token_expiry,
|
||||||
|
@id_token_issued_at,
|
||||||
|
@id_token_nonce,
|
||||||
|
@id_token_access_token_hash,
|
||||||
|
|
||||||
|
@claims
|
||||||
|
)
|
||||||
|
`,
|
||||||
|
pgx.NamedArgs{
|
||||||
|
"access_token": token.AccessToken,
|
||||||
|
"token_type": token.TokenType,
|
||||||
|
"refresh_token": token.RefreshToken,
|
||||||
|
"expiry": token.Expiry,
|
||||||
|
|
||||||
|
"id_token_issuer": idToken.Issuer,
|
||||||
|
"id_token_audience": pgtype.FlatArray[string](idToken.Audience),
|
||||||
|
"id_token_subject": idToken.Subject,
|
||||||
|
"id_token_expiry": idToken.Expiry,
|
||||||
|
"id_token_issued_at": idToken.IssuedAt,
|
||||||
|
"id_token_nonce": idToken.Nonce,
|
||||||
|
"id_token_access_token_hash": idToken.AccessTokenHash,
|
||||||
|
|
||||||
|
"claims": json.RawMessage(claimsJSON),
|
||||||
|
},
|
||||||
|
); err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("failed to perform query to save tokens: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return token.AccessToken, token.Expiry.UTC(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: need to automatically clean up expired tokens
|
||||||
|
func (a *Authenticator) DeleteOAuthTokens(ctx context.Context, accessToken string) error {
|
||||||
|
_, err := a.db.Exec(ctx, "DELETE FROM oauth_tokens WHERE access_token = @access_token", pgx.NamedArgs{"access_token": accessToken})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to perform query: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Authenticator) GetAccessTokenClaimsAndExpiration(ctx context.Context, accessToken string) (claims AccessTokenClaims, expiration time.Time, err error) {
|
||||||
|
rows, err := a.db.Query(
|
||||||
|
ctx,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
expiry,
|
||||||
|
claims
|
||||||
|
FROM
|
||||||
|
oauth_tokens
|
||||||
|
WHERE
|
||||||
|
access_token = @access_token
|
||||||
|
`,
|
||||||
|
pgx.NamedArgs{
|
||||||
|
"access_token": accessToken,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to perform query: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Row struct {
|
||||||
|
Expiry time.Time
|
||||||
|
Claims json.RawMessage
|
||||||
|
}
|
||||||
|
|
||||||
|
r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByNameLax[Row])
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return AccessTokenClaims{}, time.Time{}, consts.ErrNotFound
|
||||||
|
}
|
||||||
|
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to scan row: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(r.Claims, &claims); err != nil {
|
||||||
|
return AccessTokenClaims{}, time.Time{}, fmt.Errorf("failed to scan claims json: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return claims, r.Expiry, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package site
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"ruben/inventory2/internal/consts"
|
||||||
|
"ruben/inventory2/internal/domains/authentication"
|
||||||
|
)
|
||||||
|
|
||||||
|
// just keep this around long enough for testing auth middleware..
|
||||||
|
func (s *Server) testAuthEndpoint(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Println("SUCCESS:", getCustomClaims(r.Context()))
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
}
|
||||||
|
|
||||||
|
type customClaimsKey struct{}
|
||||||
|
|
||||||
|
// auth middleware to verify access_token cookie and set custom claims in the request context
|
||||||
|
func (s *Server) authenticate(h http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ck, err := r.Cookie("access_token")
|
||||||
|
if err != nil {
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
claims, expiration, err := s.auth.GetAccessTokenClaimsAndExpiration(ctx, ck.Value)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, consts.ErrNotFound) {
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
http.Error(w, fmt.Sprintf("failed to authenticate: %v", err), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if expiration.Before(time.Now()) {
|
||||||
|
deleteCookieInResponse(w, "access_token")
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.ServeHTTP(w, r.WithContext(context.WithValue(ctx, customClaimsKey{}, claims)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// get custom claims from request context
|
||||||
|
func getCustomClaims(ctx context.Context) authentication.AccessTokenClaims {
|
||||||
|
c, _ := ctx.Value(customClaimsKey{}).(authentication.AccessTokenClaims)
|
||||||
|
return c
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package site
|
||||||
|
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
func deleteCookieInResponse(w http.ResponseWriter, name string) {
|
||||||
|
w.Header().Set("Set-Cookie", (&http.Cookie{
|
||||||
|
Name: name,
|
||||||
|
Path: "/",
|
||||||
|
MaxAge: -1, // expire the cookie
|
||||||
|
}).String())
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package site
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GET /login
|
||||||
|
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
state, err := s.auth.NewState(ctx)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, fmt.Sprintf("failed to generate random state: %v", err), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
base64EncodedState := fmt.Sprintf("%x", state[:])
|
||||||
|
|
||||||
|
http.Redirect(w, r, s.auth.AuthCodeURL(base64EncodedState), http.StatusTemporaryRedirect)
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /login
|
||||||
|
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
email := r.FormValue("email")
|
||||||
|
if email == "" {
|
||||||
|
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
acct, err := s.accts.GetAccountByEmail(ctx, email)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, fmt.Sprintf("failed to create account: %v", err), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
//http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||||
|
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /login/callback
|
||||||
|
func (s *Server) loginCallback(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
q := r.URL.Query()
|
||||||
|
|
||||||
|
// obtain token and profile
|
||||||
|
|
||||||
|
accessToken, expiration, err := s.auth.Exchange(ctx, q.Get("state"), q.Get("code"))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Failed to exchange an authorization code for a token", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// set access_token cookie and redirect to a reasonable place
|
||||||
|
|
||||||
|
w.Header().Set("Set-Cookie", (&http.Cookie{
|
||||||
|
Name: "access_token",
|
||||||
|
Value: accessToken,
|
||||||
|
Path: "/",
|
||||||
|
Expires: expiration,
|
||||||
|
MaxAge: 0, // using Expiration instead
|
||||||
|
Secure: true,
|
||||||
|
SameSite: http.SameSiteStrictMode,
|
||||||
|
}).String())
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /logout
|
||||||
|
func (s *Server) logoutPage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
host := r.Header.Get("X-Forwarded-Host")
|
||||||
|
if host == "" {
|
||||||
|
host = r.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteCookieInResponse(w, "access_token")
|
||||||
|
|
||||||
|
if ck, err := r.Cookie("access_token"); err == nil && ck != nil {
|
||||||
|
if err := s.auth.DeleteOAuthTokens(r.Context(), ck.Value); err != nil {
|
||||||
|
fmt.Println("[ERROR] failed to delete auth token:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
http.Redirect(w, r, s.auth.GetLogoutURL(host).String(), http.StatusTemporaryRedirect)
|
||||||
|
}
|
||||||
+79
-171
@@ -5,79 +5,40 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/angelbeltran/templater"
|
"github.com/angelbeltran/templater"
|
||||||
|
|
||||||
"ruben/inventory2/internal/domains/accounts"
|
"ruben/inventory2/internal/domains/accounts"
|
||||||
|
"ruben/inventory2/internal/domains/authentication"
|
||||||
etsy_platform "ruben/inventory2/internal/domains/platforms/etsy"
|
etsy_platform "ruben/inventory2/internal/domains/platforms/etsy"
|
||||||
"ruben/inventory2/internal/domains/raw_events"
|
"ruben/inventory2/internal/domains/raw_events"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewSiteHandler(
|
type Server struct {
|
||||||
dir string,
|
mux *http.ServeMux
|
||||||
|
contentDir string
|
||||||
|
templater *templater.Templater
|
||||||
|
rawEvents *raw_events.Store
|
||||||
|
accts *accounts.Store
|
||||||
|
etsy *etsy_platform.Platform
|
||||||
|
auth *authentication.Authenticator
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewServer(
|
||||||
|
contentDir string,
|
||||||
rawEvents *raw_events.Store,
|
rawEvents *raw_events.Store,
|
||||||
accts *accounts.Store,
|
accts *accounts.Store,
|
||||||
etsy *etsy_platform.Platform,
|
etsy *etsy_platform.Platform,
|
||||||
) http.Handler {
|
auth *authentication.Authenticator,
|
||||||
mux := http.NewServeMux()
|
) *Server {
|
||||||
|
s := &Server{
|
||||||
// api routes
|
mux: http.NewServeMux(),
|
||||||
|
contentDir: contentDir,
|
||||||
mux.HandleFunc("POST /accounts", func(w http.ResponseWriter, r *http.Request) {
|
templater: templater.NewTemplater(
|
||||||
ctx := r.Context()
|
contentDir+"/templates",
|
||||||
email := r.FormValue("email")
|
|
||||||
if email == "" {
|
|
||||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
acct, err := accts.CreateAccount(ctx, email)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, fmt.Sprintf("failed to create account: %w", err), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
|
||||||
})
|
|
||||||
|
|
||||||
mux.HandleFunc("POST /log-in", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
ctx := r.Context()
|
|
||||||
email := r.FormValue("email")
|
|
||||||
if email == "" {
|
|
||||||
http.Error(w, "no email provided", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
acct, err := accts.GetAccountByEmail(ctx, email)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, fmt.Sprintf("failed to create account: %w", err), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
|
||||||
})
|
|
||||||
|
|
||||||
// non-html routes
|
|
||||||
|
|
||||||
scfs := http.FileServer(http.Dir(dir + "/scripts"))
|
|
||||||
mux.Handle("/scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "text/javascript")
|
|
||||||
if path.Ext(r.URL.Path) == ".gz" {
|
|
||||||
w.Header().Set("Content-Encoding", "gzip")
|
|
||||||
}
|
|
||||||
scfs.ServeHTTP(w, r)
|
|
||||||
})))
|
|
||||||
mux.Handle("/styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(dir+"/styles"))))
|
|
||||||
|
|
||||||
// html page routes
|
|
||||||
|
|
||||||
tmplr := templater.NewTemplater(
|
|
||||||
dir+"/templates",
|
|
||||||
func() template.FuncMap {
|
func() template.FuncMap {
|
||||||
return template.FuncMap{
|
return template.FuncMap{
|
||||||
"buildSitePath": func(parts ...any) string {
|
"buildSitePath": func(parts ...any) string {
|
||||||
@@ -87,7 +48,8 @@ func NewSiteHandler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: make "/site" dynamic somehow
|
// TODO: make "/site" dynamic somehow
|
||||||
return path.Join(append([]string{"/site"}, strParts...)...)
|
//return path.Join(append([]string{"/site"}, strParts...)...)
|
||||||
|
return path.Join(strParts...)
|
||||||
},
|
},
|
||||||
"splitPath": func(p string) []string {
|
"splitPath": func(p string) []string {
|
||||||
if p == "" {
|
if p == "" {
|
||||||
@@ -119,120 +81,66 @@ func NewSiteHandler(
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
),
|
||||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
rawEvents: rawEvents,
|
||||||
|
accts: accts,
|
||||||
|
etsy: etsy,
|
||||||
|
auth: auth,
|
||||||
|
}
|
||||||
|
|
||||||
|
// api routes
|
||||||
|
|
||||||
|
s.mux.HandleFunc("GET /login", s.loginPage)
|
||||||
|
s.mux.HandleFunc("GET /login/callback", s.loginCallback)
|
||||||
|
s.mux.HandleFunc("GET /logout", s.logoutPage)
|
||||||
|
|
||||||
|
// TODO: eliminate once no longer used.
|
||||||
|
s.mux.HandleFunc("POST /login", s.login)
|
||||||
|
|
||||||
|
// TODO: when a user is created, we should make an account for them that is associated with their openid subject.
|
||||||
|
// - then this can go away
|
||||||
|
s.mux.HandleFunc("POST /accounts", s.createAccount)
|
||||||
|
|
||||||
|
// TODO: test the new auth middleware
|
||||||
|
s.mux.Handle("GET /test-auth", s.authenticate(http.HandlerFunc(s.testAuthEndpoint)))
|
||||||
|
|
||||||
|
// webpage content
|
||||||
|
|
||||||
|
scfs := http.FileServer(http.Dir(contentDir + "/scripts"))
|
||||||
|
s.mux.Handle("GET /scripts/", http.StripPrefix("/scripts", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/javascript")
|
||||||
|
if path.Ext(r.URL.Path) == ".gz" {
|
||||||
|
w.Header().Set("Content-Encoding", "gzip")
|
||||||
|
}
|
||||||
|
scfs.ServeHTTP(w, r)
|
||||||
|
})))
|
||||||
|
s.mux.Handle("GET /styles/", http.StripPrefix("/styles", http.FileServer(http.Dir(contentDir+"/styles"))))
|
||||||
|
|
||||||
|
s.mux.HandleFunc("GET /", s.serveTemplates)
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// http.Handler implementation
|
||||||
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.mux.ServeHTTP(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /accounts
|
||||||
|
func (s *Server) createAccount(w http.ResponseWriter, r *http.Request) {
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
name, pathParams := getPageTemplateNameForURL(r.URL)
|
email := r.FormValue("email")
|
||||||
b, err := tmplr.ExecutePage(
|
if email == "" {
|
||||||
name,
|
http.Error(w, "no email provided", http.StatusBadRequest)
|
||||||
"Request",
|
|
||||||
r,
|
|
||||||
// add services here
|
|
||||||
"RawEvents",
|
|
||||||
rawEvents.WithContext(ctx),
|
|
||||||
"URLCalc",
|
|
||||||
newURLCalculator(r.URL),
|
|
||||||
"PathParams",
|
|
||||||
pathParams,
|
|
||||||
"Accounts",
|
|
||||||
accts.WithContext(ctx),
|
|
||||||
"Etsy",
|
|
||||||
etsy.WithContext(ctx),
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
// TODO: handle 'not found' as a 404?
|
|
||||||
fmt.Println("[ERROR]: failed to load or parse layout template:", err)
|
|
||||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Write(b)
|
acct, err := s.accts.CreateAccount(ctx, email)
|
||||||
})
|
if err != nil {
|
||||||
|
http.Error(w, fmt.Sprintf("failed to create account: %v", err), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
return mux
|
//http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||||
}
|
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acct.ID), http.StatusSeeOther)
|
||||||
|
|
||||||
// TODO: clean this up...
|
|
||||||
// TODO: somehow tell what the path params are and pass them up.
|
|
||||||
// - then consider pushing this functionality into the template library.
|
|
||||||
//
|
|
||||||
// getPageTemplateNameForURL eliminate any trailing .html or /, and checks for any
|
|
||||||
// file with path parameters in the name, eg '{abc}.html.tmpl', prefering exact filename matches.
|
|
||||||
func getPageTemplateNameForURL(u *url.URL) (name string, params map[string]string) {
|
|
||||||
fp := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(u.Path, ".html"), "/"), "/")
|
|
||||||
if fp == "" {
|
|
||||||
// "/" maps to "/index"
|
|
||||||
fp = "index"
|
|
||||||
}
|
|
||||||
|
|
||||||
fpParts := strings.Split(fp, "/")
|
|
||||||
res := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(fpParts)
|
|
||||||
for _, combs := range res {
|
|
||||||
const pageBodiesPrefix = "internal/site/templates/page_bodies"
|
|
||||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...)) + ".html.tmpl"
|
|
||||||
|
|
||||||
matches, _ := filepath.Glob(pattern)
|
|
||||||
if len(matches) == 0 {
|
|
||||||
pattern := path.Join(pageBodiesPrefix, path.Join(combs...), "index") + ".html.tmpl"
|
|
||||||
matches, _ = filepath.Glob(pattern)
|
|
||||||
}
|
|
||||||
if len(matches) > 0 {
|
|
||||||
match := matches[0]
|
|
||||||
name = strings.TrimPrefix(strings.TrimSuffix(match, ".html.tmpl"), pageBodiesPrefix+"/")
|
|
||||||
|
|
||||||
patternParts := strings.Split(name, "/")
|
|
||||||
params = make(map[string]string)
|
|
||||||
for i, pp := range patternParts {
|
|
||||||
if strings.HasPrefix(pp, "{") && strings.HasSuffix(pp, "}") {
|
|
||||||
params[pp[1:len(pp)-1]] = fpParts[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return name, params
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return fp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts []string) [][]string {
|
|
||||||
switch len(filepathParts) {
|
|
||||||
case 0:
|
|
||||||
return nil
|
|
||||||
case 1:
|
|
||||||
return [][]string{
|
|
||||||
[]string{filepathParts[0]},
|
|
||||||
[]string{"{*}"},
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
tailCombs := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts[1:])
|
|
||||||
|
|
||||||
combs := make([][]string, 2*len(tailCombs))
|
|
||||||
for i, c := range tailCombs {
|
|
||||||
combs[i*2] = append([]string{filepathParts[0]}, c...)
|
|
||||||
combs[i*2+1] = append([]string{"{*}"}, c...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return combs
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type URLCalculator struct {
|
|
||||||
url *url.URL
|
|
||||||
}
|
|
||||||
|
|
||||||
func newURLCalculator(u *url.URL) URLCalculator {
|
|
||||||
cpy := *u
|
|
||||||
return URLCalculator{
|
|
||||||
url: &cpy,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c URLCalculator) SetQueryParam(k string, v any) string {
|
|
||||||
u := *c.url
|
|
||||||
q := u.Query()
|
|
||||||
q.Set(k, fmt.Sprint(v))
|
|
||||||
u.RawQuery = q.Encode()
|
|
||||||
|
|
||||||
return u.String()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package site
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GET /
|
||||||
|
func (s *Server) serveTemplates(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
name, pathParams := getPageTemplateNameForURL(r.URL)
|
||||||
|
b, err := s.templater.ExecutePage(
|
||||||
|
name,
|
||||||
|
"Request",
|
||||||
|
r,
|
||||||
|
// add services here
|
||||||
|
"RawEvents",
|
||||||
|
s.rawEvents.WithContext(ctx),
|
||||||
|
"URLCalc",
|
||||||
|
newURLCalculator(r.URL),
|
||||||
|
"PathParams",
|
||||||
|
pathParams,
|
||||||
|
"Accounts",
|
||||||
|
s.accts.WithContext(ctx),
|
||||||
|
"Etsy",
|
||||||
|
s.etsy.WithContext(ctx),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
// TODO: handle 'not found' as a 404?
|
||||||
|
fmt.Println("[ERROR]: failed to load or parse layout template:", err)
|
||||||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: clean this up...
|
||||||
|
// TODO: somehow tell what the path params are and pass them up.
|
||||||
|
// - then consider pushing this functionality into the template library.
|
||||||
|
//
|
||||||
|
// getPageTemplateNameForURL eliminate any trailing .html or /, and checks for any
|
||||||
|
// file with path parameters in the name, eg '{abc}.html.tmpl', prefering exact filename matches.
|
||||||
|
func getPageTemplateNameForURL(u *url.URL) (name string, params map[string]string) {
|
||||||
|
fp := strings.TrimPrefix(strings.TrimSuffix(strings.TrimSuffix(u.Path, ".html"), "/"), "/")
|
||||||
|
if fp == "" {
|
||||||
|
// "/" maps to "/index"
|
||||||
|
fp = "index"
|
||||||
|
}
|
||||||
|
|
||||||
|
fpParts := strings.Split(fp, "/")
|
||||||
|
res := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(fpParts)
|
||||||
|
for _, combs := range res {
|
||||||
|
const pageBodiesPrefix = "internal/site/templates/page_bodies"
|
||||||
|
pattern := path.Join(pageBodiesPrefix, path.Join(combs...)) + ".html.tmpl"
|
||||||
|
|
||||||
|
matches, _ := filepath.Glob(pattern)
|
||||||
|
if len(matches) == 0 {
|
||||||
|
pattern := path.Join(pageBodiesPrefix, path.Join(combs...), "index") + ".html.tmpl"
|
||||||
|
matches, _ = filepath.Glob(pattern)
|
||||||
|
}
|
||||||
|
if len(matches) > 0 {
|
||||||
|
match := matches[0]
|
||||||
|
name = strings.TrimPrefix(strings.TrimSuffix(match, ".html.tmpl"), pageBodiesPrefix+"/")
|
||||||
|
|
||||||
|
patternParts := strings.Split(name, "/")
|
||||||
|
params = make(map[string]string)
|
||||||
|
for i, pp := range patternParts {
|
||||||
|
if strings.HasPrefix(pp, "{") && strings.HasSuffix(pp, "}") {
|
||||||
|
params[pp[1:len(pp)-1]] = fpParts[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return name, params
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts []string) [][]string {
|
||||||
|
switch len(filepathParts) {
|
||||||
|
case 0:
|
||||||
|
return nil
|
||||||
|
case 1:
|
||||||
|
return [][]string{
|
||||||
|
[]string{filepathParts[0]},
|
||||||
|
[]string{"{*}"},
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
tailCombs := getMatchingGlobPatternsCapturingFilepathIncludingParametrizedFilepaths(filepathParts[1:])
|
||||||
|
|
||||||
|
combs := make([][]string, 2*len(tailCombs))
|
||||||
|
for i, c := range tailCombs {
|
||||||
|
combs[i*2] = append([]string{filepathParts[0]}, c...)
|
||||||
|
combs[i*2+1] = append([]string{"{*}"}, c...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return combs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type URLCalculator struct {
|
||||||
|
url *url.URL
|
||||||
|
}
|
||||||
|
|
||||||
|
func newURLCalculator(u *url.URL) URLCalculator {
|
||||||
|
cpy := *u
|
||||||
|
return URLCalculator{
|
||||||
|
url: &cpy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c URLCalculator) SetQueryParam(k string, v any) string {
|
||||||
|
u := *c.url
|
||||||
|
q := u.Query()
|
||||||
|
q.Set(k, fmt.Sprint(v))
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
@@ -1,22 +1,28 @@
|
|||||||
<nav>
|
<nav>
|
||||||
<ul>
|
<ul>
|
||||||
<li>
|
<li>
|
||||||
<a href="{{ buildSitePath }}">
|
<a href="/">
|
||||||
Home
|
Home
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<li>
|
<li>
|
||||||
<a href="{{ buildSitePath "sign-up" }}">
|
<a href="/sign-up">
|
||||||
Sign Up
|
Sign Up
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
<li>
|
<li>
|
||||||
<a href="{{ buildSitePath "log-in" }}">
|
<a href="/login">
|
||||||
Log In
|
Log In
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|
||||||
|
<li>
|
||||||
|
<a href="/logout">
|
||||||
|
Log Out
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,10 @@
|
|||||||
<head>
|
<head>
|
||||||
<title>WIP</title>
|
<title>WIP</title>
|
||||||
|
|
||||||
<link rel="stylesheet" href="/site/styles/index.css">
|
<link rel="stylesheet" href="/styles/index.css">
|
||||||
|
|
||||||
<script src="/site/scripts/htmx.min.js.gz"></script>
|
<script src="/scripts/htmx.min.js.gz"></script>
|
||||||
<script src="/site/scripts/_hyperscript.min.js.gz"></script>
|
<script src="/scripts/_hyperscript.min.js.gz"></script>
|
||||||
|
|
||||||
{{/* This is where the page_head template will be inserted into the page */}}
|
{{/* This is where the page_head template will be inserted into the page */}}
|
||||||
{{- block "head" . }}{{ end }}
|
{{- block "head" . }}{{ end }}
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
{{ componentBody "nav_bar" }}
|
{{ componentBody "nav_bar" }}
|
||||||
|
|
||||||
|
|
||||||
<h1>Account: {{ .PathParams.acctID }}</h1>
|
|
||||||
|
|
||||||
{{- $acctID := parseInt64 .PathParams.acctID }}
|
{{- $acctID := parseInt64 .PathParams.acctID }}
|
||||||
|
{{- $acct := (.Accounts.GetAccount $acctID) }}
|
||||||
|
|
||||||
Email: {{ (.Accounts.GetAccount $acctID).Email }}
|
<h1>Account: {{ $acct.Email }} (id: {{ $acctID }})</h1>
|
||||||
|
|
||||||
{{- $etsyUser := .Etsy.GetUserPointerByAccountID $acctID }}
|
{{- $etsyUser := .Etsy.GetUserPointerByAccountID $acctID }}
|
||||||
{{- if $etsyUser }}
|
{{- if $etsyUser }}
|
||||||
|
|||||||
@@ -2,4 +2,6 @@
|
|||||||
|
|
||||||
<h1>Home</h1>
|
<h1>Home</h1>
|
||||||
|
|
||||||
<h2><a href="sign-up">Sign Up!</a></h2>
|
<h2><a href="/sign-up">Sign Up!</a></h2>
|
||||||
|
|
||||||
|
<h2><a href="/test-auth">Test Auth</a></h2>
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<h1>Log In</h1>
|
<h1>Log In</h1>
|
||||||
|
|
||||||
<form action="log-in" method="post">
|
<form action="login" method="post">
|
||||||
<label>
|
<label>
|
||||||
Email:
|
Email:
|
||||||
<input type="text" required name="email" />
|
<input type="text" required name="email" />
|
||||||
@@ -102,7 +102,7 @@ func NewWebhookHandler(
|
|||||||
|
|
||||||
// TODO: response with a redirect to the user's account page (SUCCESS - new sign up or login)!
|
// TODO: response with a redirect to the user's account page (SUCCESS - new sign up or login)!
|
||||||
|
|
||||||
http.Redirect(w, r, fmt.Sprintf("/site/accounts/%d", acctID), http.StatusSeeOther)
|
http.Redirect(w, r, fmt.Sprintf("/accounts/%d", acctID), http.StatusSeeOther)
|
||||||
})
|
})
|
||||||
|
|
||||||
return mux
|
return mux
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
"ruben/inventory2/internal/domains/accounts"
|
"ruben/inventory2/internal/domains/accounts"
|
||||||
|
"ruben/inventory2/internal/domains/authentication"
|
||||||
etsy_platform "ruben/inventory2/internal/domains/platforms/etsy"
|
etsy_platform "ruben/inventory2/internal/domains/platforms/etsy"
|
||||||
"ruben/inventory2/internal/domains/raw_events"
|
"ruben/inventory2/internal/domains/raw_events"
|
||||||
"ruben/inventory2/internal/site"
|
"ruben/inventory2/internal/site"
|
||||||
@@ -49,7 +50,12 @@ func runApp(ctx context.Context) error {
|
|||||||
|
|
||||||
// start http server
|
// start http server
|
||||||
|
|
||||||
srvErrCh := runServer(ctx, connPool)
|
auth, err := authentication.New(ctx, connPool)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to construct authenticator: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srvErrCh := runServer(ctx, connPool, auth)
|
||||||
|
|
||||||
// wait for interrupt signal or unrecoverable failure, then shutdown
|
// wait for interrupt signal or unrecoverable failure, then shutdown
|
||||||
|
|
||||||
@@ -85,10 +91,10 @@ func runApp(ctx context.Context) error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func runServer(ctx context.Context, connPool *pgxpool.Pool) <-chan error {
|
func runServer(ctx context.Context, connPool *pgxpool.Pool, auth *authentication.Authenticator) <-chan error {
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: ":8082", // local
|
Addr: ":8082", // local
|
||||||
Handler: buildHTTPHandler(connPool),
|
Handler: buildHTTPHandler(connPool, auth),
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
@@ -139,7 +145,7 @@ func runServer(ctx context.Context, connPool *pgxpool.Pool) <-chan error {
|
|||||||
return errCh
|
return errCh
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildHTTPHandler(connPool *pgxpool.Pool) http.Handler {
|
func buildHTTPHandler(connPool *pgxpool.Pool, auth *authentication.Authenticator) http.Handler {
|
||||||
eventsDB := raw_events.NewStore(connPool)
|
eventsDB := raw_events.NewStore(connPool)
|
||||||
etsy := etsy_platform.NewPlatform(
|
etsy := etsy_platform.NewPlatform(
|
||||||
func(acctID int64) string {
|
func(acctID int64) string {
|
||||||
@@ -158,8 +164,7 @@ func buildHTTPHandler(connPool *pgxpool.Pool) http.Handler {
|
|||||||
OAuthRedirectURIWithAcctIDParam: "/oauth/account/{acctID}/auth_code",
|
OAuthRedirectURIWithAcctIDParam: "/oauth/account/{acctID}/auth_code",
|
||||||
},
|
},
|
||||||
})))
|
})))
|
||||||
mux.Handle("/site/", http.StripPrefix("/site", site.NewSiteHandler("./internal/site", eventsDB, accts, etsy)))
|
mux.Handle("/", site.NewServer("./internal/site", eventsDB, accts, etsy, auth))
|
||||||
mux.Handle("/", http.RedirectHandler("/site", http.StatusPermanentRedirect))
|
|
||||||
|
|
||||||
return mux
|
return mux
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user