zitadel/internal/user/repository/view/user_view.go
Livio Spring fb162a7d75
fix(login): improve auth handlers (#7969)
# Which Problems Are Solved

During the implementation of #7486 it was noticed, that projections in
the `auth` database schema could be blocked.
Investigations suggested, that this is due to the use of
[GORM](https://gorm.io/index.html) and it's inability to use an existing
(sql) transaction.
With the improved / simplified handling (see below) there should also be
a minimal improvement in performance, resp. reduced database update
statements.

# How the Problems Are Solved

The handlers in `auth` are exchanged to proper (sql) statements and gorm
usage is removed for any writing part.
To further improve / simplify the handling of the users, a new
`auth.users3` table is created, where only attributes are handled, which
are not yet available from the `projections.users`,
`projections.login_name` and `projections.user_auth_methods` do not
provide. This reduces the events handled in that specific handler by a
lot.

# Additional Changes

None

# Additional Context

relates to #7486
2024-05-22 15:26:02 +00:00

43 lines
1.0 KiB
Go

package view
import (
"context"
"database/sql"
_ "embed"
"errors"
"github.com/jinzhu/gorm"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/user/repository/view/model"
"github.com/zitadel/zitadel/internal/zerrors"
)
//go:embed user_by_id.sql
var userByIDQuery string
func UserByID(db *gorm.DB, table, userID, instanceID string) (*model.UserView, error) {
user := new(model.UserView)
query := db.Raw(userByIDQuery, instanceID, userID)
tx := query.BeginTx(context.Background(), &sql.TxOptions{ReadOnly: true})
defer func() {
if err := tx.Commit().Error; err != nil {
logging.OnError(err).Info("commit failed")
}
tx.RollbackUnlessCommitted()
}()
err := tx.Scan(user).Error
if err == nil {
user.SetEmptyUserType()
return user, nil
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, zerrors.ThrowNotFound(err, "VIEW-hodc6", "object not found")
}
logging.WithFields("table ", table).WithError(err).Warn("get from cache error")
return nil, zerrors.ThrowInternal(err, "VIEW-qJBg9", "cache error")
}