-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
81 lines (65 loc) · 1.77 KB
/
auth.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
package main
import (
"fmt"
"log"
"net/http"
"github.com/gofrs/uuid"
"golang.org/x/oauth2"
)
// tokenSource returns a token source that can be used to refresh the token
func (esi *ESI) tokenSource() (oauth2.TokenSource, error) {
if esi.token == nil {
var err error
esi.token, err = esi.readToken()
if err != nil {
return nil, err
}
}
ts := esi.sso.TokenSource(esi.token)
newToken, err := ts.Token()
if err != nil {
log.Println("[ERROR] error getting token")
return nil, err
}
if esi.token != newToken {
esi.token = newToken
}
return ts, nil
}
// /login
func (esi *ESI) handleEsiLogin(w http.ResponseWriter, r *http.Request) {
state, err := uuid.NewV4()
if err != nil {
http.Error(w, "[ERROR] Unable to create random state for auth", http.StatusInternalServerError)
return
}
session, _ := esi.store.Get(r, "session")
session.Values["state"] = state.String()
session.Save(r, w)
// generate SSO URL
url := esi.sso.AuthorizeURL(state.String(), true, esi.scopes)
http.Redirect(w, r, url, http.StatusFound)
}
// /callback
func (esi *ESI) handleEsiCallback(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
state := r.FormValue("state")
session, _ := esi.store.Get(r, "session")
if session.Values["state"] != state {
http.Error(w, "[ERROR] Bad auth state", http.StatusInternalServerError)
}
token, err := esi.sso.TokenExchange(code)
if err != nil {
http.Error(w, "Token Exchange Failure", http.StatusInternalServerError)
}
// token source refreshes the token in the future
tokenSource := esi.sso.TokenSource(token)
// verify
_, err = esi.sso.Verify(tokenSource)
if err != nil {
http.Error(w, "Verify Failure", http.StatusInternalServerError)
}
esi.token = token
esi.storeToken(token)
fmt.Fprintf(w, "Login Success")
}