summaryrefslogtreecommitdiff
path: root/pkg/auth/middleware.go
blob: 280ceeba83101fe2014ab04ff7e1b8e3244b1cb4 (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
62
63
64
65
package auth

import (
	"0xacab.org/leap/vpnweb/pkg/auth/sip2"
	"0xacab.org/leap/vpnweb/pkg/config"
	"0xacab.org/leap/vpnweb/pkg/web"
	"github.com/auth0/go-jwt-middleware"
	"github.com/dgrijalva/jwt-go"
	"log"
	"net/http"
)

const (
	anonAuth = "anon"
	sip2Auth = "sip"
)

func bailOnBadAuthModule(module string) {
	log.Fatal("Unknown auth module: '", module, "'. Should be one of: ", anonAuth, ", ", sip2Auth, ".")
}

func checkForAuthSecret(opts *config.Opts) {
	if opts.AuthSecret == "" {
		log.Fatal("Need to provide a AuthSecret value for SIP Authentication")
	}
	if len(opts.AuthSecret) < 20 {
		log.Fatal("Please provider an AuthSecret longer than 20 chars")
	}
}

func AuthenticatorMiddleware(opts *config.Opts) http.HandlerFunc {
	switch opts.Auth {
	case anonAuth:
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			http.Error(w, "no authentication in anon mode", http.StatusBadRequest)
		})
	case sip2Auth:
		checkForAuthSecret(opts)
		return sip2.SipAuthenticator(opts)
	default:
		bailOnBadAuthModule(opts.Auth)
	}
	return nil
}

func RestrictedMiddleware(opts *config.Opts, ch web.CertHandler) http.Handler {

	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(opts.AuthSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
	})

	switch opts.Auth {
	case anonAuth:
		return http.HandlerFunc(ch.CertResponder)
	case sip2Auth:
		checkForAuthSecret(opts)
		return jwtMiddleware.Handler(http.HandlerFunc(ch.CertResponder))
	default:
		bailOnBadAuthModule(opts.Auth)
	}
	return nil
}