-
Notifications
You must be signed in to change notification settings - Fork 8
/
auth.go
67 lines (57 loc) · 1.67 KB
/
auth.go
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
66
67
// Copyright 2021 The VPN House Authors. All rights reserved.
// Use of this source code is governed by a AGPL-style
// license that can be found in the LICENSE file.
package httpapi
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
tunnelAPI "github.com/vpnhouse/api/go/server/tunnel_admin"
"github.com/vpnhouse/tunnel/pkg/xerror"
"github.com/vpnhouse/tunnel/pkg/xhttp"
"go.uber.org/zap"
)
// AdminDoAuth implements handler for GET /api/tunnel/admin/auth
func (tun *TunnelAPI) AdminDoAuth(w http.ResponseWriter, r *http.Request) {
xhttp.JSONResponse(w, func() (interface{}, error) {
authOK := false
// Check if basic authentication is successful
if _, password, ok := r.BasicAuth(); ok {
zap.L().Debug("found basic authentication")
if err := tun.runtime.Settings.VerifyAdminPassword(password); err != nil {
return nil, err
}
authOK = true
}
if !authOK {
// Check if bearer authentication is successful
tokenStr, haveBearer := xhttp.ExtractTokenFromRequest(r)
if haveBearer {
zap.L().Debug("found bearer authentication")
err := tun.adminCheckBearerAuth(tokenStr)
if err != nil {
return nil, err
}
authOK = true
}
}
if !authOK {
return nil, xerror.EUnauthorized("basic or bearer authentication expected", nil)
}
// Create claims
issued := time.Now().Unix()
expires := issued + int64(tun.runtime.Settings.AdminAPI.TokenLifetime)
claims := jwt.StandardClaims{
IssuedAt: issued,
ExpiresAt: expires,
}
signedToken, err := tun.adminJWT.Token(&claims)
if err != nil {
return nil, err
}
response := &tunnelAPI.AdminAuthResponse{
AccessToken: *signedToken,
}
return response, nil
})
}