]> code.octet-stream.net Git - broadcaster/blob - broadcaster-server/session.go
Add a menu system
[broadcaster] / broadcaster-server / session.go
1 package main
2
3 import (
4 "crypto/rand"
5 "encoding/hex"
6 "log"
7 "net/http"
8 "time"
9 )
10
11 func generateSession() string {
12 b := make([]byte, 32)
13 _, err := rand.Read(b)
14 if err != nil {
15 log.Fatal(err)
16 }
17 return hex.EncodeToString(b)
18 }
19
20 func currentUser(_ http.ResponseWriter, r *http.Request) (User, error) {
21 cookie, e := r.Cookie("broadcast_session")
22 if e != nil {
23 return User{}, e
24 }
25
26 return users.GetUserForSession(cookie.Value)
27 }
28
29 func createSessionCookie(w http.ResponseWriter, username string) {
30 sess := generateSession()
31 log.Println("Generated a random session", sess)
32 expiration := time.Now().Add(365 * 24 * time.Hour)
33 cookie := http.Cookie{Name: "broadcast_session", Value: sess, Expires: expiration, SameSite: http.SameSiteLaxMode}
34 db.InsertSession(username, sess, expiration)
35 http.SetCookie(w, &cookie)
36 }
37
38 func clearSessionCookie(w http.ResponseWriter) {
39 c := &http.Cookie{
40 Name: "broadcast_session",
41 Value: "",
42 MaxAge: -1,
43 HttpOnly: true,
44 }
45 http.SetCookie(w, c)
46 }