This might be what's preventing us from registering this on the Caddy page. See https://caddy.community/t/cannot-claim-package/20537
71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package caddy_tailscale
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"github.com/caddyserver/caddy/v2"
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp/caddyauth"
|
|
"net/http"
|
|
"strconv"
|
|
"tailscale.com/client/tailscale"
|
|
"time"
|
|
)
|
|
|
|
func init() {
|
|
caddy.RegisterModule(new(TailscaleAuth))
|
|
}
|
|
|
|
type TailscaleAuth struct {
|
|
lc *tailscale.LocalClient
|
|
|
|
AllowedUsers []string `json:"allowed_users"`
|
|
allowedUsersMap map[string]struct{}
|
|
}
|
|
|
|
// CaddyModule returns the Caddy module information.
|
|
func (*TailscaleAuth) CaddyModule() caddy.ModuleInfo {
|
|
return caddy.ModuleInfo{
|
|
ID: "http.authentication.providers.tailscale",
|
|
New: func() caddy.Module { return new(TailscaleAuth) },
|
|
}
|
|
}
|
|
|
|
func (ta *TailscaleAuth) Provision(caddy.Context) error {
|
|
fmt.Println("PROVISION")
|
|
ta.lc = new(tailscale.LocalClient)
|
|
|
|
ta.allowedUsersMap = make(map[string]struct{})
|
|
for _, u := range ta.AllowedUsers {
|
|
ta.allowedUsersMap[u] = struct{}{}
|
|
}
|
|
|
|
fmt.Println(ta.allowedUsersMap, ta.AllowedUsers)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (ta *TailscaleAuth) Authenticate(_ http.ResponseWriter, req *http.Request) (caddyauth.User, bool, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
|
|
defer cancel()
|
|
whois, err := ta.lc.WhoIs(ctx, req.RemoteAddr)
|
|
if err != nil {
|
|
return caddyauth.User{}, false, err
|
|
}
|
|
|
|
if _, found := ta.allowedUsersMap[whois.UserProfile.LoginName]; len(ta.allowedUsersMap) != 0 && !found {
|
|
return caddyauth.User{}, false, nil
|
|
}
|
|
|
|
return caddyauth.User{
|
|
ID: strconv.FormatInt(int64(whois.UserProfile.ID), 10),
|
|
Metadata: map[string]string{
|
|
"display_name": whois.UserProfile.DisplayName,
|
|
"login_name": whois.UserProfile.LoginName,
|
|
},
|
|
}, true, nil
|
|
}
|
|
|
|
var (
|
|
_ caddy.Module = (*TailscaleAuth)(nil)
|
|
_ caddyauth.Authenticator = (*TailscaleAuth)(nil)
|
|
)
|