]> code.octet-stream.net Git - broadcaster/blob - server/session.go
Allow web user to cancel transmission in progress
[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(w http.ResponseWriter, r *http.Request) (User, error) {
21 // todo: check if user actually exists and is allowed to log in
22 cookie, e := r.Cookie("broadcast_session")
23 if e != nil {
24 return User{}, e
25 }
26
27 username, e := db.GetUserForSession(cookie.Value)
28 if e != nil {
29 return User{}, e
30 }
31 return User{username: username}, nil
32 }
33
34 func createSessionCookie(w http.ResponseWriter) {
35 sess := generateSession()
36 log.Println("Generated a random session", sess)
37 expiration := time.Now().Add(365 * 24 * time.Hour)
38 cookie := http.Cookie{Name: "broadcast_session", Value: sess, Expires: expiration, SameSite: http.SameSiteLaxMode}
39 db.InsertSession("admin", sess, expiration)
40 http.SetCookie(w, &cookie)
41 }
42
43 func clearSessionCookie(w http.ResponseWriter) {
44 c := &http.Cookie{
45 Name: "broadcast_session",
46 Value: "",
47 MaxAge: -1,
48 HttpOnly: true,
49 }
50 http.SetCookie(w, c)
51 }