1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
|
/*
GoToSocial
Copyright (C) 2021-2022 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 <http://www.gnu.org/licenses/>.
*/
package auth
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/sirupsen/logrus"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/superseriousbusiness/gotosocial/internal/api"
"github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
)
// 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.
func (m *Module) AuthorizeGETHandler(c *gin.Context) {
l := logrus.WithField("func", "AuthorizeGETHandler")
s := sessions.Default(c)
if _, err := api.NegotiateAccept(c, api.HTMLAcceptHeaders...); err != nil {
c.HTML(http.StatusNotAcceptable, "error.tmpl", gin.H{"error": err.Error()})
return
}
// UserID will be set in the session by AuthorizePOSTHandler if the caller has already gone through the authentication flow
// If it's not set, then we don't know yet who the user is, so we need to redirect them to the sign in page.
userID, ok := s.Get(sessionUserID).(string)
if !ok || userID == "" {
l.Trace("userid was empty, parsing form then redirecting to sign in page")
form := &model.OAuthAuthorize{}
if err := c.Bind(form); err != nil {
l.Debugf("invalid auth form: %s", err)
m.clearSession(s)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()})
return
}
l.Debugf("parsed auth form: %+v", form)
if err := extractAuthForm(s, form); err != nil {
l.Debugf(fmt.Sprintf("error parsing form at /oauth/authorize: %s", err))
m.clearSession(s)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusSeeOther, AuthSignInPath)
return
}
// We can use the client_id on the session to retrieve info about the app associated with the client_id
clientID, ok := s.Get(sessionClientID).(string)
if !ok || clientID == "" {
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no client_id found in session"})
return
}
app := >smodel.Application{}
if err := m.db.GetWhere(c.Request.Context(), []db.Where{{Key: sessionClientID, Value: clientID}}, app); err != nil {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{
"error": fmt.Sprintf("no application found for client id %s", clientID),
})
return
}
// redirect the user if they have not confirmed their email yet, thier account has not been approved yet,
// or thier account has been disabled.
user := >smodel.User{}
if err := m.db.GetByID(c.Request.Context(), userID, user); err != nil {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()})
return
}
acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID)
if err != nil {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()})
return
}
if !ensureUserIsAuthorizedOrRedirect(c, user, acct) {
return
}
// Finally we should also get the redirect and scope of this particular request, as stored in the session.
redirect, ok := s.Get(sessionRedirectURI).(string)
if !ok || redirect == "" {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no redirect_uri found in session"})
return
}
scope, ok := s.Get(sessionScope).(string)
if !ok || scope == "" {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no scope found in session"})
return
}
// the authorize template will display a form to the user where they can get some information
// about the app that's trying to authorize, and the scope of the request.
// They can then approve it if it looks OK to them, which will POST to the AuthorizePOSTHandler
l.Trace("serving authorize html")
c.HTML(http.StatusOK, "authorize.tmpl", gin.H{
"appname": app.Name,
"appwebsite": app.Website,
"redirect": redirect,
sessionScope: scope,
"user": acct.Username,
})
}
// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize
// At this point we assume that the user has A) logged in and B) accepted that the app should act for them,
// so we should proceed with the authentication flow and generate an oauth token for them if we can.
func (m *Module) AuthorizePOSTHandler(c *gin.Context) {
l := logrus.WithField("func", "AuthorizePOSTHandler")
s := sessions.Default(c)
// We need to retrieve the original form submitted to the authorizeGEThandler, and
// recreate it on the request so that it can be used further by the oauth2 library.
// So first fetch all the values from the session.
errs := []string{}
forceLogin, ok := s.Get(sessionForceLogin).(string)
if !ok {
forceLogin = "false"
}
responseType, ok := s.Get(sessionResponseType).(string)
if !ok || responseType == "" {
errs = append(errs, "session missing response_type")
}
clientID, ok := s.Get(sessionClientID).(string)
if !ok || clientID == "" {
errs = append(errs, "session missing client_id")
}
redirectURI, ok := s.Get(sessionRedirectURI).(string)
if !ok || redirectURI == "" {
errs = append(errs, "session missing redirect_uri")
}
scope, ok := s.Get(sessionScope).(string)
if !ok {
errs = append(errs, "session missing scope")
}
userID, ok := s.Get(sessionUserID).(string)
if !ok {
errs = append(errs, "session missing userid")
}
// redirect the user if they have not confirmed their email yet, thier account has not been approved yet,
// or thier account has been disabled.
user := >smodel.User{}
if err := m.db.GetByID(c.Request.Context(), userID, user); err != nil {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()})
return
}
acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID)
if err != nil {
m.clearSession(s)
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()})
return
}
if !ensureUserIsAuthorizedOrRedirect(c, user, acct) {
return
}
m.clearSession(s)
if len(errs) != 0 {
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": strings.Join(errs, ": ")})
return
}
// now set the values on the request
values := url.Values{}
values.Set(sessionForceLogin, forceLogin)
values.Set(sessionResponseType, responseType)
values.Set(sessionClientID, clientID)
values.Set(sessionRedirectURI, redirectURI)
values.Set(sessionScope, scope)
values.Set(sessionUserID, userID)
c.Request.Form = values
l.Tracef("values on request set to %+v", c.Request.Form)
// and proceed with authorization using the oauth2 library
if err := m.server.HandleAuthorizeRequest(c.Writer, c.Request); err != nil {
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()})
}
}
// extractAuthForm checks the given OAuthAuthorize form, and stores
// the values in the form into the session.
func extractAuthForm(s sessions.Session, form *model.OAuthAuthorize) error {
// these fields are *required* so check 'em
if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" {
return errors.New("missing one of: response_type, client_id or redirect_uri")
}
// set default scope to read
if form.Scope == "" {
form.Scope = "read"
}
// save these values from the form so we can use them elsewhere in the session
s.Set(sessionForceLogin, form.ForceLogin)
s.Set(sessionResponseType, form.ResponseType)
s.Set(sessionClientID, form.ClientID)
s.Set(sessionRedirectURI, form.RedirectURI)
s.Set(sessionScope, form.Scope)
s.Set(sessionState, uuid.NewString())
return s.Save()
}
func ensureUserIsAuthorizedOrRedirect(ctx *gin.Context, user *gtsmodel.User, account *gtsmodel.Account) bool {
if user.ConfirmedAt.IsZero() {
ctx.Redirect(http.StatusSeeOther, CheckYourEmailPath)
return false
}
if !user.Approved {
ctx.Redirect(http.StatusSeeOther, WaitForApprovalPath)
return false
}
if user.Disabled {
ctx.Redirect(http.StatusSeeOther, AccountDisabledPath)
return false
}
if !account.SuspendedAt.IsZero() {
ctx.Redirect(http.StatusSeeOther, AccountDisabledPath)
return false
}
return true
}
|