-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsecure.go
270 lines (239 loc) · 7.72 KB
/
secure.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package secure
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/crypto/acme/autocert"
)
// Horrible Hack
var ProxyPort = 0
// SecureConfig provides configuration options when initializing echo
type SecureConfig struct {
SSLCert string // filename for SSL certificate (should be .PEM file) (default auto TLS)
SSLKey string // filename for SSL key file (should be .PEM file) (default auto TLS)
ClientID string // Google client ID for oauth (required for authentication)
ClientSecret string // Google client secret for outh (required for authentication)
AuthorizeChecker Authorizer // Checks whether user is authorized (default: authorize all)
Hostname string // Hostname is the location of the server that will be used for Google oauth callback
ProxyAuth string // ProxyAuth name of proxy server (optional)
ProxyInsecure bool // If true, disable secure connection
}
// EchoSecure handles secure connection configuration
type EchoSecure struct {
e *echo.Echo // context for secure object
secret []byte // private key used for cookies and JWT
enableAuthenticate bool
enableAuthorize bool
manCert bool // if true, requires https PEM files
config SecureConfig
}
// AuthMiddleware checks authentication and authorization for the designated handlers
func (s EchoSecure) AuthMiddleware(authLevel AuthorizationLevel) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// if no authentication, no need to check
if !s.enableAuthenticate {
return next(c)
}
email := ""
imageurl := ""
// check for either Bearer token or cookie
auth := c.Request().Header.Get(echo.HeaderAuthorization)
l := len("Bearer")
if len(auth) > l+1 && auth[:l] == "Bearer" {
auth = auth[l+1:]
claimsPtr := &jwtCustomClaims{}
t := reflect.ValueOf(claimsPtr).Type().Elem()
claims := reflect.New(t).Interface().(jwt.Claims)
token, err := jwt.ParseWithClaims(auth, claims, func(t *jwt.Token) (interface{}, error) {
// Check the signing method
if t.Method.Alg() != AlgorithmHS256 {
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
}
return s.secret, nil
})
if err == nil && token.Valid {
// Store user information from token into context.
c.Set("user", token)
claims := token.Claims.(*jwtCustomClaims)
email = claims.Email
imageurl = claims.ImageURL
} else {
return &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: "invalid or expired jwt",
Internal: err,
}
}
} else {
currSession, err := session.Get(defaultSessionID, c)
type ErrorMessage struct {
Error string `json:"error"`
}
errorMessage := &ErrorMessage{
Error: "Please provide valid credentials",
}
if err != nil {
return c.JSON(http.StatusUnauthorized, errorMessage)
}
if profile, ok := currSession.Values[googleProfileSessionKey].(*Profile); !ok || profile == nil {
// call fetchProxyProfile if there is a proxy server
if ProxyAuth != "" {
profile, err := fetchProxyProfile(c)
if err != nil {
return c.JSON(http.StatusUnauthorized, errorMessage)
}
currSession.Values[googleProfileSessionKey] = stripProfile(profile)
email = profile.Email
imageurl = profile.Picture
} else {
return c.JSON(http.StatusUnauthorized, errorMessage)
}
} else {
email = profile.Email
imageurl = profile.ImageURL
}
currSession.Save(c.Request(), c.Response())
}
// set email so logger can potentially read
c.Set("email", email)
c.Set("imageurl", imageurl)
// check authorize if it exists
if s.enableAuthorize {
if isAuthorized := s.config.AuthorizeChecker.Authorize(email, authLevel); !isAuthorized {
return &echo.HTTPError{
Code: http.StatusUnauthorized,
Message: "unauthorized user",
Internal: fmt.Errorf("user not authorized"),
}
} else {
// level exists
level, _ := s.config.AuthorizeChecker.Level(email)
levelstr, _ := StringFromLevel(level)
c.Set("level", levelstr)
}
}
return next(c)
}
}
}
// InitializeEchoSecure sets up https configurations for echo. If
// a Google authentication key is provided, authentication
// API is created. Authentication routes are addded in the default
// echo context group. Note: do not add auth middleware to the default context
// since it will disable login.
func InitializeEchoSecure(e *echo.Echo, config SecureConfig, secret []byte, sessionID string) (EchoSecure, error) {
// setup logging and panic recover
manCert := false
if config.SSLCert != "" && config.SSLKey != "" {
manCert = true
}
defaultSessionID = sessionID
defaultDomain = config.Hostname
defaultProxyInsecure = config.ProxyInsecure
defaultHostName = "https://" + config.Hostname
parts := strings.Split(config.Hostname, ".")
if len(parts) >= 2 {
defaultDomain = parts[len(parts)-2] + "." + parts[len(parts)-1]
}
if !manCert {
e.AutoTLSManager.Cache = autocert.DirCache("./cache")
}
e.Pre(middleware.HTTPSRedirect())
e.Pre(middleware.HTTPSNonWWWRedirect())
enableAuthenticate := false
enableAuthorize := false
if string(secret) != "" {
enableAuthenticate = true
enableAuthorize = true
// add if enabled, auth guard some of the handlers
e.Use(session.Middleware(sessions.NewCookieStore(secret)))
}
if config.AuthorizeChecker == nil {
enableAuthorize = false
}
s := EchoSecure{e, secret, enableAuthenticate, enableAuthorize, manCert, config}
ProxyAuth = config.ProxyAuth
if enableAuthenticate {
JWTSecret = secret
// swagger:operation GET /login user loginHandler
//
// Login user
//
// Login user redirecting to profile
//
// ---
// responses:
// 302:
// description: "Redirect to /profile"
e.GET("/login", loginHandler)
e.GET("/oauth2callback", oauthCallbackHandler)
// requires login
// swagger:operation POST /logout user logoutHandler
//
// Logout user
//
// Clears session cookie for the user
//
// ---
// responses:
// 200:
// description: "successful operation"
// security:
// - Bearer: []
e.POST("/logout", s.AuthMiddleware(NOAUTH)(logoutHandler))
// swagger:operation GET /profile user profileHandler
//
// Returns user information
//
// Returns user information
//
// ---
// responses:
// 200:
// description: "successful operation"
// security:
// - Bearer: []
e.GET("/profile", s.AuthMiddleware(NOAUTH)(profileHandler))
// swagger:operation GET /token user tokenHandler
//
// Returns JWT user bearer token
//
// JWT token should be passed in header for authentication
//
// ---
// responses:
// 200:
// description: "successful operation"
// security:
// - Bearer: []
e.GET("/token", s.AuthMiddleware(NOAUTH)(tokenHandler))
}
// return object
return s, nil
}
func (s EchoSecure) StartEchoSecure(port int) {
portstr := strconv.Itoa(port)
portstr2 := portstr
if ProxyPort != 0 {
portstr2 = strconv.Itoa(ProxyPort)
}
defaultHostName = defaultHostName + ":" + portstr2
if s.enableAuthenticate {
// setup oauth object
redirectURL := "https://" + s.config.Hostname + ":" + portstr2 + "/oauth2callback"
configureOAuthClient(s.config.ClientID, s.config.ClientSecret, redirectURL)
}
if s.manCert {
s.e.Logger.Fatal(s.e.StartTLS(":"+portstr, s.config.SSLCert, s.config.SSLKey))
} else {
s.e.Logger.Fatal(s.e.StartAutoTLS(":" + portstr))
}
}