-
Notifications
You must be signed in to change notification settings - Fork 0
/
login_handler.go
196 lines (184 loc) · 4.58 KB
/
login_handler.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
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/imagvfx/forge"
)
type loginHandler struct {
server *forge.Server
oidc *forge.OIDC
apps *AppSessionManager
}
func (h *loginHandler) Handle(w http.ResponseWriter, r *http.Request) {
err := func() error {
session, err := getSession(r)
if err != nil {
clearSession(w)
return err
}
// state prevents hijacking of communication
//
// Note: Google Chrome (and maybe other browsers too) secretly loads this page again from background.
// Skip to create a new state in that case, as that will break this whole login process.
if session["state"] == "" {
seed := make([]byte, 1024)
rand.Read(seed)
hs := sha256.New()
hs.Write(seed)
state := fmt.Sprintf("%x", hs.Sum(nil))
session["state"] = state
}
entryURL := r.URL.String()
if r.URL.Path == "/login" {
entryURL = "/"
}
session["entry_url"] = entryURL
appKey := r.FormValue("app_session_key")
if appKey != "" {
// Need to store the authentication info so the app could retrive it with api.
session["app_session_key"] = appKey
}
setSession(w, session)
// nonce prevents replay attack
seed := make([]byte, 1024)
rand.Read(seed)
hs := sha256.New()
hs.Write(seed)
nonce := fmt.Sprintf("%x", hs.Sum(nil))
recipe := struct {
OIDC *forge.OIDC
OIDCState string
OIDCNonce string
}{
OIDC: h.oidc,
OIDCState: session["state"],
OIDCNonce: nonce,
}
err = Tmpl.ExecuteTemplate(w, "login.bml", recipe)
if err != nil {
return err
}
return nil
}()
handleError(w, err)
}
func (h *loginHandler) HandleCallback(w http.ResponseWriter, r *http.Request) {
err := func() error {
session, err := getSession(r)
if err != nil {
clearSession(w)
return err
}
if r.FormValue("state") != session["state"] {
return fmt.Errorf("send and recieved states are different")
}
// code is needed for backend communication
code := r.FormValue("code")
if code == "" {
return fmt.Errorf("no code in oauth response")
}
resp, err := http.PostForm("https://oauth2.googleapis.com/token", url.Values{
"code": {code},
"client_id": {h.oidc.ClientID},
"client_secret": {h.oidc.ClientSecret},
"redirect_uri": {h.oidc.RedirectURI},
"grant_type": {"authorization_code"},
})
if err != nil {
return err
}
oa := OIDCResponse{}
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&oa)
if err != nil {
return err
}
part := strings.Split(oa.IDToken, ".")
if len(part) != 3 {
return fmt.Errorf("oauth id token should consist of 3 parts")
}
// usually we need to verify jwt token, but will skip this time as we just got from authorization server.
payload, err := base64.RawURLEncoding.DecodeString(part[1])
if err != nil {
return err
}
op := OIDCPayload{}
dec = json.NewDecoder(bytes.NewReader(payload))
err = dec.Decode(&op)
if err != nil {
return err
}
user := op.Email
called := op.Name
ctx := forge.ContextWithUserName(r.Context(), user)
_, err = h.server.GetUser(ctx, user)
if err != nil {
var e *forge.NotFoundError
if !errors.As(err, &e) {
return err
}
u := &forge.User{
Name: user,
Called: called,
}
err := h.server.AddUser(ctx, u)
if err != nil {
return err
}
}
session["user"] = user
// clear session info that was created for the login process.
session["state"] = ""
appKey := session["app_session_key"]
session["app_session_key"] = ""
entryURL := session["entry_url"]
session["entry_url"] = ""
err = setSession(w, session)
if err != nil {
return err
}
if appKey != "" {
encoded, err := secureCookie.Encode("session", session)
if err != nil {
return err
}
sess := AppSession{
User: user,
Session: encoded,
}
h.apps.SendSession(appKey, sess)
http.Redirect(w, r, "/app-login-completed", http.StatusSeeOther)
return nil
}
http.Redirect(w, r, entryURL, http.StatusSeeOther)
return nil
}()
handleError(w, err)
}
func (h *loginHandler) HandleAppLoginCompleted(w http.ResponseWriter, r *http.Request) {
err := Tmpl.ExecuteTemplate(w, "app_login_completed.bml", nil)
handleError(w, err)
}
func (h *loginHandler) HandleLogout(w http.ResponseWriter, r *http.Request) {
err := func() error {
clearSession(w)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return nil
}()
handleError(w, err)
}
type OIDCResponse struct {
IDToken string `json:"id_token"`
}
type OIDCPayload struct {
Email string `json:"email"`
Name string `json:"name"`
}