-
Notifications
You must be signed in to change notification settings - Fork 38
/
okta_profile.go
269 lines (231 loc) · 9.71 KB
/
okta_profile.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
package internalapi
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strings"
"github.com/go-openapi/runtime/middleware"
"github.com/spf13/viper"
"go.uber.org/zap"
"github.com/transcom/mymove/pkg/appcontext"
"github.com/transcom/mymove/pkg/cli"
oktaop "github.com/transcom/mymove/pkg/gen/internalapi/internaloperations/okta_profile"
"github.com/transcom/mymove/pkg/gen/internalmessages"
"github.com/transcom/mymove/pkg/handlers"
"github.com/transcom/mymove/pkg/handlers/authentication/okta"
)
// GetOktaProfileHandler gets Okta Profile via GET /okta-profile
type GetOktaProfileHandler struct {
handlers.HandlerConfig
}
// Handle performs a GET request from Okta API, returns values in profile object from response
// Could not use data from sessions since access token data does not change when profile is updated
func (h GetOktaProfileHandler) Handle(params oktaop.ShowOktaInfoParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
// if the "Local Sign In" is clicked we are going to send back dummy values
sess := appCtx.Session()
if sess.IDToken == "devlocal" {
dummyEdipi := "1234567890"
oktaUserPayload := internalmessages.OktaUserProfileData{
Login: "devlocal@mail.com",
Email: "devlocal@mail.com",
FirstName: "dev",
LastName: "local",
CacEdipi: &dummyEdipi,
Sub: "devlocal",
}
return oktaop.NewShowOktaInfoOK().WithPayload(&oktaUserPayload), nil
}
// getting okta id of user from session, to be used for api call
oktaUserID := appCtx.Session().OktaSessionInfo.Sub
// setting viper so we can access the api key in the env vars
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
apiKey := v.GetString(cli.OktaAPIKeyFlag)
// getting okta domain url for request
provider, err := okta.GetOktaProviderForRequest(params.HTTPRequest)
if err != nil {
return nil, err
}
// need to pull this payload since it is wrapped in a profile object so resp
// body can populate accurately
user := internalmessages.UpdateOktaUserProfileData{}
// getting the api call url from provider.go
baseURL := provider.GetUserURL(oktaUserID)
// making HTTP request to Okta Users API to update user
// this is done via a POST request for partial profile updates
// https://developer.okta.com/docs/reference/api/users/#update-current-user-s-profile
req, _ := http.NewRequest("GET", baseURL, bytes.NewReader([]byte("")))
h := req.Header
h.Add("Authorization", "SSWS "+apiKey)
h.Add("Accept", "application/json")
h.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
appCtx.Logger().Error("could not execute request", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
appCtx.Logger().Error("could not read response body", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusInternalServerError {
return oktaop.NewShowOktaInfoInternalServerError(), err
}
if resp.StatusCode == http.StatusBadRequest {
return oktaop.NewShowOktaInfoBadRequest(), err
}
if resp.StatusCode == http.StatusForbidden {
return oktaop.NewShowOktaInfoForbidden(), err
}
}
defer resp.Body.Close()
err = json.Unmarshal(body, &user)
if err != nil {
appCtx.Logger().Error("could not unmarshal body", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
// the return value has to be of type OktaUserPayload
// our initial objet was of type UpdateOktaUserPayload, so needs to be changed
// OktaUserPayload is not wrapped in a profile object
oktaUserPayload := internalmessages.OktaUserProfileData{
Login: user.Profile.Login,
Email: user.Profile.Email,
FirstName: user.Profile.FirstName,
LastName: user.Profile.LastName,
CacEdipi: user.Profile.CacEdipi,
Sub: user.Profile.Sub,
}
appCtx.Logger().Info("getting okta profile", zap.Any("okta profile", oktaUserPayload))
return oktaop.NewShowOktaInfoOK().WithPayload(&oktaUserPayload), nil
})
}
// GetOktaProfileHandler gets Okta Profile via GET /okta-profile
type UpdateOktaProfileHandler struct {
handlers.HandlerConfig
}
type ErrorResponse struct {
ErrorCode string `json:"errorCode"`
ErrorSummary string `json:"errorSummary"`
ErrorLink string `json:"errorLink"`
ErrorID string `json:"errorId"`
ErrorCauses []struct {
ErrorSummary string `json:"errorSummary"`
} `json:"errorCauses"`
}
// Handle implements okta_profile.UpdateOktaInfoHandler
// following the API call docs here: https://developer.okta.com/docs/reference/api/oidc/#client-authentication-methods
func (h UpdateOktaProfileHandler) Handle(params oktaop.UpdateOktaInfoParams) middleware.Responder {
return h.AuditableAppContextFromRequestWithErrors(params.HTTPRequest,
func(appCtx appcontext.AppContext) (middleware.Responder, error) {
// getting okta id of user from session, to be used for api call
oktaUserID := appCtx.Session().OktaSessionInfo.Sub
// setting viper so we can access the api key in the env vars
v := viper.New()
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()
apiKey := v.GetString(cli.OktaAPIKeyFlag)
// getting okta domain url for post request
provider, err := okta.GetOktaProviderForRequest(params.HTTPRequest)
if err != nil {
return nil, err
}
// payload is what is submitted from frontend, should contain
// {email, login, firstName, lastName, cac_edipi}
payload := params.UpdateOktaUserProfileData
// getting the api call url from provider.go
baseURL := provider.GetUserURL(oktaUserID)
body, _ := json.Marshal(payload)
// making HTTP request to Okta Users API to update user
// this is done via a POST request for partial profile updates
// https://developer.okta.com/docs/reference/api/users/#update-current-user-s-profile
req, _ := http.NewRequest("POST", baseURL, bytes.NewReader(body))
h := req.Header
h.Add("Authorization", "SSWS "+apiKey)
h.Add("Accept", "application/json")
h.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
appCtx.Logger().Error("could not execute request", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
body, err = io.ReadAll(resp.Body)
if err != nil {
appCtx.Logger().Error("could not read response body", zap.Any("returned status", resp.Status))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
defer resp.Body.Close()
// we are going to check for an okta error response
var response ErrorResponse
err = json.Unmarshal(body, &response)
if err != nil {
appCtx.Logger().Error("could not unmarshal body", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
// if there's an error code, we will see what the error will be and display it to the user
if response.ErrorCode != "" {
errorSummary := response.ErrorSummary
fieldError := strings.TrimSpace(strings.SplitN(errorSummary, "Api validation failed:", 2)[1])
// changing json fields to something more easier to read
switch fieldError {
case "cac_edipi":
fieldError = "Dod ID | EDIPI"
case "firstName":
fieldError = "Last Name"
case "lastName":
fieldError = "First Name"
case "email":
fieldError = "Email"
default:
fieldError = ""
}
// extracting the part of the response that we want
errorDescription := response.ErrorCauses[0].ErrorSummary
extractedDescription := strings.TrimSpace(strings.SplitN(errorDescription, ":", 2)[1])
errPayload := internalmessages.ValidationError{}
errPayload.Detail = handlers.FmtString(string(fieldError + ": " + extractedDescription))
return oktaop.NewUpdateOktaInfoUnprocessableEntity().WithPayload(errPayload), err
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusInternalServerError {
return oktaop.NewShowOktaInfoInternalServerError(), err
}
if resp.StatusCode == http.StatusBadRequest {
return oktaop.NewUpdateOktaInfoBadRequest(), err
}
if resp.StatusCode == http.StatusForbidden {
return oktaop.NewShowOktaInfoForbidden(), err
}
}
err = json.Unmarshal(body, &payload)
if err != nil {
appCtx.Logger().Error("could not unmarshal body", zap.Error(err))
return handlers.ResponseForError(appCtx.Logger(), err), err
}
// when calling Okta, we have to have the body wrapped in a JSON profile object
// here we will take the repsonse and convert it to a struct that doesn't have profile wrap
oktaUserPayload := internalmessages.OktaUserProfileData{
Login: payload.Profile.Login,
Email: payload.Profile.Email,
FirstName: payload.Profile.FirstName,
LastName: payload.Profile.LastName,
CacEdipi: payload.Profile.CacEdipi,
Sub: oktaUserID,
}
appCtx.Logger().Info("updated okta profile", zap.Any("okta profile", oktaUserPayload))
// setting app context values with updated values so frontend can update
appCtx.Session().OktaSessionInfo.Login = oktaUserPayload.Login
appCtx.Session().OktaSessionInfo.Email = oktaUserPayload.Email
appCtx.Session().OktaSessionInfo.FirstName = oktaUserPayload.FirstName
appCtx.Session().OktaSessionInfo.LastName = oktaUserPayload.LastName
appCtx.Session().OktaSessionInfo.Edipi = *oktaUserPayload.CacEdipi
return oktaop.NewUpdateOktaInfoOK().WithPayload(&oktaUserPayload), nil
})
}