util.go 1.79 KB
Newer Older
1 2 3 4 5 6 7 8 9
package main

import (
	"fmt"
	"net/http"
	"html/template"
	"time"
	"database/sql"
	"github.com/go-redis/redis"
Janne Koschinski's avatar
Janne Koschinski committed
10
	"strings"
Janne Koschinski's avatar
Janne Koschinski committed
11
	"encoding/json"
12 13 14 15 16 17
)

type UserInfo struct {
	Id    string
	Name  string
	Email string
18 19 20
	Roles []string
}

Janne Koschinski's avatar
Janne Koschinski committed
21
func (info UserInfo) HasRole(role string) bool {
22 23 24 25 26 27
	for _, r := range info.Roles {
		if r == role {
			return true
		}
	}
	return false
28 29 30 31 32 33 34 35 36 37 38
}

type PageContext struct {
	Config      *Config
	Redis       *redis.Client
	Database    *sql.DB
	Images      http.Handler
	AssetServer http.Handler
}

type AlbumImage struct {
Janne Koschinski's avatar
Janne Koschinski committed
39 40
	Id          string
	Title       string
41
	Description string
Janne Koschinski's avatar
Janne Koschinski committed
42
	Position    int
43 44 45
}

type Album struct {
Janne Koschinski's avatar
Janne Koschinski committed
46 47
	Id          string
	Title       string
48
	Description string
Janne Koschinski's avatar
Janne Koschinski committed
49 50
	CreatedAt   time.Time
	Images      []AlbumImage
51 52 53 54 55 56 57
}

func parseUser(r *http.Request) UserInfo {
	return UserInfo{
		r.Header.Get("X-Auth-Subject"),
		r.Header.Get("X-Auth-Username"),
		r.Header.Get("X-Auth-Email"),
Janne Koschinski's avatar
Janne Koschinski committed
58
		strings.Split(r.Header.Get("X-Auth-Roles"), ","),
59 60 61
	}
}

Janne Koschinski's avatar
Janne Koschinski committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75
func returnJson(w http.ResponseWriter, data interface{}) error {
	marshalled, err := json.Marshal(data)
	if err != nil {
		return err
	}

	w.Header().Add("Content-Type", "application/json")
	if _, err := w.Write(marshalled); err != nil {
		return err
	}

	return nil
}

Janne Koschinski's avatar
Janne Koschinski committed
76 77 78 79 80 81 82 83 84
func returnError(w http.ResponseWriter, code int, message string) error {
	w.WriteHeader(code)
	if _, err := w.Write([]byte(message)); err != nil {
		return err
	}

	return nil
}

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
func formatTemplate(w http.ResponseWriter, templateName string, data interface{}) error {
	pageTemplate, err := template.ParseFiles(
		"templates/_base.html",
		"templates/_header.html",
		"templates/_navigation.html",
		"templates/_footer.html",
		fmt.Sprintf("templates/%s", templateName),
	)
	if err != nil {
		return err
	}

	err = pageTemplate.Execute(w, data)
	if err != nil {
		return err
	}

	return nil
}