pcmt/modules/user/user.go

48 lines
1.0 KiB
Go
Raw Normal View History

package user
import (
"context"
"fmt"
"git.dotya.ml/mirre-mt/pcmt/ent"
"git.dotya.ml/mirre-mt/pcmt/ent/user"
"git.dotya.ml/mirre-mt/pcmt/slogging"
)
// CreateUser adds a user entry to the database.
func CreateUser(ctx context.Context, client *ent.Client, username, password string) (*ent.User, error) {
log := ctx.Value(CtxKey{}).(*slogging.Logger)
u, err := client.User.
Create().
SetUsername(username).
SetPassword(password).
Save(ctx)
// TODO: saving cleartext password, rework!
if err != nil {
return nil, fmt.Errorf("failed creating user: %w", err)
}
log.Infof("user was created: %#v", u)
return u, nil
}
func QueryUser(ctx context.Context, client *ent.Client, username string) (*ent.User, error) {
log := ctx.Value(CtxKey{}).(*slogging.Logger)
u, err := client.User.
Query().
Where(user.Username(username)).
// `Only` fails if no user found,
// or more than 1 user returned.
Only(ctx)
if err != nil {
return nil, fmt.Errorf("failed querying user: %w", err)
}
log.Infof("user returned: %#v", u)
return u, nil
}