Skip to content

Commit e5daa26

Browse files
adelowotechknowlogick
authored andcommitted
Generate random password (#5023)
* add random-password flag * run make fmt * add length cli flag rather than use a default value
1 parent d0f614a commit e5daa26

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

cmd/admin.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@
66
package cmd
77

88
import (
9+
"errors"
910
"fmt"
1011
"os"
1112
"text/tabwriter"
1213

1314
"code.gitea.io/git"
1415
"code.gitea.io/gitea/models"
1516
"code.gitea.io/gitea/modules/auth/oauth2"
17+
"code.gitea.io/gitea/modules/generate"
1618
"code.gitea.io/gitea/modules/log"
1719
"code.gitea.io/gitea/modules/setting"
1820

@@ -59,10 +61,19 @@ var (
5961
Value: "custom/conf/app.ini",
6062
Usage: "Custom configuration file path",
6163
},
64+
cli.BoolFlag{
65+
Name: "random-password",
66+
Usage: "Generate a random password for the user",
67+
},
6268
cli.BoolFlag{
6369
Name: "must-change-password",
6470
Usage: "Force the user to change his/her password after initial login",
6571
},
72+
cli.IntFlag{
73+
Name: "random-password-length",
74+
Usage: "Length of the random password to be generated",
75+
Value: 12,
76+
},
6677
},
6778
}
6879

@@ -277,10 +288,29 @@ func runChangePassword(c *cli.Context) error {
277288
}
278289

279290
func runCreateUser(c *cli.Context) error {
280-
if err := argsSet(c, "name", "password", "email"); err != nil {
291+
if err := argsSet(c, "name", "email"); err != nil {
281292
return err
282293
}
283294

295+
if c.IsSet("password") && c.IsSet("random-password") {
296+
return errors.New("cannot set both -random-password and -password flags")
297+
}
298+
299+
var password string
300+
301+
if c.IsSet("password") {
302+
password = c.String("password")
303+
} else if c.IsSet("random-password") {
304+
password, err := generate.GetRandomString(c.Int("random-password-length"))
305+
if err != nil {
306+
return err
307+
}
308+
309+
fmt.Printf("generated random password is '%s'\n", password)
310+
} else {
311+
return errors.New("must set either password or random-password flag")
312+
}
313+
284314
if c.IsSet("config") {
285315
setting.CustomConf = c.String("config")
286316
}
@@ -299,7 +329,7 @@ func runCreateUser(c *cli.Context) error {
299329
if err := models.CreateUser(&models.User{
300330
Name: c.String("name"),
301331
Email: c.String("email"),
302-
Passwd: c.String("password"),
332+
Passwd: password,
303333
IsActive: true,
304334
IsAdmin: c.Bool("admin"),
305335
MustChangePassword: changePassword,

0 commit comments

Comments
 (0)