summaryrefslogtreecommitdiff
path: root/pkg/auth/middleware.go
blob: 9b42fa93743494ee3bf1d716b73cf9394e6a3fd8 (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
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"
	jwt "github.com/dgrijalva/jwt-go"
	"log"
	"net/http"
)

const anonAuth string = "anon"
const sipAuth string = "sip"

/* FIXME -- get this from configuration variables */

var jwtSigningSecret = []byte("thesingingkey")

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

func Authenticator(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 sipAuth:
		return sip2.SipAuthenticator(opts)
	default:
		bailOnBadAuthModule(opts.Auth)
	}
	return nil
}

func RestrictedMiddleware(auth string, ch web.CertHandler) http.Handler {

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

	switch auth {
	case anonAuth:
		return http.HandlerFunc(ch.CertResponder)
	case sipAuth:
		return jwtMiddleware.Handler(http.HandlerFunc(ch.CertResponder))
	default:
		bailOnBadAuthModule(auth)
	}
	return nil
}