aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/middleware/auth.go
blob: b53980a7404a9b2b114c0115f92ff6fd46d9857e (plain)
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
package middleware

import (
	"database/sql"
	"log"
	"net/http"
	"time"
)

type AuthMiddleware struct {
	Err *log.Logger
	Db *sql.DB
}

func (auth *AuthMiddleware) Resolve(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(
		func (w http.ResponseWriter, r *http.Request) {
			cookie, err := r.Cookie("paterissa_session_token")
			if err != nil {
				w.WriteHeader(401)
				w.Write([]byte("Unauthorized"))
				return
			}

			stmt, err := auth.Db.Prepare("SELECT * FROM cookies WHERE content = $1;")
			if err != nil {
				cookie = &http.Cookie{
					Name: "paterissa_session_token",
					Value: "",
					Path: "/",
					MaxAge: -1,
					HttpOnly: true,
				}
				http.SetCookie(w, cookie)

				w.Write([]byte("Unauthorized"))
				auth.Err.Printf("Could not retrieve cookie from DB: %v\n", err)
				return
			}
			defer stmt.Close()

			var id int
			var content string
			var userId int
			var expiration time.Time

			row := stmt.QueryRow(cookie.Value)
			err = row.Scan(&id, &content, &userId, &expiration)
			if err != nil {
				cookie = &http.Cookie{
					Name: "paterissa_session_token",
					Value: "",
					Path: "/",
					MaxAge: -1,
					HttpOnly: true,
				}
				http.SetCookie(w, cookie)

				w.Write([]byte("Unauthorized"))
				auth.Err.Printf("Could not retrieve cookie from DB: %v\n", err)
				return
			}

			if time.Now().After(expiration) {
				cookie = &http.Cookie{
					Name: "paterissa_session_token",
					Value: "",
					Path: "/",
					MaxAge: -1,
					HttpOnly: true,
				}
				http.SetCookie(w, cookie)

				w.Write([]byte("Expired"))
				return
			}

			next.ServeHTTP(w, r)
			return
		})
}