Skip to content

Commit 8139776

Browse files
committed
Fix token generation
1 parent 9a60489 commit 8139776

File tree

4 files changed

+19
-3
lines changed

4 files changed

+19
-3
lines changed

database.db

0 Bytes
Binary file not shown.

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.20
44

55
require (
66
github.com/gin-gonic/gin v1.9.1
7+
github.com/google/uuid v1.3.0
78
gorm.io/driver/sqlite v1.5.2
89
gorm.io/gorm v1.25.2
910
)

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS
2626
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
2727
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
2828
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
29+
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
30+
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
2931
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
3032
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
3133
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=

main.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"strconv"
55

66
"github.com/gin-gonic/gin"
7+
"github.com/google/uuid"
78
"gorm.io/driver/sqlite"
89
"gorm.io/gorm"
910
)
@@ -91,9 +92,16 @@ func main() {
9192
}
9293

9394
var token Token
94-
if err := db.Where("user_id = ?", user.ID).FirstOrCreate(&token).Error; err != nil {
95-
c.JSON(400, gin.H{"code": 1, "message": "无法生成token"})
96-
return
95+
if err := db.Where("user_id = ?", user.ID).First(&token).Error; err != nil {
96+
// If token does not exist, create a new token for the user
97+
token = Token{
98+
UserID: user.ID,
99+
Token: generateToken(user.ID), // Assume there is a function generateToken to generate a unique token
100+
}
101+
if err := db.Create(&token).Error; err != nil {
102+
c.JSON(400, gin.H{"code": 1, "message": "无法生成token"})
103+
return
104+
}
97105
}
98106

99107
c.JSON(200, gin.H{"code": 0, "message": "登录成功", "token": token.Token})
@@ -217,3 +225,8 @@ func main() {
217225

218226
r.Run()
219227
}
228+
229+
func generateToken(userID uint) string {
230+
token := uuid.New().String() // Generate a unique token using UUID
231+
return token
232+
}

0 commit comments

Comments
 (0)