-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
76 lines (71 loc) · 1.86 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
package main
import (
"crypto/md5"
"fmt"
"github.com/markbates/goth/gothic"
"github.com/stretchr/objx"
"io"
"log"
"net/http"
"strings"
)
type authHandler struct {
next http.Handler
}
func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("auth")
if err == http.ErrNoCookie || cookie.Value == "" {
// not authenticated
w.Header().Set("Location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
if err != nil {
// some other error
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// success - call the next handler
h.next.ServeHTTP(w, r)
}
func MustAuth(handler http.Handler) http.Handler {
return &authHandler{next: handler}
}
// loginHandler handles the third-party login process.
// format: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
segs := strings.Split(r.URL.Path, "/")
action := segs[2]
provider := r.URL.Query().Get("provider")
switch action {
case "callback":
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
fmt.Fprintln(w, err)
return
}
fmt.Printf("user data: %v", user)
chatUser := &chatUser{User: user}
m := md5.New()
_, _ = io.WriteString(m, strings.ToLower(user.Email))
chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
avatarURL, err := avatars.GetAvatarURL(chatUser)
if err != nil {
log.Fatalln("Error when trying to GetAvatarURL", "-", err)
}
authCookieValue := objx.New(map[string]interface{}{
"userid": chatUser.uniqueID,
"name": user.Name,
"avatar_url": avatarURL,
}).MustBase64()
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: authCookieValue,
Path: "/"})
w.Header().Set("Location", "/chat")
w.WriteHeader(http.StatusTemporaryRedirect)
case "login":
log.Println("Started login for", provider)
gothic.BeginAuthHandler(w, r)
}
}