(ctx context.Context, args *NewUserArgs)
| 297 | } |
| 298 | |
| 299 | func (c *userClient) Create(ctx context.Context, args *NewUserArgs) (*ent.User, error) { |
| 300 | // Try to check if there's user with same email. |
| 301 | if existedUser, err := c.GetByEmail(ctx, args.Email); err == nil { |
| 302 | if existedUser.Status == user.StatusInactive { |
| 303 | return existedUser, ErrInactiveUserExisted |
| 304 | } |
| 305 | return existedUser, ErrUserEmailExisted |
| 306 | } |
| 307 | |
| 308 | nick := args.Nick |
| 309 | if nick == "" { |
| 310 | nick = strings.Split(args.Email, "@")[0] |
| 311 | } |
| 312 | |
| 313 | userSetting := &types.UserSetting{VersionRetention: true, VersionRetentionMax: 10} |
| 314 | query := c.client.User.Create(). |
| 315 | SetEmail(args.Email). |
| 316 | SetNick(nick). |
| 317 | SetStatus(args.Status). |
| 318 | SetGroupID(args.GroupID). |
| 319 | SetAvatar(args.Avatar) |
| 320 | |
| 321 | if args.PlainPassword != "" { |
| 322 | pwdDigest, err := digestPassword(args.PlainPassword) |
| 323 | if err != nil { |
| 324 | return nil, fmt.Errorf("failed to sha256 password: %w", err) |
| 325 | } |
| 326 | query.SetPassword(pwdDigest) |
| 327 | } |
| 328 | |
| 329 | if args.Language != "" { |
| 330 | userSetting.Language = args.Language |
| 331 | } |
| 332 | query.SetSettings(userSetting) |
| 333 | |
| 334 | // Create user |
| 335 | newUser, err := query. |
| 336 | Save(ctx) |
| 337 | if err != nil { |
| 338 | return nil, fmt.Errorf("failed to create user: %w", err) |
| 339 | } |
| 340 | |
| 341 | if newUser.ID == 1 { |
| 342 | // For the first user registered, elevate it to admin group. |
| 343 | if _, err := newUser.Update().SetGroupID(1).Save(ctx); err != nil { |
| 344 | return newUser, fmt.Errorf("failed to elevate user to admin: %w", err) |
| 345 | } |
| 346 | } |
| 347 | return newUser, nil |
| 348 | } |
| 349 | |
| 350 | func (c *userClient) GetByEmail(ctx context.Context, email string) (*ent.User, error) { |
| 351 | return withUserEagerLoading(ctx, c.client.User.Query().Where(user.EmailEqualFold(email))).First(ctx) |
nothing calls this directly
no test coverage detected