This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
token.go
101 lines (87 loc) · 2.57 KB
/
token.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
package loginserver
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"github.com/leg100/otf/internal"
"github.com/leg100/otf/internal/http/decode"
"github.com/leg100/otf/internal/user"
)
func (s *server) tokenHandler(w http.ResponseWriter, r *http.Request) {
var params struct {
ClientID string `schema:"client_id"`
Code string `schema:"code"`
CodeVerifier string `schema:"code_verifier"`
GrantType string `schema:"grant_type"`
RedirectURI string `schema:"redirect_uri"`
}
if err := decode.All(¶ms, r); err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
redirect, err := url.Parse(params.RedirectURI)
if err != nil {
http.Error(w, "invalid redirect_uri", http.StatusBadRequest)
return
}
if params.ClientID != ClientID {
http.Error(w, ErrInvalidClient, http.StatusBadRequest)
return
}
// errors from hereon in are sent to the redirect URI as per RFC6749.
re := redirectError{redirect: redirect}
if params.Code == "" {
re.error(w, r, ErrInvalidRequest, "missing code")
return
}
if params.CodeVerifier == "" {
re.error(w, r, ErrInvalidRequest, "missing code verifier")
return
}
if params.GrantType != "authorization_code" {
re.error(w, r, ErrUnsupportedGrantType, "")
return
}
decrypted, err := internal.Decrypt(params.Code, s.secret)
if err != nil {
re.error(w, r, ErrInvalidRequest, "decrypting authentication code: "+err.Error())
return
}
var code authcode
if err := json.Unmarshal(decrypted, &code); err != nil {
re.error(w, r, ErrInvalidRequest, "unmarshaling authentication code: "+err.Error())
return
}
// Perform PKCE authentication
hash := sha256.Sum256([]byte(params.CodeVerifier))
encoded := base64.RawURLEncoding.EncodeToString(hash[:])
if encoded != code.CodeChallenge {
re.error(w, r, ErrInvalidGrant, encoded)
return
}
// Create API token for user and include in response
userCtx := internal.AddSubjectToContext(r.Context(), &user.User{Username: code.Username})
_, token, err := s.users.CreateToken(userCtx, user.CreateUserTokenOptions{
Description: "terraform login",
})
if err != nil {
re.error(w, r, ErrInvalidRequest, err.Error())
return
}
marshaled, err := json.Marshal(struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}{
AccessToken: string(token),
TokenType: "bearer",
})
if err != nil {
re.error(w, r, ErrInvalidRequest, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Write(marshaled)
}