-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
77 lines (68 loc) · 2.39 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
77
package main
import (
"fmt"
"log"
"net/http"
"strings"
"github.com/jaehue/simple-chat/Godeps/_workspace/src/github.com/stretchr/gomniauth"
"github.com/jaehue/simple-chat/Godeps/_workspace/src/github.com/stretchr/gomniauth/providers/facebook"
"github.com/jaehue/simple-chat/Godeps/_workspace/src/github.com/stretchr/gomniauth/providers/github"
"github.com/jaehue/simple-chat/Godeps/_workspace/src/github.com/stretchr/gomniauth/providers/google"
"github.com/jaehue/simple-chat/Godeps/_workspace/src/github.com/stretchr/objx"
)
func init() {
// set up gomniauth
gomniauth.SetSecurityKey("some long key")
gomniauth.WithProviders(
facebook.New("key", "secret",
"http://localhost:8080/auth/callback/facebook"),
github.New("key", "secret",
"http://localhost:8080/auth/callback/github"),
google.New("636296155193-3u8lt2kmcr42mt49qmcvoq726dv9q9kj.apps.googleusercontent.com", "pq9s2KpbPyt6g-0kDM_ef-7F",
"http://simplechat.jang.io/auth/callback/google"),
)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
segs := strings.Split(r.URL.Path, "/")
action := segs[2]
provider := segs[3]
switch action {
case "login":
provider, err := gomniauth.Provider(provider)
if err != nil {
log.Fatalln("Error when trying to get provider", provider, "-", err)
}
loginUrl, err := provider.GetBeginAuthURL(nil, nil)
if err != nil {
log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
}
w.Header().Set("Location", loginUrl)
w.WriteHeader(http.StatusTemporaryRedirect)
case "callback":
provider, err := gomniauth.Provider(provider)
if err != nil {
log.Fatalln("Error when trying to get provider", provider, "-", err)
}
creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
if err != nil {
log.Fatalln("Error when trying to complete auth for", provider, "-", err)
}
user, err := provider.GetUser(creds)
if err != nil {
log.Fatalln("Error when trying to get user from", provider, "-", err)
}
authCookieValue := objx.New(map[string]interface{}{
"name": user.Name(),
"avatar_url": user.AvatarURL(),
}).MustBase64()
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: authCookieValue,
Path: "/"})
w.Header()["Location"] = []string{"/chat"}
w.WriteHeader(http.StatusTemporaryRedirect)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Auth action %s not supported", action)
}
}