-
Notifications
You must be signed in to change notification settings - Fork 634
Expand file tree
/
Copy pathazure-ad.go
More file actions
247 lines (228 loc) · 6.86 KB
/
azure-ad.go
File metadata and controls
247 lines (228 loc) · 6.86 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
package auth
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/gravitl/netmaker/database"
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/logic"
"github.com/gravitl/netmaker/models"
proLogic "github.com/gravitl/netmaker/pro/logic"
"github.com/gravitl/netmaker/servercfg"
"golang.org/x/oauth2"
"golang.org/x/oauth2/microsoft"
)
var azure_ad_functions = map[string]interface{}{
init_provider: initAzureAD,
get_user_info: getAzureUserInfo,
handle_callback: handleAzureCallback,
handle_login: handleAzureLogin,
verify_user: verifyAzureUser,
}
// == handle azure ad authentication here ==
func initAzureAD(redirectURL string, clientID string, clientSecret string) {
auth_provider = &oauth2.Config{
RedirectURL: redirectURL,
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"User.Read", "email", "profile", "openid"},
Endpoint: microsoft.AzureADEndpoint(logic.GetAzureTenant()),
}
}
func handleAzureLogin(w http.ResponseWriter, r *http.Request) {
appName := r.Header.Get("X-Application-Name")
if appName == "" {
appName = logic.NetmakerDesktopApp
}
var oauth_state_string = logic.RandomString(user_signin_length)
if auth_provider == nil {
handleOauthNotConfigured(w)
return
}
if err := logic.SetState(appName, oauth_state_string); err != nil {
handleOauthNotConfigured(w)
return
}
var url = auth_provider.AuthCodeURL(oauth_state_string)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleAzureCallback(w http.ResponseWriter, r *http.Request) {
var rState, rCode = getStateAndCode(r)
state, err := logic.GetState(rState)
if err != nil {
handleOauthNotValid(w)
return
}
content, err := getAzureUserInfo(rState, rCode)
if err != nil {
logger.Log(1, "error when getting user info from azure:", err.Error())
if strings.Contains(err.Error(), "invalid oauth state") || strings.Contains(err.Error(), "failed to fetch user email from SSO state") {
handleOauthNotValid(w)
return
}
handleOauthNotConfigured(w)
return
}
var inviteExists bool
// check if invite exists for User
in, err := logic.GetUserInvite(content.Email)
if err == nil {
inviteExists = true
}
// check if user approval is already pending
if !inviteExists && (logic.IsPendingUser(content.Email) || logic.IsPendingUser(content.UserPrincipalName)) {
handleOauthUserSignUpApprovalPending(w)
return
}
user, err := logic.GetUser(content.UserPrincipalName)
if err != nil {
if database.IsEmptyRecord(err) { // user must not exist, so try to make one
if inviteExists {
// create user
user, err := proLogic.PrepareOauthUserFromInvite(in)
if err != nil {
logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
return
}
user.UserName = content.UserPrincipalName
user.ExternalIdentityProviderID = string(content.ID)
if err = logic.CreateUser(&user); err != nil {
handleSomethingWentWrong(w)
return
}
logic.DeleteUserInvite(content.Email)
logic.DeletePendingUser(content.UserPrincipalName)
logic.DeletePendingUser(content.Email)
} else {
if !isEmailAllowed(content.Email) {
handleOauthUserNotAllowedToSignUp(w)
return
}
err = logic.InsertPendingUser(&models.User{
UserName: content.UserPrincipalName,
ExternalIdentityProviderID: string(content.ID),
AuthType: models.OAuth,
})
if err != nil {
handleSomethingWentWrong(w)
return
}
handleFirstTimeOauthUserSignUp(w)
return
}
} else {
handleSomethingWentWrong(w)
return
}
} else {
// if user exists, then ensure user's auth type is
// oauth before proceeding.
if user.AuthType == models.BasicAuth {
logger.Log(0, "invalid auth type: basic_auth")
handleAuthTypeMismatch(w)
return
}
}
user, err = logic.GetUser(content.UserPrincipalName)
if err != nil {
handleOauthUserNotFound(w)
return
}
if user.AccountDisabled {
handleUserAccountDisabled(w)
return
}
userRole, err := logic.GetRole(user.PlatformRoleID)
if err != nil {
handleSomethingWentWrong(w)
return
}
if userRole.DenyDashboardAccess {
handleOauthUserNotAllowed(w)
return
}
var newPass, fetchErr = logic.FetchPassValue("")
if fetchErr != nil {
return
}
// send a netmaker jwt token
var authRequest = models.UserAuthParams{
UserName: content.UserPrincipalName,
Password: newPass,
}
var jwt, jwtErr = logic.VerifyAuthRequest(authRequest, state.AppName)
if jwtErr != nil {
logger.Log(1, "could not parse jwt for user", authRequest.UserName)
return
}
logic.LogEvent(&models.Event{
Action: models.Login,
Source: models.Subject{
ID: user.UserName,
Name: user.UserName,
Type: models.UserSub,
},
TriggeredBy: user.UserName,
Target: models.Subject{
ID: models.DashboardSub.String(),
Name: models.DashboardSub.String(),
Type: models.DashboardSub,
Info: user,
},
Origin: models.Dashboard,
})
logger.Log(1, "completed azure OAuth sigin in for", user.UserName)
http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+user.UserName, http.StatusPermanentRedirect)
}
func getAzureUserInfo(state string, code string) (*OAuthUser, error) {
oauth_state_string, isValid := logic.IsStateValid(state)
if (!isValid || state != oauth_state_string) && !isStateCached(state) {
return nil, fmt.Errorf("invalid oauth state")
}
var token, err = auth_provider.Exchange(context.Background(), code, oauth2.SetAuthURLParam("prompt", "login"))
if err != nil {
return nil, fmt.Errorf("code exchange failed: %s", err.Error())
}
var data []byte
data, err = json.Marshal(token)
if err != nil {
return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
}
var httpReq, reqErr = http.NewRequest("GET", "https://graph.microsoft.com/v1.0/me", nil)
if reqErr != nil {
return nil, fmt.Errorf("failed to create request to microsoft")
}
httpReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
response, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("failed getting user info: %s", err.Error())
}
defer response.Body.Close()
contents, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("failed reading response body: %s", err.Error())
}
var userInfo = &OAuthUser{}
if err = json.Unmarshal(contents, userInfo); err != nil {
return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
}
userInfo.AccessToken = string(data)
if userInfo.Email == "" {
userInfo.Email = getUserEmailFromClaims(token.AccessToken)
}
if userInfo.Email == "" && userInfo.UserPrincipalName != "" {
userInfo.Email = userInfo.UserPrincipalName
}
if userInfo.Email == "" {
err = errors.New("failed to fetch user email from SSO state")
return userInfo, err
}
return userInfo, nil
}
func verifyAzureUser(token *oauth2.Token) bool {
return token.Valid()
}