forked from
tangled.org/core
fork
Configure Feed
Select the types of activity you want to include in your feed.
Monorepo for Tangled
fork
Configure Feed
Select the types of activity you want to include in your feed.
1package middleware
2
3import (
4 "context"
5 "log"
6 "net/http"
7 "strconv"
8
9 "tangled.sh/tangled.sh/core/appview/oauth"
10 "tangled.sh/tangled.sh/core/appview/pagination"
11)
12
13type Middleware func(http.Handler) http.Handler
14
15func AuthMiddleware(a *oauth.OAuth) Middleware {
16 return func(next http.Handler) http.Handler {
17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18 redirectFunc := func(w http.ResponseWriter, r *http.Request) {
19 http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
20 }
21 if r.Header.Get("HX-Request") == "true" {
22 redirectFunc = func(w http.ResponseWriter, _ *http.Request) {
23 w.Header().Set("HX-Redirect", "/login")
24 w.WriteHeader(http.StatusOK)
25 }
26 }
27
28 _, auth, err := a.GetSession(r)
29 if err != nil {
30 log.Printf("not logged in, redirecting")
31 redirectFunc(w, r)
32 return
33 }
34
35 if !auth {
36 log.Printf("not logged in, redirecting")
37 redirectFunc(w, r)
38 return
39 }
40
41 next.ServeHTTP(w, r)
42 })
43 }
44}
45
46func Paginate(next http.Handler) http.Handler {
47 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
48 page := pagination.FirstPage()
49
50 offsetVal := r.URL.Query().Get("offset")
51 if offsetVal != "" {
52 offset, err := strconv.Atoi(offsetVal)
53 if err != nil {
54 log.Println("invalid offset")
55 } else {
56 page.Offset = offset
57 }
58 }
59
60 limitVal := r.URL.Query().Get("limit")
61 if limitVal != "" {
62 limit, err := strconv.Atoi(limitVal)
63 if err != nil {
64 log.Println("invalid limit")
65 } else {
66 page.Limit = limit
67 }
68 }
69
70 ctx := context.WithValue(r.Context(), "page", page)
71 next.ServeHTTP(w, r.WithContext(ctx))
72 })
73}