-
Notifications
You must be signed in to change notification settings - Fork 3
/
gf_service_handlers__auth0.go
353 lines (280 loc) · 10.8 KB
/
gf_service_handlers__auth0.go
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
GloFlow application and media management/publishing platform
Copyright (C) 2022 Ivan Trajkovic
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package gf_identity
import (
"fmt"
"net/http"
"context"
"encoding/base64"
"github.com/gloflow/gloflow/go/gf_core"
"github.com/gloflow/gloflow/go/gf_rpc_lib"
"github.com/gloflow/gloflow/go/gf_extern_services/gf_auth0"
"github.com/gloflow/gloflow/go/gf_identity/gf_identity_core"
)
//------------------------------------------------
func initHandlersAuth0(pKeyServer *gf_identity_core.GFkeyServerInfo,
pHTTPmux *http.ServeMux,
pAuthenticator *gf_auth0.GFauthenticator,
pConfig *gf_auth0.GFconfig,
pServiceInfo *gf_identity_core.GFserviceInfo,
pRuntimeSys *gf_core.RuntimeSys) {
//---------------------
// METRICS
handlersEndpointsLst := []string{
"/v1/identity/auth0/api_token/generate",
"/v1/identity/auth0/login",
"/v1/identity/auth0/login_callback",
"/v1/identity/auth0/logout",
"/v1/identity/auth0/logout_callback",
}
metricsGroupNameStr := "auth0"
metrics := gf_rpc_lib.MetricsCreateForHandlers(metricsGroupNameStr, pServiceInfo.NameStr, handlersEndpointsLst)
//---------------------
// RPC_HANDLER_RUNTIME
rpcHandlerRuntime := &gf_rpc_lib.GFrpcHandlerRuntime {
Mux: pHTTPmux,
Metrics: metrics,
StoreRunBool: true,
SentryHub: nil,
AuthSubsystemTypeStr: pServiceInfo.AuthSubsystemTypeStr,
// url redirected too if user not logged in and tries to access auth handler
AuthLoginURLstr: "/v1/identity/login_ui",
AuthKeyServer: pKeyServer,
EnableEventsBool: true,
}
//---------------------
// API_TOKEN_GENERATE
gf_rpc_lib.CreateHandlerHTTPwithAuth(true, "/v1/identity/auth0/api_token/generate",
func(pCtx context.Context, pResp http.ResponseWriter, pReq *http.Request) (map[string]interface{}, *gf_core.GFerror) {
//---------------------
// INPUT
userID, _ := gf_identity_core.GetUserIDfromCtx(pCtx)
iMap, gfErr := gf_core.HTTPgetInput(pReq, pRuntimeSys)
if gfErr != nil {
return nil, gfErr
}
audienceStr := iMap["audience_str"].(string)
// ADD!! - set these to proper secret values
appClientIDstr := ""
appClientSecretStr := ""
input := &gf_identity_core.GFauth0inputAPItokenGenerate{
UserID: userID,
AppClientIDstr: appClientIDstr,
AppClientSecretStr: appClientSecretStr,
AudienceStr: audienceStr,
Auth0appDomainStr: pConfig.Auth0domainStr,
}
//---------------------
if pReq.Method == "GET" {
tokenStr, gfErr := gf_identity_core.Auth0apiTokenGeneratePipeline(input,
pCtx, pRuntimeSys)
if gfErr != nil {
return nil, gfErr
}
//------------------
// OUTPUT
outputMap := map[string]interface{}{
"token_str": tokenStr,
}
return outputMap, nil
//------------------
}
return nil, nil
},
rpcHandlerRuntime,
pRuntimeSys)
//---------------------
// Auth0 may need to redirect back to the application's Login Initiation endpoint, using OIDC third-party initiated login
gf_rpc_lib.CreateHandlerHTTPwithAuth(false, "/v1/identity/auth0/login",
func(pCtx context.Context, pResp http.ResponseWriter, pReq *http.Request) (map[string]interface{}, *gf_core.GFerror) {
if pReq.Method == "GET" {
sessionIDstr, gfErr := gf_identity_core.Auth0loginPipeline(pCtx, pRuntimeSys)
if gfErr != nil {
return nil, gfErr
}
//------------------
// HTTP_REDIRECT - redirect user to Auth0 login url
// IMPORTANT!! - disable client caching for this endpoint, to avoid incosistent behavior
gf_core.HTTPdisableCachingOfResponse(pResp)
auth0appStateBase64str := base64.StdEncoding.EncodeToString([]byte(string(sessionIDstr)))
http.Redirect(pResp,
pReq,
pAuthenticator.AuthCodeURL(auth0appStateBase64str),
301)
//------------------
}
return nil, nil
},
rpcHandlerRuntime,
pRuntimeSys)
//---------------------
// user redirected to this URL by Auth0 on successful login
gf_rpc_lib.CreateHandlerHTTPwithAuth(false, "/v1/identity/auth0/login_callback",
func(pCtx context.Context, pResp http.ResponseWriter, pReq *http.Request) (map[string]interface{}, *gf_core.GFerror) {
//------------------
// INPUT
qsMap := pReq.URL.Query()
// "code" arg - provided by Auth0
if _, ok := qsMap["code"]; !ok {
gfErr := gf_core.ErrorCreate("auth0 login callback request is missing the 'code' qs argument",
"verify__input_data_missing_in_req_error",
map[string]interface{}{},
nil, "gf_identity", pRuntimeSys)
return nil, gfErr
}
//------------------
// CODE
// 45 char length string
codeStr := qsMap["code"][0]
//------------------
// STATE
// "state" arg - this is the session ID set by GF handler initially via a cookie,
// and Auth0 enforces the "state" symbol name.
if _, ok := qsMap["state"]; !ok {
gfErr := gf_core.ErrorCreate("auth0 login callback request is missing the 'state' qs argument",
"verify__input_data_missing_in_req_error",
map[string]interface{}{},
nil, "gf_identity", pRuntimeSys)
return nil, gfErr
}
// state is base64 encoded session_id, so it needs to be decoded and casted into an GF_ID
auth0providedStateBase64str := qsMap["state"][0]
auth0providedStateStr, _ := base64.StdEncoding.DecodeString(auth0providedStateBase64str)
sessionID := gf_core.GF_ID(auth0providedStateStr)
//------------------
input := &gf_identity_core.GFauth0inputLoginCallback{
CodeStr: codeStr,
SessionID: sessionID,
Auth0appDomainStr: pConfig.Auth0domainStr,
}
//------------------
// ADD!! - create login attempt record in the DB
//------------------
output, gfErr := gf_identity_core.Auth0loginCallbackPipeline(input,
pAuthenticator,
pCtx,
pRuntimeSys)
if gfErr != nil {
return nil, gfErr
}
//---------------------
// COOKIES
// SESSION_ID - sets gf_sess cookie
gf_identity_core.CreateSessionIDcookie(string(sessionID),
pServiceInfo.DomainForAuthCookiesStr,
pResp)
// JWT - sets "Authorization" cookie
gf_identity_core.CreateAuthCookie(output.JWTtokenStr,
pServiceInfo.DomainForAuthCookiesStr,
pResp)
//------------------
// HTTP_REDIRECT - redirect user to logged in page
// IMPORTANT!! - disable client caching for this endpoint, to avoid incosistent behavior
gf_core.HTTPdisableCachingOfResponse(pResp)
/*
IMPORTANT!! - currently in the Auth0 login_callback, once all login initialization is complete,
the client is redirected to the login_page with a QS arg "login_success" set to 1.
this indicates to the login page that it should not initialize into its standard login state,
but instead should indicate to the user that login has succeeded and then via JS
(with a time delay) redirect to Home.
this is needed to handle a race condition where if user was redirected to home via a
server redirect (HTTP 3xx response) the browser wouldnt have time to set the needed
auth cookies that are necessary for the Home handler to authenticate.
the recommended solution for this is to do the redirection via client/JS code with a slight
time delay, giving the browser time to set the cookies.
*/
homeUrlStr := "/v1/identity/login_ui?login_success=1"
http.Redirect(pResp,
pReq,
homeUrlStr,
301)
//------------------
return nil, nil
},
rpcHandlerRuntime,
pRuntimeSys)
//---------------------
gf_rpc_lib.CreateHandlerHTTPwithAuth(true, "/v1/identity/auth0/logout",
func(pCtx context.Context, pResp http.ResponseWriter, pReq *http.Request) (map[string]interface{}, *gf_core.GFerror) {
if pReq.Method == "GET" {
//------------------
/*
IMPORTANT!! - redirect user to Auth0 logout url, which will log them out of Auth0
and any third-party identity providers. this does not log them out of the GF
application, which needs to be done separatelly.
*/
logoutURLstr := fmt.Sprintf("https://%s/v2/logout?client_id=%s&returnTo=%s",
pConfig.Auth0domainStr,
pConfig.Auth0clientIDstr,
pConfig.Auth0logoutCallbackURLstr)
pRuntimeSys.LogNewFun("DEBUG", "redirecting to Auth0 logout url...",
map[string]interface{}{"logout_url_str": logoutURLstr})
// IMPORTANT!! - disable client caching for this endpoint, to avoid incosistent behavior
gf_core.HTTPdisableCachingOfResponse(pResp)
// HTTP_REDIRECT
http.Redirect(pResp,
pReq,
logoutURLstr,
301)
//------------------
}
return nil, nil
},
rpcHandlerRuntime,
pRuntimeSys)
//---------------------
// user redirected to this URL by Auth0 on successful logout.
gf_rpc_lib.CreateHandlerHTTPwithAuth(false, "/v1/identity/auth0/logout_callback",
func(pCtx context.Context, pResp http.ResponseWriter, pReq *http.Request) (map[string]interface{}, *gf_core.GFerror) {
if pReq.Method == "GET" {
//------------------
// INPUT
/*
session_id in this handler has to be fetched directly from request cookies instead from
context because this handler is not authed, and so in gf_rpc the auth path is not chosen
and context is not enriched with the session_id.
*/
sessionID, existsBool := gf_identity_core.GetSessionID(pReq, pRuntimeSys)
if !existsBool {
gfErr := gf_core.ErrorCreate("session_id is missing from auth0 logout_callback handler request cookies",
"http_cookie",
map[string]interface{}{},
nil, "gf_identity", pRuntimeSys)
return nil, gfErr
}
//------------------
// IMPORTANT!! - delete GF application session
gfErr := gf_identity_core.Auth0logoutPipeline(sessionID, pCtx, pRuntimeSys)
if gfErr != nil {
return nil, gfErr
}
// unset all session cookies
gf_identity_core.DeleteCookies(pResp)
afterLogoutURLstr := "/landing/main"
// IMPORTANT!! - disable client caching for this endpoint, to avoid incosistent behavior
gf_core.HTTPdisableCachingOfResponse(pResp)
// HTTP_REDIRECT
http.Redirect(pResp,
pReq,
afterLogoutURLstr,
301)
}
return nil, nil
},
rpcHandlerRuntime,
pRuntimeSys)
//---------------------
}