-
Notifications
You must be signed in to change notification settings - Fork 14
/
auth_oauth2.go
206 lines (175 loc) · 6.08 KB
/
auth_oauth2.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
package main
import (
"encoding/json"
"fmt"
"golang.org/x/net/context"
//"golang.org/x/oauth2"
"io/ioutil"
"net/http"
"strings"
"time"
)
const maxAgeSecondsRedirCookie = 120
const redirCookieName = "oauth2_redir"
const oauth2LoginBeginPath = "/auth/oauth2/login"
func (state *RuntimeState) oauth2DoRedirectoToProviderHandler(w http.ResponseWriter, r *http.Request) {
if state.Config.Oauth2.Config == nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println("asking for oauth2, but it is not defined")
return
}
if !state.Config.Oauth2.Enabled {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Oauth2 is not enabled in for this system")
logger.Println("asking for oauth2, but it is not enabled")
return
}
cookieVal, err := genRandomString()
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println(err)
return
}
// we have to create new context and set redirector...
expiration := time.Now().Add(time.Duration(maxAgeSecondsRedirCookie) * time.Second)
stateString, err := genRandomString()
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println(err)
return
}
cookie := http.Cookie{Name: redirCookieName, Value: cookieVal,
Expires: expiration, Path: "/", HttpOnly: true}
http.SetCookie(w, &cookie)
pending := pendingAuth2Request{
ExpiresAt: expiration,
state: stateString,
ctx: context.Background()}
state.Mutex.Lock()
state.pendingOauth2[cookieVal] = pending
state.Mutex.Unlock()
http.Redirect(w, r, state.Config.Oauth2.Config.AuthCodeURL(stateString), http.StatusFound)
}
func httpGet(client *http.Client, url string) ([]byte, error) {
r, err := client.Get(url)
if err != nil {
return nil, err
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if r.StatusCode >= 300 {
return nil, fmt.Errorf(string(body))
}
logger.Debugf(8, "HTTP GET %s: %s %s", url, r.Status, string(body))
return body, nil
}
func (state *RuntimeState) oauth2RedirectPathHandler(w http.ResponseWriter, r *http.Request) {
if state.Config.Oauth2.Config == nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println("asking for oauth2, but it is not defined")
return
}
if !state.Config.Oauth2.Enabled {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Oauth2 is not enabled in for this system")
logger.Println("asking for oauth2, but it is not enabled")
return
}
redirCookie, err := r.Cookie(redirCookieName)
if err != nil {
if err == http.ErrNoCookie {
state.writeFailureResponse(w, r, http.StatusBadRequest, "Missing setup cookie!")
logger.Println(err)
return
}
// TODO: this is probably a user error? send back to oath2 login path?
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println(err)
return
}
index := redirCookie.Value
state.Mutex.Lock()
pending, ok := state.pendingOauth2[index]
state.Mutex.Unlock()
if !ok {
// clear cookie here!!!!
state.writeFailureResponse(w, r, http.StatusBadRequest, "Invalid setup cookie!")
logger.Println(err)
return
}
if r.URL.Query().Get("state") != pending.state {
logger.Printf("state does not match")
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
//if Debug {
//logger.Printf("req : %+v", r)
//}
oauth2Token, err := state.Config.Oauth2.Config.Exchange(pending.ctx, r.URL.Query().Get("code"))
if err != nil {
logger.Printf("failed to get token: ctx: %+v", pending.ctx)
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
client := state.Config.Oauth2.Config.Client(pending.ctx, oauth2Token)
//client.Get("...")
body, err := httpGet(client, state.Config.Oauth2.UserinfoUrl)
if err != nil {
logger.Printf("fail to fetch %s (%s) ", state.Config.Oauth2.UserinfoUrl, err.Error())
http.Error(w, "Failed to get userinfo from url: "+err.Error(), http.StatusInternalServerError)
return
}
var data struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Login string `json:"login"`
Username string `json:"username"`
Email string `json:"email"`
Attributes map[string][]string `json:"attributes"`
}
logger.Debugf(3, "Userinfo body:'%s'", string(body))
err = json.Unmarshal(body, &data)
if err != nil {
logger.Printf("failed to unmarshall userinfo to fetch %s ", body)
http.Error(w, "Failed to get unmarshall userinfo: "+err.Error(), http.StatusInternalServerError)
return
}
// The Name field could also be useful
logger.Debugf(2, "%+v", data)
// Check if name is there..
//Make new auth cookie
cookieVal, err := genRandomString()
if err != nil {
state.writeFailureResponse(w, r, http.StatusInternalServerError, "error internal")
logger.Println(err)
return
}
// TODO: we need a more robust way to get the username and to add some filters. This
// mechanism is ok for 0.2 but not for 0.3.
username := data.Login
if username == "" {
components := strings.Split(data.Email, "@")
if len(components[0]) < 1 {
http.Error(w, "Email from userinfo is invalid: ", http.StatusInternalServerError)
return
}
username = strings.ToLower(components[0])
}
// TODO: we should enhance oath2 to limit who can login by either full username OR
// source domain.
expiration := time.Now().Add(time.Duration(maxAgeSecondsAuthCookie) * time.Second)
savedUserInfo := authInfo{Username: username, ExpiresAt: expiration, AuthType: AuthTypeFederated}
state.Mutex.Lock()
state.authCookie[cookieVal] = savedUserInfo
state.Mutex.Unlock()
authCookie := http.Cookie{Name: authCookieName, Value: cookieVal, Expires: expiration, Path: "/", HttpOnly: true, Secure: true}
//use handler with original request.
http.SetCookie(w, &authCookie)
// delete peding cookie
state.Mutex.Lock()
delete(state.pendingOauth2, index)
state.Mutex.Unlock()
//and redirect to profile page
http.Redirect(w, r, profilePath, 302)
}