Skip to content

Commit b3e2aef

Browse files
authored
feat(dal): 重构数据迁移和初始化 (#110)
* feat(dal): refactor data migration and initialization - Drop and recreate tables instead of auto-migrate - Use FirstOrCreate to initialize default data - Extract default values to constants - Simplify and optimize the migration process * fix(user): add old password verification and update password logic - Add error handling for incorrect old password - Implement password update functionality - Remove unnecessary comment in repository initialization
1 parent daedba3 commit b3e2aef

6 files changed

Lines changed: 106 additions & 79 deletions

File tree

api/v1/errors.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ var (
1010

1111
var (
1212
ErrorUserNameAndPassword = newError(100, "用户名和密码错误")
13+
ErrorUserOldPassword = newError(100, "原密码错误")
1314
ErrorTokenGeneration = newError(101, "令牌生成错误")
1415
)

internal/dal/repository/repository.go

Lines changed: 56 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"go.uber.org/zap"
1313
"gorm.io/driver/mysql"
1414
"gorm.io/driver/postgres"
15+
"gorm.io/gen/field"
1516
"gorm.io/gorm"
1617

1718
"github.com/ch3nnn/webstack-go/internal/dal/model"
@@ -91,7 +92,18 @@ func NewDB(conf *viper.Viper, l *log.Logger) *gorm.DB {
9192
}
9293

9394
func autoMigrateAndInitialize(db *gorm.DB) {
94-
err := db.AutoMigrate(
95+
ctx := context.Background()
96+
97+
err := db.Migrator().DropTable(
98+
&model.SysUserMenu{},
99+
&model.SysMenu{},
100+
)
101+
if err != nil {
102+
fmt.Println("migrate drop table error")
103+
os.Exit(0)
104+
}
105+
106+
err = db.AutoMigrate(
95107
&model.SysConfig{},
96108
&model.SysUser{},
97109
&model.SysUserMenu{},
@@ -104,34 +116,24 @@ func autoMigrateAndInitialize(db *gorm.DB) {
104116
os.Exit(0)
105117
}
106118

107-
ctx := context.Background()
108-
109-
umCtn, err := query.SysUserMenu.WithContext(ctx).Count()
110-
if err != nil {
111-
os.Exit(0)
112-
}
113-
114-
uCtn, err := query.SysUser.WithContext(ctx).Count()
115-
if err != nil {
116-
os.Exit(0)
117-
}
118-
119-
mCtn, err := query.SysMenu.WithContext(ctx).Count()
119+
_, err = query.SysUser.WithContext(ctx).
120+
Where(
121+
query.SysUser.ID.Eq(1),
122+
query.SysUser.Username.Eq(DefaultUname),
123+
).
124+
Attrs(
125+
field.Attrs(&model.SysUser{
126+
Password: cryptor.Md5String(DefaultUPassword)},
127+
),
128+
).
129+
FirstOrCreate()
120130
if err != nil {
131+
fmt.Println("user migrate error")
121132
os.Exit(0)
122133
}
123134

124-
if umCtn == 0 && uCtn == 0 && mCtn == 0 {
125-
err := query.SysUser.WithContext(ctx).Create(&model.SysUser{
126-
ID: 1,
127-
Username: "admin",
128-
Password: cryptor.Md5String("admin"),
129-
})
130-
if err != nil {
131-
os.Exit(0)
132-
}
133-
134-
err = query.SysMenu.WithContext(ctx).Create(
135+
err = query.SysMenu.WithContext(ctx).
136+
Create(
135137
&model.SysMenu{
136138
ID: 1,
137139
Pid: 0,
@@ -177,11 +179,13 @@ func autoMigrateAndInitialize(db *gorm.DB) {
177179
IsUsed: true,
178180
},
179181
)
180-
if err != nil {
181-
os.Exit(0)
182-
}
182+
if err != nil {
183+
fmt.Println("menu migrate error")
184+
os.Exit(0)
185+
}
183186

184-
err = query.SysUserMenu.WithContext(ctx).Create(
187+
err = query.SysUserMenu.WithContext(ctx).
188+
Create(
185189
&model.SysUserMenu{
186190
UserID: 1,
187191
MenuID: 1,
@@ -203,54 +207,30 @@ func autoMigrateAndInitialize(db *gorm.DB) {
203207
MenuID: 5,
204208
},
205209
)
206-
if err != nil {
207-
os.Exit(0)
208-
}
209-
210-
err = query.SysConfig.WithContext(ctx).Create(
211-
&model.SysConfig{
212-
ID: 1,
213-
AboutSite: "> ❤️ 基于 Golang 开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己平日收藏的网址导航。\n\n\n> 如果你也是开发者,如果你也正好喜欢折腾,那希望这个网站能给你带来一些作用。",
214-
AboutAuthor: `
215-
<div class="col-sm-4">
216-
<div class="xe-widget xe-conversations box2 label-info" onclick="window.open('https://blog.ch3nnn.cn/about/', '_blank')" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="https://blog.ch3nnn.cn/about/">
217-
<div class="xe-comment-entry">
218-
<a class="xe-user-img">
219-
<img src="https://s2.loli.net/2023/02/20/H1k52mlXNYKWDrU.png" class="img-circle" width="40">
220-
</a>
221-
<div class="xe-comment">
222-
<a href="#" class="xe-user-name overflowClip_1">
223-
<strong>Developer. Ch3nnn.</strong>
224-
</a>
225-
<p class="overflowClip_2"> 折腾不息 · 乐此不疲.</p>
226-
</div>
227-
</div>
228-
</div>
229-
</div>
210+
if err != nil {
211+
fmt.Println("user menu migrate error")
212+
os.Exit(0)
213+
}
230214

231-
<div class="col-md-8">
232-
<div class="row">
233-
<div class="col-sm-12">
234-
<br>
235-
<blockquote>
236-
<p>
237-
这是一个公益项目,而且是<a href="https://github.com/ch3nnn/webstack-go"> 开源 </a>的。你也可以拿来制作自己的网址导航。如果你有更好的想法,可以通过个人网站<a href="https://ch3nnn.cn/about/">ch3nnn.cn</a>中的联系方式找到我,欢迎与我交流分享。
238-
</p>
239-
</blockquote>
240-
</div>
241-
</div>
242-
<br>
243-
</div>
244-
`,
245-
IsAbout: false,
246-
SiteTitle: "WebStack-Go - 网址导航",
247-
SiteKeyword: "网址导航",
248-
SiteDesc: "WebStack-Go - 基于 Golang 开源的网址导航网站",
249-
})
250-
if err != nil {
251-
os.Exit(0)
252-
}
215+
_, err = query.SysConfig.WithContext(ctx).
216+
Where(
217+
query.SysConfig.ID.Eq(1),
218+
).
219+
Attrs(
220+
field.Attrs(&model.SysConfig{
221+
AboutSite: DefaultAboutSite,
222+
AboutAuthor: DefaultAuthor,
223+
SiteTitle: DefaultSiteTitle,
224+
SiteKeyword: DefaultSiteKeyword,
225+
SiteDesc: DefaultSiteDesc,
226+
}),
227+
).
228+
FirstOrCreate()
253229

254-
fmt.Println("success initialize")
230+
if err != nil {
231+
fmt.Println("config migrate error")
232+
os.Exit(0)
255233
}
234+
235+
fmt.Println("success initialize")
256236
}

internal/dal/repository/sys_config.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,44 @@ import (
66
"github.com/ch3nnn/webstack-go/internal/dal/query"
77
)
88

9+
const (
10+
DefaultAboutSite = "> ❤️ 基于 Golang 开源的网址导航网站项目,具备完整的前后台,您可以拿来制作自己平日收藏的网址导航。\n\n\n> 如果你也是开发者,如果你也正好喜欢折腾,那希望这个网站能给你带来一些作用。"
11+
DefaultAuthor = `
12+
<div class="col-sm-4">
13+
<div class="xe-widget xe-conversations box2 label-info" onclick="window.open('https://blog.ch3nnn.cn/about/', '_blank')" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="https://blog.ch3nnn.cn/about/">
14+
<div class="xe-comment-entry">
15+
<a class="xe-user-img">
16+
<img src="https://s2.loli.net/2023/02/20/H1k52mlXNYKWDrU.png" class="img-circle" width="40">
17+
</a>
18+
<div class="xe-comment">
19+
<a href="#" class="xe-user-name overflowClip_1">
20+
<strong>Developer. Ch3nnn.</strong>
21+
</a>
22+
<p class="overflowClip_2"> 折腾不息 · 乐此不疲.</p>
23+
</div>
24+
</div>
25+
</div>
26+
</div>
27+
28+
<div class="col-md-8">
29+
<div class="row">
30+
<div class="col-sm-12">
31+
<br>
32+
<blockquote>
33+
<p>
34+
这是一个公益项目,而且是<a href="https://github.com/ch3nnn/webstack-go"> 开源 </a>的。你也可以拿来制作自己的网址导航。如果你有更好的想法,可以通过个人网站<a href="https://ch3nnn.cn/about/">ch3nnn.cn</a>中的联系方式找到我,欢迎与我交流分享。
35+
</p>
36+
</blockquote>
37+
</div>
38+
</div>
39+
<br>
40+
</div>
41+
`
42+
DefaultSiteTitle = "WebStack-Go - 网址导航"
43+
DefaultSiteKeyword = "网址导航"
44+
DefaultSiteDesc = "WebStack-Go - 基于 Golang 开源的网址导航网站"
45+
)
46+
947
var _ iCustomGenSysConfigFunc = (*customSysConfigDao)(nil)
1048

1149
type (

internal/dal/repository/sys_user.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ import (
66
"github.com/ch3nnn/webstack-go/internal/dal/query"
77
)
88

9+
const (
10+
DefaultUname = "admin"
11+
DefaultUPassword = "admin"
12+
)
13+
914
var _ iCustomGenSysUserFunc = (*customSysUserDao)(nil)
1015

1116
type (

internal/service/config/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
)
1313

1414
func (s *service) GetConfig(ctx context.Context) (*v1.ConfigResp, error) {
15-
conf, err := s.configRepo.WithContext(ctx).FindOne(s.configRepo.WhereByID(1))
15+
conf, err := s.configRepo.WithContext(ctx).FindOne()
1616
if err != nil {
1717
return nil, err
1818
}

internal/service/user/updatepassword.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ func (s *service) UpdatePassword(ctx *gin.Context, req *v1.UpdatePasswordReq) (*
2020
user, err := s.userRepo.WithContext(ctx).
2121
FindOne(
2222
s.userRepo.WhereByID(ctx.GetInt(middleware.UserID)),
23-
s.userRepo.WhereByPassword(req.OldPassword),
2423
)
2524
if err != nil {
2625
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -29,10 +28,14 @@ func (s *service) UpdatePassword(ctx *gin.Context, req *v1.UpdatePasswordReq) (*
2928
return nil, err
3029
}
3130

31+
if user.Password != req.OldPassword {
32+
return nil, v1.ErrorUserOldPassword
33+
}
34+
3235
_, err = s.userRepo.WithContext(ctx).Update(&model.SysUser{Password: req.NewPassword}, s.userRepo.WhereByID(user.ID))
3336
if err != nil {
3437
return nil, err
3538
}
3639

37-
return &v1.UpdatePasswordResp{}, nil
40+
return nil, nil
3841
}

0 commit comments

Comments
 (0)