code.gitea.io/gitea@v1.21.7/models/user/must_change_password.go (about)

     1  // Copyright 2023 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package user
     5  
     6  import (
     7  	"context"
     8  	"strings"
     9  
    10  	"code.gitea.io/gitea/models/db"
    11  	"code.gitea.io/gitea/modules/util"
    12  
    13  	"xorm.io/builder"
    14  )
    15  
    16  func SetMustChangePassword(ctx context.Context, all, mustChangePassword bool, include, exclude []string) (int64, error) {
    17  	sliceTrimSpaceDropEmpty := func(input []string) []string {
    18  		output := make([]string, 0, len(input))
    19  		for _, in := range input {
    20  			in = strings.ToLower(strings.TrimSpace(in))
    21  			if in == "" {
    22  				continue
    23  			}
    24  			output = append(output, in)
    25  		}
    26  		return output
    27  	}
    28  
    29  	var cond builder.Cond
    30  
    31  	// Only include the users where something changes to get an accurate count
    32  	cond = builder.Neq{"must_change_password": mustChangePassword}
    33  
    34  	if !all {
    35  		include = sliceTrimSpaceDropEmpty(include)
    36  		if len(include) == 0 {
    37  			return 0, util.NewSilentWrapErrorf(util.ErrInvalidArgument, "no users to include provided")
    38  		}
    39  
    40  		cond = cond.And(builder.In("lower_name", include))
    41  	}
    42  
    43  	exclude = sliceTrimSpaceDropEmpty(exclude)
    44  	if len(exclude) > 0 {
    45  		cond = cond.And(builder.NotIn("lower_name", exclude))
    46  	}
    47  
    48  	return db.GetEngine(ctx).Where(cond).MustCols("must_change_password").Update(&User{MustChangePassword: mustChangePassword})
    49  }