From eb2ff2ab23a70298c65f19d52b76c794b2f4937c Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 11:33:06 +0100 Subject: Some more messing around with oauth2 --- internal/api/server.go | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'internal/api/server.go') diff --git a/internal/api/server.go b/internal/api/server.go index 8af9e75fa..9073618f0 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -19,16 +19,13 @@ package api import ( - "net/http" - "github.com/gin-gonic/gin" "github.com/gotosocial/gotosocial/internal/config" "github.com/sirupsen/logrus" ) type Server interface { - AttachHTTPHandler(method string, path string, handler http.HandlerFunc) - AttachGinHandler(method string, path string, handler gin.HandlerFunc) + AttachHandler(method string, path string, handler gin.HandlerFunc) // AttachMiddleware(handler gin.HandlerFunc) GetAPIGroup() *gin.RouterGroup Start() @@ -60,12 +57,12 @@ func (s *server) Stop() { // todo: shut down gracefully } -func (s *server) AttachHTTPHandler(method string, path string, handler http.HandlerFunc) { - s.engine.Handle(method, path, gin.WrapH(handler)) -} - -func (s *server) AttachGinHandler(method string, path string, handler gin.HandlerFunc) { - s.engine.Handle(method, path, handler) +func (s *server) AttachHandler(method string, path string, handler gin.HandlerFunc) { + if method == "ANY" { + s.engine.Any(path, handler) + } else { + s.engine.Handle(method, path, handler) + } } func New(config *config.Config, logger *logrus.Logger) Server { -- cgit v1.2.3 From 9d5fb0785f80fddd3b4193aae25c4b1ee96eb7fa Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 13:14:52 +0100 Subject: fiddling --- go.mod | 1 + go.sum | 26 ++++++++++++++++++++++++++ internal/api/server.go | 4 ++++ internal/oauth/oauth.go | 19 ++++++++----------- 4 files changed, 39 insertions(+), 11 deletions(-) (limited to 'internal/api/server.go') diff --git a/go.mod b/go.mod index daa784905..75b82ea18 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/gotosocial/gotosocial go 1.16 require ( + github.com/gin-contrib/sessions v0.0.3 // indirect github.com/gin-gonic/gin v1.6.3 github.com/go-fed/activity v1.0.0 github.com/go-pg/pg/extra/pgdebug v0.2.0 diff --git a/go.sum b/go.sum index f86cc7417..6edb85cb4 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,9 @@ github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU= github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= github.com/andybalholm/brotli v1.0.0 h1:7UCwP93aiSfvWpapti8g88vVVGp2qqtGyePsSuDafo4= github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff/go.mod h1:+RTT1BOk5P97fT2CiHkbFQwkK3mjsFAP6zCYV2aXtjw= +github.com/bradfitz/gomemcache v0.0.0-20190329173943-551aad21a668/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA= +github.com/bradleypeabody/gorilla-sessions-memcache v0.0.0-20181103040241-659414f458e1/go.mod h1:dkChI7Tbtx7H1Tj7TqGSZMOeGpMP5gLHtjroHd4agiI= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= @@ -24,10 +27,14 @@ 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/gavv/httpexpect v2.0.0+incompatible h1:1X9kcRshkSKEjNJJxX9Y9mQ5BRfbxU5kORdjhlA1yX8= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= +github.com/gin-contrib/sessions v0.0.3 h1:PoBXki+44XdJdlgDqDrY5nDVe3Wk7wDV/UCOuLP6fBI= +github.com/gin-contrib/sessions v0.0.3/go.mod h1:8C/J6cad3Il1mWYYgtw0w+hqasmpvy25mPkXdOgeB9I= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do= github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q= github.com/go-fed/activity v1.0.0 h1:j7w3auHZnVCjUcgA1mE+UqSOjFBhvW2Z2res3vNol+o= github.com/go-fed/activity v1.0.0/go.mod h1:v4QoPaAzjWZ8zN2VFVGL5ep9C02mst0hQYHUpQwso4Q= github.com/go-fed/httpsig v0.1.1-0.20190914113940-c2de3672e5b5 h1:WLvFZqoXnuVTBKA6U/1FnEHNQ0Rq0QM0rGhY8Tx6R1g= @@ -41,8 +48,10 @@ github.com/go-pg/zerochecker v0.2.0 h1:pp7f72c3DobMWOb2ErtZsnrPaSvHd2W4o9//8HtF4 github.com/go-pg/zerochecker v0.2.0/go.mod h1:NJZ4wKL0NmTtz0GKCoJ8kym6Xn/EQzXRl2OnAe7MmDo= github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM= github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= @@ -70,6 +79,7 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 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= @@ -86,6 +96,13 @@ github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= +github.com/gorilla/sessions v1.1.3 h1:uXoZdcdA5XdXF3QzuSlheVRUvjl+1rKY7zBXL68L9RU= +github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210315164102-1f7842217e57 h1:+zKsBEkg1cbz7zJDms1KMU9vJBeBAlElS1SbK/x0Rvc= @@ -97,11 +114,13 @@ github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= +github.com/kidstuff/mongostore v0.0.0-20181113001930-e650cd85ee4b/go.mod h1:g2nVr8KZVXJSS97Jo8pJ0jgq29P6H7dG0oplUA86MQw= github.com/klauspost/compress v1.10.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.10.10 h1:a/y8CglcM7gLGYmlbP/stPE5sR3hbhFRUjCBfd/0B3I= github.com/klauspost/compress v1.10.10/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= @@ -111,13 +130,16 @@ github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfn github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= github.com/magefile/mage v1.10.0 h1:3HiXzCUY12kh9bIuyXShaVe529fJfyqoVM42o/uom2g= github.com/magefile/mage v1.10.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A= github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/memcachier/mc v2.0.1+incompatible/go.mod h1:7bkvFE61leUBvXz+yxsOnGBQSZpBSPIMUQSmmSHvuXc= 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 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg= @@ -141,6 +163,7 @@ github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7 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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/quasoft/memstore v0.0.0-20180925164028-84a050167438/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= @@ -281,6 +304,7 @@ golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -343,6 +367,8 @@ gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= +gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/internal/api/server.go b/internal/api/server.go index 9073618f0..0cfe23531 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -19,6 +19,8 @@ package api import ( + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" "github.com/gotosocial/gotosocial/internal/config" "github.com/sirupsen/logrus" @@ -67,6 +69,8 @@ func (s *server) AttachHandler(method string, path string, handler gin.HandlerFu func New(config *config.Config, logger *logrus.Logger) Server { engine := gin.New() + store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-key")) + engine.Use(sessions.Sessions("mysession", store)) return &server{ APIGroup: engine.Group("/api").Group("/v1"), logger: logger, diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index d877022d9..94258b806 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -20,10 +20,12 @@ package oauth import ( "bytes" + "fmt" "net/http" "net/url" "time" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/go-pg/pg/v10" "github.com/go-session/session" @@ -75,7 +77,7 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L } func (a *API) AddRoutes(s api.Server) error { - s.AttachHandler(methodAny, "/auth/sign_in", gin.WrapF(a.SignInHandler)) + s.AttachHandler(methodAny, "/auth/sign_in", a.SignInHandler) s.AttachHandler(methodAny, "/oauth/token", gin.WrapF(a.TokenHandler)) s.AttachHandler(methodAny, "/oauth/authorize", gin.WrapF(a.AuthorizeHandler)) s.AttachHandler(methodAny, "/auth", gin.WrapF(a.AuthHandler)) @@ -93,13 +95,8 @@ func incorrectPassword() (string, error) { // SignInHandler should be served at https://example.org/auth/sign_in. // The idea is to present a sign in page to the user, where they can enter their username and password. // The handler will then redirect to the auth handler served at /auth -func (a *API) SignInHandler(w http.ResponseWriter, r *http.Request) { - store, err := session.Start(r.Context(), w, r) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - +func (a *API) SignInHandler(c *gin.Context) { + s := sessions.Default(c) if r.Method == "POST" { if r.Form == nil { if err := r.ParseForm(); err != nil { @@ -107,8 +104,8 @@ func (a *API) SignInHandler(w http.ResponseWriter, r *http.Request) { return } } - store.Set("username", r.Form.Get("username")) - store.Save() + s.Set("username", r.Form.Get("username")) + s.Save() w.Header().Set("Location", "/auth") w.WriteHeader(http.StatusFound) @@ -171,7 +168,7 @@ func (a *API) AuthHandler(w http.ResponseWriter, r *http.Request) { } /* - SUB-HANDLERS -- don't serve these directly + SUB-HANDLERS -- don't serve these directly, they should be attached to the oauth2 server */ // PasswordAuthorizationHandler takes a username (in this case, we use an email address) -- cgit v1.2.3 From 6eab00e05e6e65a2b8fc738ae25be5fa6c5283b3 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Wed, 17 Mar 2021 16:01:31 +0100 Subject: getting there....... --- go.mod | 4 +- go.sum | 3 +- internal/api/server.go | 4 +- internal/oauth/oauth.go | 194 +++++++++++++++++++++-------------- internal/oauth/oauth_test.go | 39 ++++--- internal/oauth/pgclientstore.go | 13 ++- internal/oauth/pgclientstore_test.go | 1 - internal/oauth/pgtokenstore.go | 33 ++++-- 8 files changed, 180 insertions(+), 111 deletions(-) (limited to 'internal/api/server.go') diff --git a/go.mod b/go.mod index 75b82ea18..6f1ede9ed 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,12 @@ module github.com/gotosocial/gotosocial go 1.16 require ( - github.com/gin-contrib/sessions v0.0.3 // indirect + github.com/gin-contrib/sessions v0.0.3 github.com/gin-gonic/gin v1.6.3 github.com/go-fed/activity v1.0.0 github.com/go-pg/pg/extra/pgdebug v0.2.0 github.com/go-pg/pg/v10 v10.8.0 - github.com/go-session/session v3.1.2+incompatible // indirect + github.com/go-session/session v3.1.2+incompatible github.com/golang/mock v1.4.4 // indirect github.com/google/uuid v1.2.0 // indirect github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 diff --git a/go.sum b/go.sum index 6edb85cb4..f482187af 100644 --- a/go.sum +++ b/go.sum @@ -105,8 +105,6 @@ github.com/gorilla/sessions v1.1.3 h1:uXoZdcdA5XdXF3QzuSlheVRUvjl+1rKY7zBXL68L9R github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gotosocial/oauth2/v4 v4.2.1-0.20210315164102-1f7842217e57 h1:+zKsBEkg1cbz7zJDms1KMU9vJBeBAlElS1SbK/x0Rvc= -github.com/gotosocial/oauth2/v4 v4.2.1-0.20210315164102-1f7842217e57/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 h1:YJ//HmHOYJ4srm/LA6VPNjNisneMbY6TTM1xttV/ZQU= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= @@ -163,6 +161,7 @@ github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7 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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/quasoft/memstore v0.0.0-20180925164028-84a050167438 h1:jnz/4VenymvySjE+Ez511s0pqVzkUOmr1fwCVytNNWk= github.com/quasoft/memstore v0.0.0-20180925164028-84a050167438/go.mod h1:wTPjTepVu7uJBYgZ0SdWHQlIas582j6cn2jgk4DDdlg= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= diff --git a/internal/api/server.go b/internal/api/server.go index 0cfe23531..321c932cd 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -69,8 +69,8 @@ func (s *server) AttachHandler(method string, path string, handler gin.HandlerFu func New(config *config.Config, logger *logrus.Logger) Server { engine := gin.New() - store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-key")) - engine.Use(sessions.Sessions("mysession", store)) + store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-keyencryption-key----")) + engine.Use(sessions.Sessions("gotosocial-session", store)) return &server{ APIGroup: engine.Group("/api").Group("/v1"), logger: logger, diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 94258b806..d1f3bcf54 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -19,16 +19,12 @@ package oauth import ( - "bytes" - "fmt" "net/http" "net/url" - "time" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/go-pg/pg/v10" - "github.com/go-session/session" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/gtsmodel" "github.com/gotosocial/oauth2/v4" @@ -48,6 +44,19 @@ type API struct { log *logrus.Logger } +type login struct { + Username string `form:"username"` + Password string `form:"password"` +} + +type authorize struct { + ForceLogin string `form:"force_login,omitempty"` + ResponseType string `form:"response_type"` + ClientID string `form:"client_id"` + RedirectURI string `form:"redirect_uri"` + Scope string `form:"scope,omitempty"` +} + func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.Logger) *API { manager := manage.NewDefaultManager() manager.MapTokenStorage(ts) @@ -77,10 +86,11 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L } func (a *API) AddRoutes(s api.Server) error { - s.AttachHandler(methodAny, "/auth/sign_in", a.SignInHandler) - s.AttachHandler(methodAny, "/oauth/token", gin.WrapF(a.TokenHandler)) - s.AttachHandler(methodAny, "/oauth/authorize", gin.WrapF(a.AuthorizeHandler)) - s.AttachHandler(methodAny, "/auth", gin.WrapF(a.AuthHandler)) + s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) + s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) + s.AttachHandler(methodAny, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeHandler) + s.AttachHandler(methodAny, "/auth", a.AuthHandler) return nil } @@ -92,78 +102,132 @@ func incorrectPassword() (string, error) { MAIN HANDLERS -- serve these through a server/router */ -// SignInHandler should be served at https://example.org/auth/sign_in. +// SignInGETHandler should be served at https://example.org/auth/sign_in. +// The idea is to present a sign in page to the user, where they can enter their username and password. +// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler +func (a *API) SignInGETHandler(c *gin.Context) { + c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(signInHTML)) +} + +// SignInPOSTHandler should be served at https://example.org/auth/sign_in. // The idea is to present a sign in page to the user, where they can enter their username and password. // The handler will then redirect to the auth handler served at /auth -func (a *API) SignInHandler(c *gin.Context) { +func (a *API) SignInPOSTHandler(c *gin.Context) { s := sessions.Default(c) - if r.Method == "POST" { - if r.Form == nil { - if err := r.ParseForm(); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - } - s.Set("username", r.Form.Get("username")) - s.Save() - - w.Header().Set("Location", "/auth") - w.WriteHeader(http.StatusFound) + form := &login{} + if err := c.ShouldBind(form); err != nil || form.Username == "" || form.Password == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - http.ServeContent(w, r, "sign_in.html", time.Unix(0, 0), bytes.NewReader([]byte(signInHTML))) + s.Set("username", form.Username) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.Redirect(http.StatusFound, "/auth") } // TokenHandler should be served at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token -func (a *API) TokenHandler(w http.ResponseWriter, r *http.Request) { - if err := a.server.HandleTokenRequest(w, r); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) +func (a *API) TokenHandler(c *gin.Context) { + if err := a.server.HandleTokenRequest(c.Writer, c.Request); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) } } -// AuthorizeHandler should be served at https://example.org/oauth/authorize +// AuthorizeHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (a *API) AuthorizeHandler(w http.ResponseWriter, r *http.Request) { - store, err := session.Start(nil, w, r) - if err != nil { +func (a *API) AuthorizeHandler(c *gin.Context) { + s := sessions.Default(c) + form := &authorize{} - http.Error(w, err.Error(), http.StatusInternalServerError) + if err := c.ShouldBind(form); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - if _, ok := store.Get("username"); !ok { - w.Header().Set("Location", "/auth/sign_in") - w.WriteHeader(http.StatusFound) + if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) return } - http.ServeContent(w, r, "authorize.html", time.Unix(0, 0), bytes.NewReader([]byte(authorizeHTML))) + s.Set("force_login", form.ForceLogin) + s.Set("response_type", form.ResponseType) + s.Set("client_id", form.ClientID) + s.Set("redirect_uri", form.RedirectURI) + s.Set("scope", form.Scope) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + + v := s.Get("username") + if username, ok := v.(string); !ok || username == "" { + c.Redirect(http.StatusFound, "/auth/sign_in") + return + } + + c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(authorizeHTML)) } // AuthHandler should be served at https://example.org/auth -func (a *API) AuthHandler(w http.ResponseWriter, r *http.Request) { - store, err := session.Start(r.Context(), w, r) - if err != nil { - a.log.Errorf("error creating session in authhandler: %s", err) - http.Error(w, err.Error(), http.StatusInternalServerError) +func (a *API) AuthHandler(c *gin.Context) { + s := sessions.Default(c) + + values := url.Values{} + + if v, ok := s.Get("force_login").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing force_login"}) + return + } else { + values.Add("force_login", v) + } + + if v, ok := s.Get("response_type").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing response_type"}) + return + } else { + values.Add("response_type", v) + } + + if v, ok := s.Get("client_id").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing client_id"}) + return + } else { + values.Add("client_id", v) + } + + if v, ok := s.Get("redirect_uri").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing redirect_uri"}) + return + } else { + values.Add("redirect_uri", v) + } + + if v, ok := s.Get("scope").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing scope"}) return + } else { + values.Add("scope", v) } - var form url.Values - if v, ok := store.Get("ReturnUri"); ok { - form = v.(url.Values) + if v, ok := s.Get("username").(string); !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "session missing username"}) + return + } else { + values.Add("username", v) } - r.Form = form - store.Delete("ReturnUri") - store.Save() + c.Request.Form = values - if err := a.server.HandleAuthorizeRequest(w, r); err != nil { - a.log.Errorf("error in authhandler during handleauthorizerequest: %s", err) - http.Error(w, err.Error(), http.StatusBadRequest) + if err := s.Save(); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if err := a.server.HandleAuthorizeRequest(c.Writer, c.Request); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } @@ -203,34 +267,14 @@ func (a *API) PasswordAuthorizationHandler(email string, password string) (useri return } -// UserAuthorizationHandler gets the user's email address from the session key 'username' +// UserAuthorizationHandler gets the user's email address from the form key 'username' // or redirects to the /auth/sign_in page, if this key is not present. func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (string, error) { - a.log.Errorf("entering userauthorizationhandler") - - sessionStore, err := session.Start(r.Context(), w, r) - if err != nil { - a.log.Errorf("error starting session: %s", err) - return "", err + username := r.FormValue("username") + if username == "" { + http.Redirect(w, r, "/auth/sign_in", http.StatusFound) + return "", nil } - - v, ok := sessionStore.Get("username") - if !ok { - if err := r.ParseForm(); err != nil { - a.log.Errorf("error parsing form: %s", err) - return "", err - } - - sessionStore.Set("ReturnUri", r.Form) - sessionStore.Save() - - w.Header().Set("Location", "/auth/sign_in") - w.WriteHeader(http.StatusFound) - return v.(string), nil - } - - sessionStore.Delete("username") - sessionStore.Save() - return v.(string), nil + return username, nil } diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 4d942c51d..f786df396 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -7,6 +7,7 @@ import ( "github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/config" "github.com/gotosocial/gotosocial/internal/gtsmodel" @@ -18,35 +19,37 @@ import ( type OauthTestSuite struct { suite.Suite - tokenStore oauth2.TokenStore - clientStore oauth2.ClientStore - conn *pg.DB - testClientID string - testClientSecret string - testClientDomain string - testClientUserID string - testUser *gtsmodel.User - config *config.Config + tokenStore oauth2.TokenStore + clientStore oauth2.ClientStore + conn *pg.DB + testUser *gtsmodel.User + testClient *oauthClient + config *config.Config } const () // SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout func (suite *OauthTestSuite) SetupSuite() { - suite.testClientID = "test-client-id" - suite.testClientSecret = "test-client-secret" - suite.testClientDomain = "https://example.org" - suite.testClientUserID = "test-client-user-id" encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("test-password"), bcrypt.DefaultCost) if err != nil { logrus.Panicf("error encrypting user pass: %s", err) } + + userID := uuid.NewString() suite.testUser = >smodel.User{ + ID: userID, EncryptedPassword: string(encryptedPassword), - Email: "user@example.org", + Email: "user@localhost", CreatedAt: time.Now(), UpdatedAt: time.Now(), - AccountID: "whatever", + AccountID: "some-account-id-it-doesn't-matter-really", + } + suite.testClient = &oauthClient{ + ID: "a-known-client-id", + Secret: "some-secret", + Domain: "localhost", + UserID: userID, } } @@ -78,6 +81,10 @@ func (suite *OauthTestSuite) SetupTest() { logrus.Panicf("could not insert test user into db: %s", err) } + if _, err := suite.conn.Model(suite.testClient).Insert(); err != nil { + logrus.Panicf("could not insert test client into db: %s", err) + } + } // TearDownTest drops the oauth_clients table and closes the pg connection after each test @@ -107,7 +114,7 @@ func (suite *OauthTestSuite) TestAPIInitialize() { api.AddRoutes(r) go r.Start() time.Sleep(30 * time.Second) - // http://localhost:8080/oauth/authorize?client_id=whatever + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code } func TestOauthTestSuite(t *testing.T) { diff --git a/internal/oauth/pgclientstore.go b/internal/oauth/pgclientstore.go index 22bb54f55..1df46fedb 100644 --- a/internal/oauth/pgclientstore.go +++ b/internal/oauth/pgclientstore.go @@ -20,6 +20,7 @@ package oauth import ( "context" + "fmt" "github.com/go-pg/pg/v10" "github.com/gotosocial/oauth2/v4" @@ -42,7 +43,7 @@ func (pcs *pgClientStore) GetByID(ctx context.Context, clientID string) (oauth2. ID: clientID, } if err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in clientstore getbyid searching for client %s: %s", clientID, err) } return models.New(poc.ID, poc.Secret, poc.Domain, poc.UserID), nil } @@ -55,7 +56,10 @@ func (pcs *pgClientStore) Set(ctx context.Context, id string, cli oauth2.ClientI UserID: cli.GetUserID(), } _, err := pcs.conn.WithContext(ctx).Model(poc).OnConflict("(id) DO UPDATE").Insert() - return err + if err != nil { + return fmt.Errorf("error in clientstore set: %s", err) + } + return nil } func (pcs *pgClientStore) Delete(ctx context.Context, id string) error { @@ -63,7 +67,10 @@ func (pcs *pgClientStore) Delete(ctx context.Context, id string) error { ID: id, } _, err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Delete() - return err + if err != nil { + return fmt.Errorf("error in clientstore delete: %s", err) + } + return nil } type oauthClient struct { diff --git a/internal/oauth/pgclientstore_test.go b/internal/oauth/pgclientstore_test.go index d6a76981f..eb011fe01 100644 --- a/internal/oauth/pgclientstore_test.go +++ b/internal/oauth/pgclientstore_test.go @@ -96,7 +96,6 @@ func (suite *PgClientStoreTestSuite) TestClientSetAndDelete() { deletedClient, err := cs.GetByID(context.Background(), suite.testClientID) suite.Assert().Nil(deletedClient) suite.Assert().NotNil(err) - suite.EqualValues("pg: no rows in result set", err.Error()) } func TestPgClientStoreTestSuite(t *testing.T) { diff --git a/internal/oauth/pgtokenstore.go b/internal/oauth/pgtokenstore.go index a927be862..0271afafb 100644 --- a/internal/oauth/pgtokenstore.go +++ b/internal/oauth/pgtokenstore.go @@ -21,6 +21,7 @@ package oauth import ( "context" "errors" + "fmt" "time" "github.com/go-pg/pg/v10" @@ -98,32 +99,44 @@ func (pts *pgTokenStore) Create(ctx context.Context, info oauth2.TokenInfo) erro return errors.New("info param was not a models.Token") } _, err := pts.conn.WithContext(ctx).Model(oauthTokenToPGToken(t)).Insert() - return err + if err != nil { + return fmt.Errorf("error in tokenstore create: %s", err) + } + return nil } // RemoveByCode deletes a token from the DB based on the Code field func (pts *pgTokenStore) RemoveByCode(ctx context.Context, code string) error { _, err := pts.conn.Model(&oauthToken{}).Where("code = ?", code).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebycode: %s", err) + } + return nil } // RemoveByAccess deletes a token from the DB based on the Access field func (pts *pgTokenStore) RemoveByAccess(ctx context.Context, access string) error { _, err := pts.conn.Model(&oauthToken{}).Where("access = ?", access).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebyaccess: %s", err) + } + return nil } // RemoveByRefresh deletes a token from the DB based on the Refresh field func (pts *pgTokenStore) RemoveByRefresh(ctx context.Context, refresh string) error { _, err := pts.conn.Model(&oauthToken{}).Where("refresh = ?", refresh).Delete() - return err + if err != nil { + return fmt.Errorf("error in tokenstore removebyrefresh: %s", err) + } + return nil } // GetByCode selects a token from the DB based on the Code field func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("code = ?", code).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbycode: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -132,7 +145,7 @@ func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.Tok func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("access = ?", access).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbyaccess: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -141,7 +154,7 @@ func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2 func (pts *pgTokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) { pgt := &oauthToken{} if err := pts.conn.Model(pgt).Where("refresh = ?", refresh).Select(); err != nil { - return nil, err + return nil, fmt.Errorf("error in tokenstore getbyrefresh: %s", err) } return pgTokenToOauthToken(pgt), nil } @@ -165,15 +178,15 @@ type oauthToken struct { UserID string RedirectURI string Scope string - Code string `pg:",pk"` + Code string `pg:"default:'',pk"` CodeChallenge string CodeChallengeMethod string CodeCreateAt time.Time `pg:"type:timestamp"` CodeExpiresAt time.Time `pg:"type:timestamp"` - Access string `pg:",pk"` + Access string `pg:"default:'',pk"` AccessCreateAt time.Time `pg:"type:timestamp"` AccessExpiresAt time.Time `pg:"type:timestamp"` - Refresh string `pg:",pk"` + Refresh string `pg:"default:'',pk"` RefreshCreateAt time.Time `pg:"type:timestamp"` RefreshExpiresAt time.Time `pg:"type:timestamp"` } -- cgit v1.2.3 From 1b118841211da90381dd950cafa13ead78b7f589 Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Thu, 18 Mar 2021 23:27:43 +0100 Subject: auth flow working for code --- .gitignore | 3 ++ cmd/gotosocial/main.go | 12 ++++- example/config.yaml | 7 +++ go.mod | 2 +- go.sum | 6 +++ internal/api/server.go | 8 ++++ internal/config/config.go | 53 ++++++++++++++------- internal/config/template.go | 25 ++++++++++ internal/oauth/html.go | 63 +------------------------ internal/oauth/oauth.go | 110 ++++++++++++++++++++++++++----------------- internal/oauth/oauth_test.go | 15 ++++-- pkg/mastotypes/oauth.go | 37 +++++++++++++++ web/template/authorize.tmpl | 33 +++++++++++++ web/template/sign-in.tmpl | 28 +++++++++++ 14 files changed, 274 insertions(+), 128 deletions(-) create mode 100644 internal/config/template.go create mode 100644 pkg/mastotypes/oauth.go create mode 100644 web/template/authorize.tmpl create mode 100644 web/template/sign-in.tmpl (limited to 'internal/api/server.go') diff --git a/.gitignore b/.gitignore index fe72fe018..6f9b97023 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ # exclude built documentation, since readthedocs will build it for us anyway /docs/_build + +# exclude coverage report +cp.out diff --git a/cmd/gotosocial/main.go b/cmd/gotosocial/main.go index 0b4110656..96798035e 100644 --- a/cmd/gotosocial/main.go +++ b/cmd/gotosocial/main.go @@ -95,6 +95,14 @@ func main() { Value: "postgres", EnvVars: []string{envNames.DbDatabase}, }, + + // TEMPLATE FLAGS + &cli.StringFlag{ + Name: flagNames.TemplateBaseDir, + Usage: "Basedir for html templating files for rendering pages and composing emails", + Value: "./web/template/", + EnvVars: []string{envNames.TemplateBaseDir}, + }, }, Commands: []*cli.Command{ { @@ -137,12 +145,12 @@ func main() { func runAction(c *cli.Context, a action.GTSAction) error { // create a new *config.Config based on the config path provided... - conf, err := config.New(c.String(config.GetFlagNames().ConfigPath)) + conf, err := config.FromFile(c.String(config.GetFlagNames().ConfigPath)) if err != nil { return fmt.Errorf("error creating config: %s", err) } // ... and the flags set on the *cli.Context by urfave - conf.ParseFlags(c) + conf.ParseCLIFlags(c) // create a logger with the log level, formatting, and output splitter already set log, err := log.New(conf.LogLevel) diff --git a/example/config.yaml b/example/config.yaml index e4d05c634..b65149d9a 100644 --- a/example/config.yaml +++ b/example/config.yaml @@ -60,3 +60,10 @@ db: # Examples: ["mydb","postgres","gotosocial"] # Default: "postgres" database: "postgres" + +# Config pertaining to templating of web pages/email notifications and the like +template: + # String. Directory from which gotosocial will attempt to load html templates (.tmpl files). + # Examples: ["/some/absolute/path/", "./relative/path/", "../../some/weird/path/"] + # Default: "./web/template/" + baseDir: "./web/template/" diff --git a/go.mod b/go.mod index 6f1ede9ed..473ff3ea8 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/go-session/session v3.1.2+incompatible github.com/golang/mock v1.4.4 // indirect github.com/google/uuid v1.2.0 // indirect - github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 + github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3 github.com/onsi/ginkgo v1.15.0 // indirect github.com/onsi/gomega v1.10.5 // indirect github.com/sirupsen/logrus v1.8.0 diff --git a/go.sum b/go.sum index f482187af..0b12241f0 100644 --- a/go.sum +++ b/go.sum @@ -107,6 +107,12 @@ github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0U github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88 h1:YJ//HmHOYJ4srm/LA6VPNjNisneMbY6TTM1xttV/ZQU= github.com/gotosocial/oauth2/v4 v4.2.1-0.20210316171520-7b12112bbb88/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132047-b7df44000ea6 h1:mWWMTK2Boy6FSCi45WB6GVCcXW3IoTVJKJiHmmdjywU= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132047-b7df44000ea6/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132554-68b81fe90e62 h1:duqoA9NSY+BFY2IVveXx5lSvIQliVvPsaNMdspkTJPc= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318132554-68b81fe90e62/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3 h1:CKRz5d7mRum+UMR88Ue33tCYcej14WjUsB59C02DDqY= +github.com/gotosocial/oauth2/v4 v4.2.1-0.20210318133800-45d321d259b3/go.mod h1:zl5kwHf/atRUrY5yOyDnk49Us1Ygs0BzdW4jKAgoiP8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk= github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= diff --git a/internal/api/server.go b/internal/api/server.go index 321c932cd..8e22742bb 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -19,6 +19,10 @@ package api import ( + "fmt" + "os" + "path/filepath" + "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" @@ -71,6 +75,10 @@ func New(config *config.Config, logger *logrus.Logger) Server { engine := gin.New() store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-keyencryption-key----")) engine.Use(sessions.Sessions("gotosocial-session", store)) + cwd, _ := os.Getwd() + tmPath := filepath.Join(cwd, fmt.Sprintf("%s*", config.TemplateConfig.BaseDir)) + logger.Debugf("loading templates from %s", tmPath) + engine.LoadHTMLGlob(tmPath) return &server{ APIGroup: engine.Group("/api").Group("/v1"), logger: logger, diff --git a/internal/config/config.go b/internal/config/config.go index 5832ed53f..8e2656e3f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -27,25 +27,38 @@ import ( // Config pulls together all the configuration needed to run gotosocial type Config struct { - LogLevel string `yaml:"logLevel"` - ApplicationName string `yaml:"applicationName"` - DBConfig *DBConfig `yaml:"db"` + LogLevel string `yaml:"logLevel"` + ApplicationName string `yaml:"applicationName"` + DBConfig *DBConfig `yaml:"db"` + TemplateConfig *TemplateConfig `yaml:"template"` } -// New returns a new config, or an error if something goes amiss. -// The path parameter is optional, for loading a configuration json from the given path. -func New(path string) (*Config, error) { - config := &Config{ - DBConfig: &DBConfig{}, +// FromFile returns a new config from a file, or an error if something goes amiss. +func FromFile(path string) (*Config, error) { + c, err := loadFromFile(path) + if err != nil { + return nil, fmt.Errorf("error creating config: %s", err) } - if path != "" { - var err error - if config, err = loadFromFile(path); err != nil { - return nil, fmt.Errorf("error creating config: %s", err) - } + return c, nil +} + +// Default returns a new config with default values. +// Not yet implemented. +func Default() *Config { + // TODO: find a way of doing this without code repetition, because having to + // repeat all values here and elsewhere is annoying and gonna be prone to mistakes. + return &Config{ + DBConfig: &DBConfig{}, + TemplateConfig: &TemplateConfig{}, } +} - return config, nil +// Empty just returns an empty config +func Empty() *Config { + return &Config{ + DBConfig: &DBConfig{}, + TemplateConfig: &TemplateConfig{}, + } } // loadFromFile takes a path to a yaml file and attempts to load a Config object from it @@ -63,8 +76,8 @@ func loadFromFile(path string) (*Config, error) { return config, nil } -// ParseFlags sets flags on the config using the provided Flags object -func (c *Config) ParseFlags(f KeyedFlags) { +// ParseCLIFlags sets flags on the config using the provided Flags object +func (c *Config) ParseCLIFlags(f KeyedFlags) { fn := GetFlagNames() // For all of these flags, we only want to set them on the config if: @@ -108,6 +121,11 @@ func (c *Config) ParseFlags(f KeyedFlags) { if c.DBConfig.Database == "" || f.IsSet(fn.DbDatabase) { c.DBConfig.Database = f.String(fn.DbDatabase) } + + // template flags + if c.TemplateConfig.BaseDir == "" || f.IsSet(fn.TemplateBaseDir) { + c.TemplateConfig.BaseDir = f.String(fn.TemplateBaseDir) + } } // KeyedFlags is a wrapper for any type that can store keyed flags and give them back. @@ -130,6 +148,7 @@ type Flags struct { DbUser string DbPassword string DbDatabase string + TemplateBaseDir string } // GetFlagNames returns a struct containing the names of the various flags used for @@ -145,6 +164,7 @@ func GetFlagNames() Flags { DbUser: "db-user", DbPassword: "db-password", DbDatabase: "db-database", + TemplateBaseDir: "template-basedir", } } @@ -161,5 +181,6 @@ func GetEnvNames() Flags { DbUser: "GTS_DB_USER", DbPassword: "GTS_DB_PASSWORD", DbDatabase: "GTS_DB_DATABASE", + TemplateBaseDir: "GTS_TEMPLATE_BASEDIR", } } diff --git a/internal/config/template.go b/internal/config/template.go new file mode 100644 index 000000000..eba86f8e6 --- /dev/null +++ b/internal/config/template.go @@ -0,0 +1,25 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package config + +// TemplateConfig pertains to templating of web pages/email notifications and the like +type TemplateConfig struct { + // Directory from which gotosocial will attempt to load html templates (.tmpl files). + BaseDir string `yaml:"baseDir"` +} diff --git a/internal/oauth/html.go b/internal/oauth/html.go index 06089aedd..a3ae4318a 100644 --- a/internal/oauth/html.go +++ b/internal/oauth/html.go @@ -2,67 +2,8 @@ package oauth const ( signInHTML = ` - - - - - Login - - - - - - -
-

Login

-
-
- - -
-
- - -
- -
-
- - -` +` authorizeHTML = ` - - - - - Auth - - - - - - -
-
-
-

Authorize

-

The client would like to perform actions on your behalf.

-

- -

-
-
-
- -` +` ) diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 97913549a..c6d596761 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -27,6 +27,7 @@ import ( "github.com/go-pg/pg/v10" "github.com/gotosocial/gotosocial/internal/api" "github.com/gotosocial/gotosocial/internal/gtsmodel" + "github.com/gotosocial/gotosocial/pkg/mastotypes" "github.com/gotosocial/oauth2/v4" "github.com/gotosocial/oauth2/v4/errors" "github.com/gotosocial/oauth2/v4/manage" @@ -45,16 +46,12 @@ type API struct { } type login struct { - Email string `form:"username"` + Email string `form:"username"` Password string `form:"password"` } -type authorize struct { - ForceLogin string `form:"force_login,omitempty"` - ResponseType string `form:"response_type"` - ClientID string `form:"client_id"` - RedirectURI string `form:"redirect_uri"` - Scope string `form:"scope,omitempty"` +type code struct { + Code string `form:"code"` } func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.Logger) *API { @@ -79,6 +76,9 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L oauth2.AuthorizationCode, oauth2.Refreshing, }, + AllowedCodeChallengeMethods: []oauth2.CodeChallengeMethod{ + oauth2.CodeChallengePlain, + }, } srv := server.NewServer(sc, manager) @@ -106,9 +106,13 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L func (a *API) AddRoutes(s api.Server) error { s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler) s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler) + s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenHandler) + s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler) - s.AttachHandler(methodAny, "/auth", a.AuthHandler) + s.AttachHandler(http.MethodPost, "/oauth/authorize", a.AuthorizePOSTHandler) + + // s.AttachHandler(http.MethodGet, "/auth", a.AuthGETHandler) return nil } @@ -125,7 +129,7 @@ func incorrectPassword() (string, error) { // The form will then POST to the sign in page, which will be handled by SignInPOSTHandler func (a *API) SignInGETHandler(c *gin.Context) { a.log.WithField("func", "SignInGETHandler").Trace("serving sign in html") - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(signInHTML)) + c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) } // SignInPOSTHandler should be served at https://example.org/auth/sign_in. @@ -135,15 +139,16 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { l := a.log.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) form := &login{} - if err := c.ShouldBind(form); err != nil || form.Email == "" || form.Password == "" { + if err := c.ShouldBind(form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } l.Tracef("parsed form: %+v", form) - userid, err := a.ValidatePassword(form.Email, form.Password); + userid, err := a.ValidatePassword(form.Email, form.Password) if err != nil { c.String(http.StatusForbidden, err.Error()) + return } s.Set("username", userid) @@ -151,11 +156,12 @@ func (a *API) SignInPOSTHandler(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } + l.Trace("redirecting to auth page") - c.Redirect(http.StatusFound, "/auth") + c.Redirect(http.StatusFound, "/oauth/authorize") } -// TokenHandler should be served at https://example.org/oauth/token +// TokenHandler should be served as a POST at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token func (a *API) TokenHandler(c *gin.Context) { @@ -166,50 +172,61 @@ func (a *API) TokenHandler(c *gin.Context) { } } -// AuthorizeHandler should be served as GET at https://example.org/oauth/authorize +// AuthorizeGETHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user func (a *API) AuthorizeGETHandler(c *gin.Context) { - l := a.log.WithField("func", "AuthorizeHandler") + l := a.log.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) - form := &authorize{} - - if err := c.ShouldBind(form); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - return - } - l.Tracef("parsed form: %+v", form) - - if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) - return - } - - s.Set("force_login", form.ForceLogin) - s.Set("response_type", form.ResponseType) - s.Set("client_id", form.ClientID) - s.Set("redirect_uri", form.RedirectURI) - s.Set("scope", form.Scope) - if err := s.Save(); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } v := s.Get("username") if username, ok := v.(string); !ok || username == "" { - l.Trace("username was empty, redirecting to sign in page") + l.Trace("username was empty, parsing form then redirecting to sign in page") + + form := &mastotypes.OAuthAuthorize{} + + if err := c.ShouldBind(form); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + l.Tracef("parsed form: %+v", form) + + if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"}) + return + } + + // save these values from the form so we can use them elsewhere in the session + s.Set("force_login", form.ForceLogin) + s.Set("response_type", form.ResponseType) + s.Set("client_id", form.ClientID) + s.Set("redirect_uri", form.RedirectURI) + s.Set("scope", form.Scope) + if err := s.Save(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.Redirect(http.StatusFound, "/auth/sign_in") return } l.Trace("serving authorize html") - c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(authorizeHTML)) + c.HTML(http.StatusOK, "authorize.tmpl", gin.H{}) } -// AuthHandler should be served at https://example.org/auth -func (a *API) AuthHandler(c *gin.Context) { - l := a.log.WithField("func", "AuthHandler") +// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize +// The idea here is to present an oauth authorize page to the user, with a button +// that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user +func (a *API) AuthorizePOSTHandler(c *gin.Context) { + l := a.log.WithField("func", "AuthorizePOSTHandler") s := sessions.Default(c) + v := s.Get("username") + if username, ok := v.(string); !ok || username == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "you are not signed in"}) + } + values := url.Values{} if v, ok := s.Get("force_login").(string); !ok { @@ -277,7 +294,13 @@ func (a *API) AuthHandler(c *gin.Context) { // so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db. func (a *API) ValidatePassword(email string, password string) (userid string, err error) { l := a.log.WithField("func", "PasswordAuthorizationHandler") - l.Tracef("email %s password %s", email, password) + + // make sure an email/password was provided and bail if not + if email == "" || password == "" { + l.Debug("email or password was not provided") + return incorrectPassword() + } + // first we select the user from the database based on email address, bail if no user found for that email gtsUser := >smodel.User{} if err := a.conn.Model(gtsUser).Where("email = ?", email).Select(); err != nil { @@ -297,8 +320,7 @@ func (a *API) ValidatePassword(email string, password string) (userid string, er return incorrectPassword() } - // If we've made it this far the email/password is correct so we need the oauth client-id of the user - // This is, conveniently, the same as the user ID, so we can just return it. + // If we've made it this far the email/password is correct, so we can just return the id of the user. userid = gtsUser.ID l.Tracef("returning (%s, %s)", userid, err) return diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go index 404ea5c20..901f99b64 100644 --- a/internal/oauth/oauth_test.go +++ b/internal/oauth/oauth_test.go @@ -40,17 +40,24 @@ func (suite *OauthTestSuite) SetupSuite() { suite.testUser = >smodel.User{ ID: userID, EncryptedPassword: string(encryptedPassword), - Email: "user@localhost", + Email: "user@example.org", CreatedAt: time.Now(), UpdatedAt: time.Now(), - AccountID: "some-account-id-it-doesn't-matter-really", + AccountID: "some-account-id-it-doesn't-matter-really-since-this-user-doesn't-actually-have-an-account!", } suite.testClient = &oauthClient{ ID: "a-known-client-id", Secret: "some-secret", - Domain: "http://localhost:8080", + Domain: "https://example.org", UserID: userID, } + + // because go tests are run within the test package directory, we need to fiddle with the templateconfig + // basedir in a way that we wouldn't normally have to do when running the binary, in order to make + // the templates actually load + c := config.Empty() + c.TemplateConfig.BaseDir = "../../web/template/" + suite.config = c } // SetupTest creates a postgres connection and creates the oauth_clients table before each test @@ -114,7 +121,7 @@ func (suite *OauthTestSuite) TestAPIInitialize() { api.AddRoutes(r) go r.Start() time.Sleep(30 * time.Second) - // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&redirect_uri=''&response_type=code + // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=https://example.org } func TestOauthTestSuite(t *testing.T) { diff --git a/pkg/mastotypes/oauth.go b/pkg/mastotypes/oauth.go new file mode 100644 index 000000000..1b45b38e0 --- /dev/null +++ b/pkg/mastotypes/oauth.go @@ -0,0 +1,37 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package mastotypes + +// OAuthAuthorize represents a request sent to https://example.org/oauth/authorize +// See here: https://docs.joinmastodon.org/methods/apps/oauth/ +type OAuthAuthorize struct { + // Forces the user to re-login, which is necessary for authorizing with multiple accounts from the same instance. + ForceLogin string `form:"force_login,omitempty"` + // Should be set equal to `code`. + ResponseType string `form:"response_type"` + // Client ID, obtained during app registration. + ClientID string `form:"client_id"` + // Set a URI to redirect the user to. + // If this parameter is set to urn:ietf:wg:oauth:2.0:oob then the authorization code will be shown instead. + // Must match one of the redirect URIs declared during app registration. + RedirectURI string `form:"redirect_uri"` + // List of requested OAuth scopes, separated by spaces (or by pluses, if using query parameters). + // Must be a subset of scopes declared during app registration. If not provided, defaults to read. + Scope string `form:"scope,omitempty"` +} diff --git a/web/template/authorize.tmpl b/web/template/authorize.tmpl new file mode 100644 index 000000000..0043e21ba --- /dev/null +++ b/web/template/authorize.tmpl @@ -0,0 +1,33 @@ + + + + + Auth + + + + + + +
+
+
+

Authorize

+

The client would like to perform actions on your behalf.

+

+ +

+
+
+
+ + diff --git a/web/template/sign-in.tmpl b/web/template/sign-in.tmpl new file mode 100644 index 000000000..b7aa7c702 --- /dev/null +++ b/web/template/sign-in.tmpl @@ -0,0 +1,28 @@ + + + + + Login + + + + + + +
+

Login

+
+
+ + +
+
+ + +
+ +
+
+ + + -- cgit v1.2.3