Skip to content

Commit

Permalink
Add legacy TOML user+password to API auth on init with warning.
Browse files Browse the repository at this point in the history
  • Loading branch information
knadh committed Oct 13, 2024
1 parent 5024ded commit 2da920d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
12 changes: 7 additions & 5 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,11 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
lo.Fatalf("error initializing auth: %v", err)
}

// Cache all API users in-memory for token auth.
if err := cacheAPIUsers(co, a); err != nil {
lo.Fatalf("error loading API users: %v", err)
}

// If the legacy username+password is set in the TOML file, use that as an API
// access token in the auth module to preserve backwards compatibility for existing
// API integrations. The presence of these values show a red banner on the admin UI
Expand All @@ -994,12 +999,9 @@ func initAuth(db *sql.DB, ko *koanf.Koanf, co *core.Core) *auth.Auth {
Type: models.UserTypeAPI,
}
u.Role.ID = auth.SuperAdminRoleID
a.CacheAPIUsers([]models.User{u})
}
a.CacheAPIUser(u)

// Load all API users.
if err := cacheAPIUsers(co, a); err != nil {
lo.Fatalf("error loading API users: %v", err)
lo.Println(`WARNING: Remove the admin_username and admin_password fields from the TOML configuration file. If you are using APIs, create and use new credentials. Users are now managed via the Admin -> Settings -> Users dashboard.`)
}

return a
Expand Down
13 changes: 11 additions & 2 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@ func New(cfg Config, db *sql.DB, cb *Callbacks, lo *log.Logger) (*Auth, error) {
return a, nil
}

// CacheAPIUsers caches API users for authenticating requests.
// CacheAPIUsers caches API users for authenticating requests. It wipes
// the existing cache every time and is meant for syncing all API users
// in the database in one shot.
func (o *Auth) CacheAPIUsers(users []models.User) {
o.Lock()
o.apiUsers = map[string]models.User{}
Expand All @@ -149,6 +151,13 @@ func (o *Auth) CacheAPIUsers(users []models.User) {
o.Unlock()
}

// CacheAPIUser caches an API user for authenticating requests.
func (o *Auth) CacheAPIUser(u models.User) {
o.Lock()
o.apiUsers[u.Username] = u
o.Unlock()
}

// GetAPIToken validates an API user+token.
func (o *Auth) GetAPIToken(user string, token string) (models.User, bool) {
o.RLock()
Expand Down Expand Up @@ -236,7 +245,7 @@ func (o *Auth) Middleware(next echo.HandlerFunc) echo.HandlerFunc {
return next(c)
}

// It's a cookie based session.
// Is it a cookie based session?
sess, user, err := o.validateSession(c)
if err != nil {
c.Set(UserKey, echo.NewHTTPError(http.StatusForbidden, "invalid session"))
Expand Down

0 comments on commit 2da920d

Please sign in to comment.