Debian Codegraph @

_examples/chat_oauth2/main.go

raw
1 package main
2
3 import (
4 "bytes"
5 "compress/gzip"
6 "context"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io/ioutil"
11 "log"
12 "net/http"
13 "net/url"
14 "os"
15 "strings"
16 "time"
17
18 _ "net/http/pprof"
19
20 "github.com/centrifugal/centrifuge"
21 "github.com/dchest/uniuri"
22 "github.com/gorilla/mux"
23 "github.com/gorilla/sessions"
24 "golang.org/x/oauth2"
25 "golang.org/x/oauth2/google"
26 )
27
28 // SessionName is the key used to access the session store.
29 const SessionName = "_session"
30
31 // Store can/should be set by applications. The default is a cookie store.
32 var Store sessions.Store
33
34 func init() {
35 if os.Getenv("SESSION_SECRET") == "" {
36 log.Fatal("SESSION_SECRET environment variable required")
37 }
38 if os.Getenv("GOOGLE_CLIENT_ID") == "" {
39 log.Fatal("GOOGLE_CLIENT_ID environment variable required")
40 }
41 if os.Getenv("GOOGLE_CLIENT_SECRET") == "" {
42 log.Fatal("GOOGLE_CLIENT_SECRET environment variable required")
43 }
44 key := []byte(os.Getenv("SESSION_SECRET"))
45 cookieStore := sessions.NewCookieStore(key)
46 cookieStore.Options.HttpOnly = true
47 cookieStore.Options.MaxAge = 3600
48 Store = cookieStore
49 }
50
51 var googleOauthConfig = &oauth2.Config{
52 RedirectURL: "http://localhost:3000/callback",
53 ClientID: os.Getenv("GOOGLE_CLIENT_ID"),
54 ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
55 Scopes: []string{
56 "https://www.googleapis.com/auth/userinfo.profile",
57 "https://www.googleapis.com/auth/userinfo.email"},
58 Endpoint: google.Endpoint,
59 }
60
61 // GoogleUser ...
62 type GoogleUser struct {
63 ID string `json:"id"`
64 Email string `json:"email"`
65 VerifiedEmail bool `json:"verified_email"`
66 Name string `json:"name"`
67 GivenName string `json:"given_name"`
68 FamilyName string `json:"family_name"`
69 Link string `json:"link"`
70 Picture string `json:"picture"`
71 Gender string `json:"gender"`
72 Locale string `json:"locale"`
73 }
74
75 func authMiddleware(h http.Handler) http.Handler {
76 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
77 value, _ := GetFromSession("user", r)
78 if value == "" {
79 http.Redirect(w, r, "/account", http.StatusTemporaryRedirect)
80 return
81 }
82 var user *GoogleUser
83 err := json.Unmarshal([]byte(value), &user)
84 if err != nil {
85 log.Printf("Error unmarshaling Google user %s\n", err.Error())
86 _ = Logout(w, r)
87 http.Redirect(w, r, "/account", http.StatusTemporaryRedirect)
88 return
89 }
90 ctx := r.Context()
91 ctx = centrifuge.SetCredentials(ctx, &centrifuge.Credentials{
92 UserID: user.Email,
93 })
94 r = r.WithContext(ctx)
95 h.ServeHTTP(w, r)
96 })
97 }
98
99 func createCentrifugeNode() (*centrifuge.Node, error) {
100 node, err := centrifuge.New(centrifuge.DefaultConfig)
101 if err != nil {
102 return nil, err
103 }
104
105 node.OnConnect(func(client *centrifuge.Client) {
106 log.Printf("client %s connected via %s", client.UserID(), client.Transport().Name())
107
108 client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
109 log.Printf("client %s subscribes on channel %s", client.UserID(), e.Channel)
110 cb(centrifuge.SubscribeReply{}, nil)
111 })
112
113 client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) {
114 log.Printf("client %s publishes into channel %s: %s", client.UserID(), e.Channel, string(e.Data))
115 cb(centrifuge.PublishReply{}, nil)
116 })
117
118 client.OnDisconnect(func(e centrifuge.DisconnectEvent) {
119 log.Printf("client %s disconnected", client.UserID())
120 })
121 })
122
123 if err := node.Run(); err != nil {
124 return nil, err
125 }
126
127 return node, nil
128 }
129
130 func main() {
131 node, err := createCentrifugeNode()
132 if err != nil {
133 log.Fatal(err)
134 }
135
136 router := mux.NewRouter().StrictSlash(true)
137
138 // Chat handlers.
139 router.Handle("/", authMiddleware(http.FileServer(http.Dir("./"))))
140 router.Handle("/connection/websocket", authMiddleware(centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{})))
141
142 // Auth handlers.
143 router.HandleFunc("/account", accountHandler)
144 router.HandleFunc("/login", loginHandler)
145 router.HandleFunc("/logout", logoutHandler)
146 router.HandleFunc("/callback", callbackHandler)
147
148 if err := http.ListenAndServe(":3000", router); err != nil {
149 log.Fatalln(err)
150 }
151 }
152
153 func accountHandler(w http.ResponseWriter, r *http.Request) {
154 value, _ := GetFromSession("user", r)
155 if value != "" {
156 _, _ = fmt.Fprintln(w, "<a href='/logout'>Logout</a>")
157 return
158 }
159 _, _ = fmt.Fprintln(w, "<a href='/login'>Log in with Google</a>")
160 }
161
162 func loginHandler(w http.ResponseWriter, r *http.Request) {
163 oauthStateString := uniuri.New()
164 rawURL := googleOauthConfig.AuthCodeURL(oauthStateString)
165 parsedURL, err := url.Parse(rawURL)
166 if err != nil {
167 log.Printf("error parsing url: %v", err)
168 w.WriteHeader(http.StatusInternalServerError)
169 return
170 }
171 state := parsedURL.Query().Get("state")
172 err = StoreInSession("state", state, r, w)
173 if err != nil {
174 log.Printf("error storing in session %s\n", err.Error())
175 w.WriteHeader(http.StatusInternalServerError)
176 return
177 }
178 http.Redirect(w, r, rawURL, http.StatusTemporaryRedirect)
179 }
180
181 func logoutHandler(w http.ResponseWriter, r *http.Request) {
182 _ = Logout(w, r)
183 http.Redirect(w, r, "/account", http.StatusTemporaryRedirect)
184 }
185
186 func callbackHandler(w http.ResponseWriter, r *http.Request) {
187
188 state := r.FormValue("state")
189 if state == "" {
190 _, _ = fmt.Fprintf(w, "Empty state received")
191 return
192 }
193
194 savedState, _ := GetFromSession("state", r)
195 if savedState == "" {
196 _, _ = fmt.Fprintf(w, "No state in session")
197 return
198 }
199
200 if state != savedState {
201 _, _ = fmt.Fprintf(w, "Invalid state")
202 return
203 }
204
205 code := r.FormValue("code")
206 token, err := googleOauthConfig.Exchange(context.Background(), code)
207 if err != nil {
208 _, _ = fmt.Fprintf(w, "Code exchange failed with error %s\n", err.Error())
209 return
210 }
211
212 if !token.Valid() {
213 _, _ = fmt.Fprintln(w, "Retrieved invalid token")
214 return
215 }
216
217 client := &http.Client{
218 Timeout: 5 * time.Second,
219 }
220 response, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
221 if err != nil {
222 log.Printf("Error getting user from token %s\n", err.Error())
223 return
224 }
225 defer func() { _ = response.Body.Close() }()
226
227 contents, err := ioutil.ReadAll(response.Body)
228
229 var user *GoogleUser
230 err = json.Unmarshal(contents, &user)
231 if err != nil {
232 log.Printf("Error unmarshaling Google user %s\n", err.Error())
233 return
234 }
235
236 err = StoreInSession("user", string(contents), r, w)
237 if err != nil {
238 log.Printf("Error storing in session %s\n", err.Error())
239 return
240 }
241
242 http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
243 }
244
245 // StoreInSession stores a specified key/value pair in the session.
246 func StoreInSession(key string, value string, req *http.Request, res http.ResponseWriter) error {
247 session, _ := Store.New(req, SessionName)
248 if err := updateSessionValue(session, key, value); err != nil {
249 return err
250 }
251 return session.Save(req, res)
252 }
253
254 // GetFromSession retrieves a previously-stored value from the session.
255 // If no value has previously been stored at the specified key, it will return an error.
256 func GetFromSession(key string, req *http.Request) (string, error) {
257 session, _ := Store.Get(req, SessionName)
258 value, err := getSessionValue(session, key)
259 if err != nil {
260 return "", errors.New("could not find a matching session for this request")
261 }
262 return value, nil
263 }
264
265 func getSessionValue(session *sessions.Session, key string) (string, error) {
266 value := session.Values[key]
267 if value == nil {
268 return "", fmt.Errorf("could not find a matching session for this request")
269 }
270
271 rdata := strings.NewReader(value.(string))
272 r, err := gzip.NewReader(rdata)
273 if err != nil {
274 return "", err
275 }
276 s, err := ioutil.ReadAll(r)
277 if err != nil {
278 return "", err
279 }
280
281 return string(s), nil
282 }
283
284 func updateSessionValue(session *sessions.Session, key, value string) error {
285 var b bytes.Buffer
286 gz := gzip.NewWriter(&b)
287 if _, err := gz.Write([]byte(value)); err != nil {
288 return err
289 }
290 if err := gz.Flush(); err != nil {
291 return err
292 }
293 if err := gz.Close(); err != nil {
294 return err
295 }
296
297 session.Values[key] = b.String()
298 return nil
299 }
300
301 // Logout invalidates a user session.
302 func Logout(res http.ResponseWriter, req *http.Request) error {
303 session, err := Store.Get(req, SessionName)
304 if err != nil {
305 return err
306 }
307 session.Options.MaxAge = -1
308 session.Values = make(map[interface{}]interface{})
309 err = session.Save(req, res)
310 if err != nil {
311 return errors.New("could not delete user session")
312 }
313 return nil
314 }