accountService.go 7.53 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
package service

import (
	"context"
	"net/http"
	"os"
	"fmt"
	"encoding/json"
	"github.com/okta/okta-sdk-golang/v2/okta"
	"github.com/okta/okta-sdk-golang/v2/okta/query"
)

type User struct {
14
15
	FirstName string `json:"firstname"`
	LastName string `json:"lastname"`
16
17
	Email string `json:"email"`
	Login string `json:"login"`
18
	Password string `json:"password"`
19
20
21
22
23
24
25
}

type Users struct {
	UserList []User `json:"users"`
}

func printUser(user User) {
26
	fmt.Print("\n Firstname:", user.FirstName, "\n Lastname:", user.LastName, "\n Email:", user.Email)
27
28
29
30
31
32
33
34
35
36
}

func printAllUsers(users []User) {
	for index, u := range users {
        fmt.Printf("user at user[%d] is : %v \n", index, u)
	}
}

func GetUsers() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
37
		fmt.Printf("\n Fetching users...")
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

		_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		users, _, err := client.User.ListUsers(context.Background(), &query.Params{})
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		allUsers := []User{}

		for _, user := range users {

			User := User{
				FirstName: 	fmt.Sprintf("%v", (*user.Profile)["firstName"]),
				LastName: 	fmt.Sprintf("%v", (*user.Profile)["lastName"]),
				Email: 			fmt.Sprintf("%v", (*user.Profile)["email"]),
				Login:			fmt.Sprintf("%v", (*user.Profile)["login"]),
			}

			allUsers = append(allUsers, User)
		}

		usr := Users {
			allUsers,
		}

		printAllUsers(allUsers)
		if err := json.NewEncoder(w).Encode(usr); 
		err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}
	}
}

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
// Gets user data from OKTA SDK API from user.id
func GetUser(w http.ResponseWriter, r *http.Request) User {
	tempUserData := User{}

	_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
	if err != nil {
		ReturnError(w, http.StatusInternalServerError, err.Error())
		return tempUserData
	}

	if err := json.NewDecoder(r.Body).Decode(&tempUserData); 
	err != nil {
		ReturnError(w, http.StatusInternalServerError, err.Error())
		return tempUserData
	}

	user, resp, err := client.User.GetUser(context.Background(), tempUserData.Email)
		if _, err := w.Write([]byte(resp.Self)); err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return tempUserData
		}

	tempUserData.FirstName = fmt.Sprintf("%v", (*user.Profile)["firstName"])
	tempUserData.LastName = fmt.Sprintf("%v", (*user.Profile)["lastName"])
	tempUserData.Email = fmt.Sprintf("%v", (*user.Profile)["email"])
	tempUserData.Login = fmt.Sprintf("%v", (*user.Profile)["login"])

	return tempUserData
}

108
109
func CreateUser() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
110
		fmt.Printf("\n Creating new user...")
111
112
113
114
115
116
117

		_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

118
		tempUserData := User{}
119

120
		if err := json.NewDecoder(r.Body).Decode(&tempUserData); 
121
122
123
124
125
		err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

126
		tempUserData.Login = tempUserData.Email
127
128


129
		p := &okta.PasswordCredential{
130
			Value: tempUserData.Password,
131
132
133
134
135
136
137
		}

		uc := &okta.UserCredentials{
			Password: p,
		}

		profile := okta.UserProfile{}
138
139
140
141
		profile["firstName"] = tempUserData.FirstName
		profile["lastName"] = tempUserData.LastName
		profile["email"] = tempUserData.Email
		profile["login"] = tempUserData.Login
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

		u := &okta.CreateUserRequest{
			Credentials: uc,
			Profile:     &profile,
		}

		qp := query.NewQueryParams(query.WithActivate(true))

		user, _, err := client.User.CreateUser(context.Background(), *u, qp)
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		newUser := User{
				FirstName: fmt.Sprintf("%v", (*user.Profile)["firstName"]),
				LastName: fmt.Sprintf("%v", (*user.Profile)["lastName"]),
				Email: fmt.Sprintf("%v", (*user.Profile)["email"]),
				Login:fmt.Sprintf("%v", (*user.Profile)["login"]),
			}
		
163
		fmt.Printf("\n User activation success. New user created:")
164
		printUser(newUser)
165
166

		w.WriteHeader(http.StatusOK)
167
	}
168
169
170
171
}

func RemoveUser() http.HandlerFunc {
	return func(w http.ResponseWriter, r*http.Request) {
172
173
		userId := GetUser(w, r).Email
		fmt.Printf("\n Removing User: %v", userId)
174
175
176
177
178
179
180
181

		_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		// Deactivate user first
182
		resp, err := client.User.DeactivateUser(context.Background(), userId, &query.Params{})
183
184
185
186
187
188
189
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}


		// Response.Message?
190
191
		if _, err := w.Write([]byte(resp.Self)); 
		err != nil {
192
193
194
195
196
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		// Now Remove user
197
		response, err := client.User.DeactivateOrDeleteUser(context.Background(), userId, &query.Params{})
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
		if _, err := w.Write([]byte(response.Self)); 
		err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

		fmt.Printf("\n User removal success")
	}
}

func RecoverUserPassword() http.HandlerFunc {
	return func(w http.ResponseWriter, r*http.Request) {
		fmt.Printf("\n User requesting password reset. Sending email with password recovery link")

		_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
213
214
215
216
217
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

218
219
		_, resp, err := client.User.ForgotPasswordGenerateOneTimeToken(context.Background(), GetUser(w, r).Email, &query.Params{})
		if _, err := w.Write([]byte(resp.Self)); 
220
		err != nil {
221
222
223
224
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

225
		fmt.Println("\n A password recovery email has been sent to the user")
226
	}
227
228
}

229
230
231
func UpdateUserData() http.HandlerFunc {
	return func (w http.ResponseWriter, r*http.Request) {
		fmt.Printf("\n User requesting profile data update")
232
233
234
235
236
237
238

		_, client, err := okta.NewClient(context.Background(), okta.WithOrgUrl("https://" + os.Getenv("CLIENT_ID")), okta.WithToken("007XkBhvAfeVf1jUB0xhdwQJJEvWNSBQ6bbO4MoEaV"))
		if err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}

239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
		// Parse the userData and append to new okta.user object
		userData := User{}
		if err := json.NewDecoder(r.Body).Decode(&userData); 
		err != nil {
		ReturnError(w, http.StatusInternalServerError, err.Error())
		return
		}

		profile := okta.UserProfile{}
		profile["firstName"] = userData.FirstName
		profile["lastName"] = userData.LastName
		profile["email"] = userData.Email
		profile["login"] = userData.Login

		updatedUser := &okta.User{
		Profile: &profile,
}

		_, resp, err := client.User.UpdateUser(context.Background(), userData.Email, *updatedUser, &query.Params{})
258
259
260
261
262
		if _, err := w.Write([]byte(resp.Self)); 
		err != nil {
			ReturnError(w, http.StatusInternalServerError, err.Error())
			return
		}
263

264
		fmt.Printf("\n User data has been updated for user: %v", userData.Email)
265
	}
266
}