62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package application
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
type AuthConfig struct {
|
|
Required bool
|
|
Configured bool
|
|
SessionSecret string
|
|
}
|
|
|
|
func ParseAuthConfig(getenv func(string) string) (AuthConfig, error) {
|
|
if getenv == nil {
|
|
return AuthConfig{}, errors.New("auth config getenv is required")
|
|
}
|
|
|
|
sessionSecret := firstAuthEnv(getenv,
|
|
"ZHINIAN_AUTH_SESSION_SECRET",
|
|
"AUTH_SESSION_SECRET",
|
|
"NEXTAUTH_SECRET",
|
|
)
|
|
hasSecret := sessionSecret != ""
|
|
explicitRequired, hasExplicitRequired := authBool(getenv("ZHINIAN_AUTH_REQUIRED"))
|
|
disabled, _ := authBool(getenv("ZHINIAN_AUTH_DISABLED"))
|
|
|
|
required := getenv("NODE_ENV") == "production" || hasSecret
|
|
if hasExplicitRequired {
|
|
required = explicitRequired
|
|
}
|
|
if disabled {
|
|
required = false
|
|
}
|
|
|
|
return AuthConfig{
|
|
Required: required,
|
|
Configured: (required || hasSecret) && hasSecret,
|
|
SessionSecret: sessionSecret,
|
|
}, nil
|
|
}
|
|
|
|
func firstAuthEnv(getenv func(string) string, names ...string) string {
|
|
for _, name := range names {
|
|
if value := strings.TrimSpace(getenv(name)); value != "" {
|
|
return value
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func authBool(value string) (bool, bool) {
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "1", "true", "yes", "on":
|
|
return true, true
|
|
case "0", "false", "no", "off":
|
|
return false, true
|
|
default:
|
|
return false, false
|
|
}
|
|
}
|