-
Notifications
You must be signed in to change notification settings - Fork 21
/
handlers.go
174 lines (150 loc) · 4.64 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
"os"
"time"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
// Credentials which stores google ids.
type Credentials struct {
Installed struct {
Cid string `json:"client_id"`
Csecret string `json:"client_secret"`
} `json:"installed"`
}
// Handlers contains the handlers and config for the handlers.
type Handlers struct {
conf *oauth2.Config
db *Database
}
func NewHandler(db *Database) (*Handlers, error) {
cred := &Credentials{}
file, err := os.ReadFile("./creds.json")
if err != nil {
log.Printf("File error: %v\n", err)
return nil, err
}
if err := json.Unmarshal(file, &cred); err != nil {
log.Println("unable to marshal data")
return nil, err
}
conf := &oauth2.Config{
ClientID: cred.Installed.Cid,
ClientSecret: cred.Installed.Csecret,
RedirectURL: "http://127.0.0.1:9090/auth", // can come from Credentials file redirect URLs.
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email", // You have to select your own scope from here -> https://developers.google.com/identity/protocols/googlescopes#google_sign-in
},
Endpoint: google.Endpoint,
}
return &Handlers{
conf: conf,
db: db,
}, nil
}
// RandToken generates a random @l length token.
func RandToken(l int) (string, error) {
b := make([]byte, l)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
func (h *Handlers) getLoginURL(state string) string {
return h.conf.AuthCodeURL(state)
}
// IndexHandler handles the location /.
func (h *Handlers) IndexHandler(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{})
}
// AuthHandler handles authentication of a user and initiates a session.
func (h *Handlers) AuthHandler(c *gin.Context) {
// Handle the exchange code to initiate transport.
session := sessions.Default(c)
retrievedState := session.Get("state")
queryState := c.Request.URL.Query().Get("state")
if retrievedState != nil && retrievedState != queryState {
log.Printf("Invalid session state: retrieved: %s; Param: %s", retrievedState, queryState)
c.HTML(http.StatusUnauthorized, "error.tmpl", gin.H{"message": "Invalid session state."})
return
}
code := c.Request.URL.Query().Get("code")
ctx, done := context.WithTimeout(context.Background(), 15*time.Second)
defer done()
tok, err := h.conf.Exchange(ctx, code)
if err != nil {
log.Println(err)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Login failed. Please try again."})
return
}
client := h.conf.Client(ctx, tok)
userinfo, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
if err != nil {
log.Println(err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
defer userinfo.Body.Close()
data, err := io.ReadAll(userinfo.Body)
if err != nil {
log.Println(err)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Failed to read request body."})
return
}
u := User{}
if err = json.Unmarshal(data, &u); err != nil {
log.Println(err)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Error marshalling response. Please try again."})
return
}
session.Set("user-id", u.Email)
err = session.Save()
if err != nil {
log.Println(err)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Error while saving session. Please try again."})
return
}
if _, err := h.db.LoadUser(u.Email); err == nil {
c.HTML(http.StatusOK, "battle.tmpl", gin.H{"email": u.Email, "seen": true})
return
}
err = h.db.SaveUser(&u)
if err != nil {
log.Println(err)
c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"message": "Error while saving user. Please try again."})
return
}
c.HTML(http.StatusOK, "battle.tmpl", gin.H{"email": u.Email, "seen": false})
}
// LoginHandler handles the login procedure.
func (h *Handlers) LoginHandler(c *gin.Context) {
state, err := RandToken(32)
if err != nil {
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"message": "Error while generating random data."})
return
}
session := sessions.Default(c)
session.Set("state", state)
err = session.Save()
if err != nil {
c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"message": "Error while saving session."})
return
}
link := h.getLoginURL(state)
c.HTML(http.StatusOK, "auth.tmpl", gin.H{"link": link})
}
// FieldHandler is a rudimentary handler for logged in users.
func (h *Handlers) FieldHandler(c *gin.Context) {
session := sessions.Default(c)
userID := session.Get("user-id")
c.HTML(http.StatusOK, "field.tmpl", gin.H{"user": userID})
}