-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
115 lines (90 loc) · 2.56 KB
/
handlers.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
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/gomicro/doorman/users"
)
type token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"`
}
func handleUserInfo(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
token = strings.TrimPrefix(token, "jwt ")
log.Debugf("Token: %v", token)
u, err := users.Lookup(token)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("bad request token")) //nolint,errcheck
return
}
b, err := json.Marshal(u)
if err != nil {
msg := fmt.Sprintf("failed to marshal user: %v", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(msg)) //nolint,errcheck
return
}
w.WriteHeader(200)
w.Write(b) //nolint,errcheck
}
func handleGetGoogleAuth(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
cID := q.Get("client_id")
log.Debugf("Client ID: %v", cID)
rType := q.Get("response_type")
log.Debugf("Response Type: %v", rType)
scope := q.Get("scope")
log.Debugf("Scope: %v", scope)
encState := q.Get("state")
state, err := base64.StdEncoding.DecodeString(encState)
if err != nil {
log.Errorf("failed to decode state: %v", err.Error())
w.WriteHeader(http.StatusBadRequest)
msg := "state not base64 encoded"
w.Write([]byte(msg)) //nolint,errcheck
return
}
log.Debugf("State: %v", string(state))
redURI := q.Get("redirect_uri")
log.Debugf("Redirect URI: %v", redURI)
ru, err := url.Parse(redURI)
if err != nil {
log.Errorf("failed to parse redirect uri: %v", err.Error())
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("bad redirect uri")) //nolint,errchecK
return
}
code := "somecode"
values := url.Values{}
values.Set("code", code)
values.Set("state", encState)
ru.RawQuery = values.Encode()
http.Redirect(w, r, ru.String(), http.StatusSeeOther)
}
func handlePostGoogleAuth(w http.ResponseWriter, r *http.Request) {
u := users.Random()
t := &token{
AccessToken: u.Sub,
TokenType: "jwt",
RefreshToken: "somerefreshtoken",
ExpiresIn: time.Now().Add(15 * time.Minute).Unix(),
}
b, err := json.Marshal(t)
if err != nil {
log.Errorf("failed to marshal token: %v", err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("failed to marshal token")) //nolint,errchecK
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b) //nolint,errchecK
}