2023-04-13 00:07:08 +02:00
|
|
|
package user
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.dotya.ml/mirre-mt/pcmt/ent"
|
|
|
|
"git.dotya.ml/mirre-mt/pcmt/ent/user"
|
2023-04-19 02:12:27 +02:00
|
|
|
"git.dotya.ml/mirre-mt/pcmt/slogging"
|
2023-04-13 00:07:08 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// CreateUser adds a user entry to the database.
|
|
|
|
func CreateUser(ctx context.Context, client *ent.Client, username, password string) (*ent.User, error) {
|
2023-04-19 23:44:49 +02:00
|
|
|
log := ctx.Value(CtxKey{}).(*slogging.Logger)
|
2023-04-19 02:12:27 +02:00
|
|
|
|
2023-04-13 00:07:08 +02:00
|
|
|
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)
|
|
|
|
}
|
2023-04-19 02:12:27 +02:00
|
|
|
|
|
|
|
log.Infof("user was created: %#v", u)
|
|
|
|
|
2023-04-13 00:07:08 +02:00
|
|
|
return u, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func QueryUser(ctx context.Context, client *ent.Client, username string) (*ent.User, error) {
|
2023-04-19 23:44:49 +02:00
|
|
|
log := ctx.Value(CtxKey{}).(*slogging.Logger)
|
2023-04-19 02:12:27 +02:00
|
|
|
|
2023-04-13 00:07:08 +02:00
|
|
|
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)
|
|
|
|
}
|
2023-04-19 02:12:27 +02:00
|
|
|
|
|
|
|
log.Infof("user returned: %#v", u)
|
|
|
|
|
2023-04-13 00:07:08 +02:00
|
|
|
return u, nil
|
|
|
|
}
|