-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_auth_middleware.go
53 lines (41 loc) · 1.4 KB
/
proxy_auth_middleware.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
package auth
import (
"net/http"
"strings"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/sparkymat/finchphone/internal/dbx"
"golang.org/x/crypto/bcrypt"
)
const defaultBcryptCost = 10
func ProxyAuthMiddleware(cfg ConfigService, db DatabaseService) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
name := c.Request().Header.Get(cfg.ProxyAuthNameHeader())
username := c.Request().Header.Get(cfg.ProxyAuthUsernameHeader())
if username == "" {
return c.String(http.StatusUnauthorized, "user header missing") //nolint:wrapcheck
}
user, err := db.FetchUserByUsername(c.Request().Context(), username)
if err == nil {
c.Set(UserKey, user)
return next(c)
}
password := strings.ReplaceAll(uuid.New().String(), "-", "")
encryptedPasswordBytes, err := bcrypt.GenerateFromPassword([]byte(password), defaultBcryptCost)
if err != nil {
return c.String(http.StatusUnauthorized, "failed to generate password") //nolint:wrapcheck
}
user, err = db.CreateUser(c.Request().Context(), dbx.CreateUserParams{
Name: name,
Username: username,
EncryptedPassword: string(encryptedPasswordBytes),
})
if err != nil {
return c.String(http.StatusUnauthorized, "failed to add new user") //nolint:wrapcheck
}
c.Set(UserKey, user)
return next(c)
}
}
}