This repository has been archived by the owner on Oct 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
oauth_intra.go
192 lines (168 loc) · 4.93 KB
/
oauth_intra.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
package weblogin
import (
"crypto/rand"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"github.com/riking/marvin/intra"
"github.com/riking/marvin/util"
)
func (mod *WebLoginModule) StartIntraURL(returnURL string, extraScopes ...string) string {
form := url.Values{}
if returnURL != "" {
form.Set("redirect_url", returnURL)
}
if len(extraScopes) > 0 {
form.Set("scope", strings.Join(extraScopes, " "))
}
uri, err := url.Parse(mod.team.AbsoluteURL("/oauth/intra/start"))
if err != nil {
panic(err)
}
uri.RawQuery = form.Encode()
return uri.String()
}
func (mod *WebLoginModule) OAuthIntraStart(w http.ResponseWriter, r *http.Request) {
loginSession, err := mod.getSession(w, r, cookieLoginTmp)
if err != nil {
return
}
err = r.ParseForm()
if err != nil {
http.Error(w, "bad form encoding", http.StatusBadRequest)
return
}
var bytes [16]byte
rand.Read(bytes[:])
nonce := base64.URLEncoding.EncodeToString(bytes[:])
loginSession.Values[cookieKeyNonce] = nonce
if after := r.Form.Get("redirect_url"); after != "" {
loginSession.Values[cookieKeyRedirect] = after
}
var scopes []string
if len(r.Form.Get("scope")) > 0 {
scopes = strings.Split(r.Form.Get("scope"), " ")
}
scopes = append(scopes, "public")
scope := strings.Join(scopes, " ")
targetURL := mod.IntraOAuthConfig.AuthCodeURL(nonce,
oauth2.SetAuthURLParam("scope", scope),
)
err = loginSession.Save(r, w)
if err != nil {
util.LogError(errors.Wrap(err, "could not create oauth cookie"))
http.Error(w, fmt.Sprintf("Internal error: %s", err), http.StatusInternalServerError)
return
}
http.Redirect(w, r, targetURL, http.StatusSeeOther)
}
func (mod *WebLoginModule) OAuthIntraCallback(w http.ResponseWriter, r *http.Request) {
loginSession, err := mod.getSession(w, r, cookieLoginTmp)
if err != nil {
return
}
doneRedirectURL, _ := loginSession.Values[cookieKeyRedirect].(string)
// Burn nonce (this deletes record from database)
loginSession.Options.MaxAge = -1
err = loginSession.Save(r, w)
if err != nil {
util.LogError(errors.Wrap(err, "oauth: clearing session"))
http.Error(w, "Internal error", http.StatusInternalServerError)
w.Write([]byte(`<br><a href="/oauth/slack/start">Start Over</a>`))
return
}
if loginSession.IsNew {
http.Error(w, "nonce expired", http.StatusBadRequest)
w.Write([]byte(`<br><a href="/oauth/slack/start">Start Over</a>`))
return
}
err = r.ParseForm()
if err != nil {
http.Error(w, "bad form encoding", http.StatusBadRequest)
return
}
intraErr := r.Form.Get("error")
if intraErr != "" {
mod.HTTPError(w, r, errors.Errorf("Intra OAuth failed: %s", intraErr))
return
}
nonceExpect, anyStored := loginSession.Values[cookieKeyNonce]
nonceGot := r.Form.Get("state")
if nonceExpect != nonceGot || !anyStored {
http.Error(w, "nonce mismatch", http.StatusBadRequest)
return
}
ctx := r.Context()
token, err := mod.IntraOAuthConfig.Exchange(ctx, r.Form.Get("code"))
if err != nil {
util.LogError(err)
http.Error(w, fmt.Sprintf("could not contact Intra: %s", err), http.StatusInternalServerError)
return
}
cl := intra.Client(ctx, oauth2.ReuseTokenSource(token, nil))
var response struct {
Login string `json:"login"`
Campus []struct {
ID int `json:"id"`
} `json:"campus"`
}
const fremontCampusID = 7
httpResp, err := cl.DoGetFormJSON(ctx, "/v2/me", nil, &response)
fmt.Println(httpResp.Status, httpResp.Header)
if err != nil {
err = errors.Wrap(err, "contacting intra")
util.LogError(err)
http.Error(w, fmt.Sprintf("could not contact Intra: %s", err), http.StatusInternalServerError)
return
}
fmt.Println("Intra sign in:", response)
ok := false
for _, v := range response.Campus {
if v.ID == fremontCampusID {
ok = true
}
}
if !ok {
mod.HTTPError(w, r, errors.Errorf("Sorry, Marvin is only available to the Fremont campus."))
return
}
var user *User
user, err = mod.GetUserByIntra(response.Login)
if err != nil && err != ErrNoSuchUser {
util.LogError(err)
http.Error(w, fmt.Sprintf("database error: %s", err), http.StatusBadRequest)
return
}
if user == nil {
user, err = mod.GetOrNewCurrentUser(w, r)
if err != nil {
util.LogError(err)
http.Error(w, fmt.Sprintf("error getting current user: %s", err), http.StatusBadRequest)
return
}
}
err = user.UpdateIntra(response.Login, token, []string{"public"}) // TODO scopes
if err != nil {
err = errors.Wrap(err, "error saving login data")
util.LogError(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = user.Login(w, r)
if err != nil {
err = errors.Wrap(err, "error saving login cookie")
util.LogError(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if doneRedirectURL != "" {
http.Redirect(w, r, doneRedirectURL, http.StatusFound)
return
}
http.Redirect(w, r, mod.team.AbsoluteURL("/"), http.StatusFound)
w.Write([]byte(`You are now logged in, redirecting to the homepage...`))
}