-
Notifications
You must be signed in to change notification settings - Fork 19
/
auth.go
123 lines (104 loc) · 2.44 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
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
116
117
118
119
120
121
122
123
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/sessions"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/github"
"github.com/pkg/errors"
)
var sess sessions.Store
func init() {
sess = sessions.NewCookieStore(
[]byte(os.Getenv("SESSION_SECRET")),
)
gothic.Store = sess
goth.UseProviders(
github.New(
os.Getenv("GITHUB_KEY"),
os.Getenv("GITHUB_SECRET"),
os.Getenv("GITHUB_CALLBACK")+"/auth/github/callback",
"user:email",
),
)
}
func authCallback(w http.ResponseWriter, r *http.Request) {
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
fmt.Fprintln(w, err)
return
}
// Throw this away because it makes cookies too large
user.RawData = make(map[string]interface{})
s, _ := sess.Get(r, "session")
s.Values["user"] = user
s.Values["new"], err = saveUser(user)
if err != nil {
log.Println(err)
http.Error(w, "database error", http.StatusInternalServerError)
return
}
if err := s.Save(r, w); err != nil {
log.Println(err)
http.Error(w, "could not save cookie", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/profile", http.StatusTemporaryRedirect)
}
func saveUser(u goth.User) (bool, error) {
var found int
err := db.QueryRow("SELECT id FROM users WHERE id = $1", u.UserID).Scan(&found)
if err != nil && err != sql.ErrNoRows {
return false, errors.Wrap(err, "could not check for existing user")
}
if err == sql.ErrNoRows {
_, err := db.Exec(
"INSERT INTO users (id, username, name, email, avatar, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7)",
u.UserID,
u.NickName,
u.Name,
u.Email,
u.AvatarURL,
time.Now(),
time.Now(),
)
if err != nil {
return false, errors.Wrap(err, "could not insert user")
}
return true, nil
}
_, err = db.Exec(
"UPDATE users SET username = $1, name = $2, email = $3, avatar = $4, updated_at = $5 WHERE id = $6",
u.NickName,
u.Name,
u.Email,
u.AvatarURL,
time.Now(),
u.UserID,
)
if err != nil {
return false, errors.Wrap(err, "could not update user")
}
return false, nil
}
func findUser(r *http.Request) (goth.User, bool, bool) {
s, err := sess.Get(r, "session")
if err != nil {
return goth.User{}, false, false
}
val, ok := s.Values["user"]
if !ok {
return goth.User{}, false, false
}
n, ok := s.Values["new"].(bool)
if !ok {
n = false
}
u, ok := val.(goth.User)
return u, n, ok
}