summaryrefslogtreecommitdiff
path: root/userpath.go
blob: 9c9793fbcff4a5cd3b0b302254c1ba7b547ba9a0 (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
package main

import (
	"context"
	"os/user"
	"path"
	"path/filepath"
	"strings"

	sr "tildegit.org/tjp/sliderule"
)

func usernameFromRouter(ctx context.Context) (string, bool) {
	username, ok := sr.RouteParams(ctx)["username"]
	return username, ok
}

func userFsRoute(ctx context.Context, route RouteDirective) (RouteDirective, bool) {
	username, ok := usernameFromRouter(ctx)
	if !ok {
		return route, false
	}

	u, err := user.Lookup(username)
	if err != nil {
		return route, false
	}

	route.URLPath = strings.ReplaceAll(route.URLPath, "~", "~"+u.Username)
	if strings.HasPrefix(route.FsPath, "~/") {
		route.FsPath = filepath.Join(u.HomeDir, route.FsPath[2:])
	} else {
		route.FsPath = strings.ReplaceAll(route.FsPath, "/~/", "/"+u.Username+"/")
	}
	return route, true
}

func buildAndAddRoute(router *sr.Router, route RouteDirective, handlerf func(RouteDirective) sr.Handler) {
	var (
		urlpath string
		handler sr.Handler
	)

	if strings.IndexByte(route.FsPath, '~') < 0 {
		urlpath = route.URLPath
		handler = handlerf(route)
	} else {
		urlpath = strings.Replace(route.URLPath, "~", "~:username", 1)
		handler = sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
			route, ok := userFsRoute(ctx, route)
			if !ok {
				return nil
			}

			return handlerf(route).Handle(ctx, request)
		})
	}

	router.Route(urlpath, handler)
	router.Route(path.Join(urlpath, "*"), handler)
}