-
-
Notifications
You must be signed in to change notification settings - Fork 839
Expand file tree
/
Copy pathoauth.go
More file actions
276 lines (235 loc) · 7.99 KB
/
Copy pathoauth.go
File metadata and controls
276 lines (235 loc) · 7.99 KB
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
266
267
268
269
270
271
272
273
274
275
276
package handlers
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/models/enum"
"github.com/getfider/fider/app/models/query"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web"
webutil "github.com/getfider/fider/app/pkg/web/util"
)
// OAuthEcho exchanges OAuth Code for a user profile and return directly to the UI, without storing it
func OAuthEcho() web.HandlerFunc {
return func(c *web.Context) error {
provider := c.Param("provider")
code := c.QueryParam("code")
if code == "" {
return c.Redirect("/")
}
identifier := c.QueryParam("identifier")
if identifier == "" || identifier != c.SessionID() {
log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
return c.Redirect("/")
}
rawProfile := &query.GetOAuthRawProfile{Provider: provider, Code: code}
err := bus.Dispatch(c, rawProfile)
if err != nil {
return c.Page(http.StatusOK, web.Props{
Page: "OAuthEcho/OAuthEcho.page",
Title: "OAuth Test Page",
Data: web.Map{
"err": errors.Cause(err).Error(),
},
})
}
parseRawProfile := &cmd.ParseOAuthRawProfile{Provider: provider, Body: rawProfile.Result}
_ = bus.Dispatch(c, parseRawProfile)
return c.Page(http.StatusOK, web.Props{
Page: "OAuthEcho/OAuthEcho.page",
Title: "OAuth Test Page",
Data: web.Map{
"body": rawProfile.Result,
"profile": parseRawProfile.Result,
},
})
}
}
// OAuthToken exchanges OAuth Code for a user profile
// The user profile is then used to either get an existing user on Fider or creating a new one
// Once Fider user is retrieved/created, an authentication cookie is store in user's browser
func OAuthToken() web.HandlerFunc {
return func(c *web.Context) error {
provider := c.Param("provider")
redirectURL, _ := url.ParseRequestURI(c.QueryParam("redirect"))
redirectURL.ResolveReference(c.Request.URL)
code := c.QueryParam("code")
if code == "" {
return c.Redirect(redirectURL.String())
}
identifier := c.QueryParam("identifier")
if identifier == "" || identifier != c.SessionID() {
log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
return c.Redirect(redirectURL.String())
}
oauthUser := &query.GetOAuthProfile{Provider: provider, Code: code}
if err := bus.Dispatch(c, oauthUser); err != nil {
return c.Failure(err)
}
var user *entity.User
userByProvider := &query.GetUserByProvider{Provider: provider, UID: oauthUser.Result.ID}
err := bus.Dispatch(c, userByProvider)
user = userByProvider.Result
if errors.Cause(err) == app.ErrNotFound && oauthUser.Result.Email != "" {
userByEmail := &query.GetUserByEmail{Email: oauthUser.Result.Email}
err = bus.Dispatch(c, userByEmail)
user = userByEmail.Result
}
if err != nil {
if errors.Cause(err) == app.ErrNotFound {
isTrusted := isTrustedOAuthProvider(c, provider)
if c.Tenant().IsPrivate && !isTrusted {
return c.Redirect("/not-invited")
}
user = &entity.User{
Name: oauthUser.Result.Name,
Tenant: c.Tenant(),
Email: oauthUser.Result.Email,
Role: enum.RoleVisitor,
Providers: []*entity.UserProvider{
{
UID: oauthUser.Result.ID,
Name: provider,
},
},
}
if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
return c.Failure(err)
}
} else {
return c.Failure(err)
}
} else if !user.HasProvider(provider) {
if err = bus.Dispatch(c, &cmd.RegisterUserProvider{
UserID: user.ID,
ProviderName: provider,
ProviderUID: oauthUser.Result.ID,
}); err != nil {
return c.Failure(err)
}
}
webutil.AddAuthUserCookie(c, user)
return c.Redirect(redirectURL.String())
}
}
func isTrustedOAuthProvider(ctx context.Context, provider string) bool {
customOAuthConfigByProvider := &query.GetCustomOAuthConfigByProvider{Provider: provider}
err := bus.Dispatch(ctx, customOAuthConfigByProvider)
if err != nil {
return false
}
return customOAuthConfigByProvider.Result.IsTrusted
}
// OAuthCallback handles the redirect back from the OAuth provider
// This callback can run on either Tenant or Login address
// If the request is for a sign in, we redirect the user to the tenant address
// If the request is for a sign up, we exchange the OAuth code and get the user profile
func OAuthCallback() web.HandlerFunc {
return func(c *web.Context) error {
c.Response.Header().Add("X-Robots-Tag", "noindex")
provider := c.Param("provider")
// Support both query parameters (GET) and form data (POST)
// Apple Sign-In uses POST with response_mode=form_post when name/email scopes are requested
state := c.QueryParam("state")
if state == "" && c.Request.Method == "POST" {
state = c.Request.GetFormValue("state")
}
claims, err := jwt.DecodeOAuthStateClaims(state)
if err != nil {
return c.Forbidden()
}
if claims.Redirect == "" {
log.Warnf(c, "Missing redirect URL in OAuth callback state for provider @{Provider}.", dto.Props{"Provider": provider})
return c.NotFound()
}
redirectURL, err := url.ParseRequestURI(claims.Redirect)
if err != nil {
return c.Failure(err)
}
code := c.QueryParam("code")
if code == "" && c.Request.Method == "POST" {
code = c.Request.GetFormValue("code")
}
if code == "" {
return c.Redirect(redirectURL.String())
}
//Test OAuth
if redirectURL.Path == fmt.Sprintf("/oauth/%s/echo", provider) {
var query = redirectURL.Query()
query.Set("code", code)
query.Set("identifier", claims.Identifier)
redirectURL.RawQuery = query.Encode()
return c.Redirect(redirectURL.String())
}
//Sign up process
if redirectURL.Path == "/signup" {
oauthUser := &query.GetOAuthProfile{Provider: provider, Code: code}
if err := bus.Dispatch(c, oauthUser); err != nil {
return c.Failure(err)
}
claims := jwt.OAuthClaims{
OAuthID: oauthUser.Result.ID,
OAuthProvider: provider,
OAuthName: oauthUser.Result.Name,
OAuthEmail: oauthUser.Result.Email,
Metadata: jwt.Metadata{
ExpiresAt: jwt.Time(time.Now().Add(10 * time.Minute)),
},
}
token, err := jwt.Encode(claims)
if err != nil {
return c.Failure(err)
}
var query = redirectURL.Query()
query.Set("token", token)
redirectURL.RawQuery = query.Encode()
return c.Redirect(redirectURL.String())
}
//Sign in process
var query = redirectURL.Query()
query.Set("code", code)
query.Set("redirect", redirectURL.RequestURI())
query.Set("identifier", claims.Identifier)
redirectURL.RawQuery = query.Encode()
redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)
return c.Redirect(redirectURL.String())
}
}
// SignInByOAuth is responsible for redirecting the user to the OAuth authorization URL for given provider
// A cookie is stored in user's browser with a random identifier that is later used to verify the authenticity of the request
func SignInByOAuth() web.HandlerFunc {
return func(c *web.Context) error {
c.Response.Header().Add("X-Robots-Tag", "noindex")
provider := c.Param("provider")
redirect := c.QueryParam("redirect")
if redirect == "" {
redirect = c.BaseURL()
} else if redirect != c.BaseURL() && !strings.HasPrefix(redirect, c.BaseURL()+"/") {
return c.Forbidden()
}
redirectURL, _ := url.ParseRequestURI(redirect)
redirectURL.ResolveReference(c.Request.URL)
if c.IsAuthenticated() && redirectURL.Path != fmt.Sprintf("/oauth/%s/echo", provider) {
return c.Redirect(redirect)
}
authURL := &query.GetOAuthAuthorizationURL{
Provider: provider,
Redirect: redirect,
Identifier: c.SessionID(),
}
if err := bus.Dispatch(c, authURL); err != nil {
return c.Failure(err)
}
return c.Redirect(authURL.Result)
}
}