diff --git a/assets b/assets index 21c3082..15f39ef 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 21c3082ba8d52a8b88cd8468c94e29edbbb1f017 +Subproject commit 15f39efd93342b6ba546c207239681d0a0bcf952 diff --git a/models/scripts/reset.go b/models/scripts/reset.go new file mode 100644 index 0000000..d5747db --- /dev/null +++ b/models/scripts/reset.go @@ -0,0 +1,35 @@ +package scripts + +import ( + "context" + model "github.com/cloudreve/Cloudreve/v3/models" + "github.com/cloudreve/Cloudreve/v3/pkg/util" + "github.com/fatih/color" +) + +type ResetAdminPassword int + +func init() { + register("ResetAdminPassword", ResetAdminPassword(0)) +} + +// Run 运行脚本从社区版升级至 Pro 版 +func (script ResetAdminPassword) Run(ctx context.Context) { + // 查找用户 + user, err := model.GetUserByID(1) + if err != nil { + util.Log().Panic("初始管理员用户不存在, %s", err) + } + + // 生成密码 + password := util.RandStringRunes(8) + + // 更改为新密码 + user.SetPassword(password) + if err := user.Update(map[string]interface{}{"password": user.Password}); err != nil { + util.Log().Panic("密码更改失败, %s", err) + } + + c := color.New(color.FgWhite).Add(color.BgBlack).Add(color.Bold) + util.Log().Info("初始管理员密码已更改为:" + c.Sprint(password)) +} diff --git a/models/scripts/reset_test.go b/models/scripts/reset_test.go new file mode 100644 index 0000000..ffacb28 --- /dev/null +++ b/models/scripts/reset_test.go @@ -0,0 +1,50 @@ +package scripts + +import ( + "context" + "errors" + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestResetAdminPassword_Run(t *testing.T) { + asserts := assert.New(t) + script := ResetAdminPassword(0) + + // 初始用户不存在 + { + mock.ExpectQuery("SELECT(.+)users(.+)"). + WillReturnRows(sqlmock.NewRows([]string{"id", "email", "storage"})) + asserts.Panics(func() { + script.Run(context.Background()) + }) + asserts.NoError(mock.ExpectationsWereMet()) + } + + // 密码更新失败 + { + mock.ExpectQuery("SELECT(.+)users(.+)"). + WillReturnRows(sqlmock.NewRows([]string{"id", "email", "storage"}).AddRow(1, "a@a.com", 10)) + mock.ExpectBegin() + mock.ExpectExec("UPDATE(.+)").WillReturnError(errors.New("error")) + mock.ExpectRollback() + asserts.Panics(func() { + script.Run(context.Background()) + }) + asserts.NoError(mock.ExpectationsWereMet()) + } + + // 成功 + { + mock.ExpectQuery("SELECT(.+)users(.+)"). + WillReturnRows(sqlmock.NewRows([]string{"id", "email", "storage"}).AddRow(1, "a@a.com", 10)) + mock.ExpectBegin() + mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1)) + mock.ExpectCommit() + asserts.NotPanics(func() { + script.Run(context.Background()) + }) + asserts.NoError(mock.ExpectationsWereMet()) + } +}