aboutsummaryrefslogtreecommitdiffstats
path: root/api/handlers/ical.go
blob: bcbf42b0414d0136042e99d138096ece2e21d51f (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
package handlers

import (
	"crypto/subtle"
	"net/http"

	"github.com/LMBishop/confplanner/api/dto"
	"github.com/LMBishop/confplanner/pkg/calendar"
	"github.com/LMBishop/confplanner/pkg/ical"
)

func GetIcal(icalService ical.Service, calendarService calendar.Service) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		name := r.URL.Query().Get("name")
		key := r.URL.Query().Get("key")

		if name == "" || key == "" {
			dto.WriteDto(w, r, &dto.ErrorResponse{
				Code:    http.StatusBadRequest,
				Message: "Both name and key must be specified",
			})
			return
		}

		calendar, err := calendarService.GetCalendarByName(name)
		if err != nil {
			dto.WriteDto(w, r, err)
			return
		}

		if subtle.ConstantTimeCompare([]byte(key), []byte(calendar.Key)) != 1 {
			dto.WriteDto(w, r, &dto.ErrorResponse{
				Code:    http.StatusUnauthorized,
				Message: "Invalid key",
			})
			return
		}

		ical, err := icalService.GenerateIcalForCalendar(*calendar)
		if err != nil {
			dto.WriteDto(w, r, err)
			return
		}

		w.Header().Add("Content-Type", "text/calendar")
		w.Write([]byte(ical))
	}
}