Skip to content

Commit

Permalink
feat: 支持cookie和添加token-check接口
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Apr 12, 2024
1 parent fb0b3b4 commit ab75928
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 5 deletions.
31 changes: 31 additions & 0 deletions backend/controller/accapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func NewAccountRouter(rg *gin.RouterGroup, as service.AccountService) *AccountRo
group.POST("/login", ar.LoginAccount)
group.PUT("/reset", ar.ResetPassword)
group.PUT("/change-pwd", ar.ChangePassword)
group.GET("/token-check", ar.CheckToken)

return ar
}
Expand Down Expand Up @@ -67,6 +68,9 @@ func (ar *AccountRouter) LoginAccount(c *gin.Context) {
return
}

// set-cookie
c.SetCookie("access-token", token, 3600, "/", c.Request.Host, false, true)

ar.Success(c, gin.H{
"token": token,
})
Expand Down Expand Up @@ -122,3 +126,30 @@ func (ar *AccountRouter) ChangePassword(c *gin.Context) {

ar.Success(c, nil)
}

// 检查token
func (ar *AccountRouter) CheckToken(c *gin.Context) {
uin, err := ar.GetUin(c)

if err != nil {
ar.StatusCode(c, 401, err.Error())
return
}

acc, err := ar.AccountService.DB.GetAccountByUIN(uin)

if err != nil {
ar.StatusCode(c, 500, err.Error())
return
}

if acc == nil {
ar.StatusCode(c, 401, service.ErrAccountNotFound.Error())
return
}

ar.Success(c, gin.H{
"uin": uin,
"user_group": acc.UserGroup,
})
}
26 changes: 21 additions & 5 deletions backend/controller/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,30 @@ type APIRouter struct {

// 从jwt取uin
func (ar *APIRouter) GetUin(c *gin.Context) (int64, error) {
jwtToken := c.GetHeader("Authorization")

// 删除Bearer
jwtToken = jwtToken[7:]
// 尝试从header取jwt token
if c.GetHeader("Authorization") != "" {

uin, err := util.ParseJWTToken(jwtToken)
jwtToken := c.GetHeader("Authorization")

return uin, err
// 删除Bearer
jwtToken = jwtToken[7:]

uin, err := util.ParseJWTToken(jwtToken)

return uin, err
} else {
// 尝试从cookies取jwt token
jwtToken, err := c.Cookie("access-token")

if err != nil {
return -1, err
}

uin, err := util.ParseJWTToken(jwtToken)

return uin, err
}
}

func (ar *APIRouter) Success(c *gin.Context, data interface{}) {
Expand Down
7 changes: 7 additions & 0 deletions backend/controller/postapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ func NewPostRouter(rg *gin.RouterGroup, ps service.PostService) *PostRouter {

// 上传图片
func (pr *PostRouter) UploadImage(c *gin.Context) {
_, err := pr.GetUin(c)

if err != nil {
pr.StatusCode(c, 401, err.Error())
return
}

// 取body的json里的图片数据
file, _, err := c.Request.FormFile("image")
if err != nil {
Expand Down

0 comments on commit ab75928

Please sign in to comment.