Skip to content

Commit

Permalink
增加中间件,删除冗余鉴权代码
Browse files Browse the repository at this point in the history
  • Loading branch information
palp1tate committed Aug 16, 2023
1 parent ae03523 commit 710df59
Show file tree
Hide file tree
Showing 9 changed files with 19 additions and 134 deletions.
11 changes: 0 additions & 11 deletions controllers/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,6 @@ func (c *CommentController) CommentAction() {
commentContext := c.GetString("comment_text") // 评论内容
commentId, _ := strconv.Atoi(c.GetString("comment_id")) // 评论id

// 鉴权
if err := utils.ValidateToken(tokenString); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
"comment": nil,
}
c.ServeJSON()
return
}

// 解析token
user, err := utils.GetUserFromToken(tokenString)
if err != nil {
Expand Down
21 changes: 2 additions & 19 deletions controllers/favorite.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,7 @@ func (c *FavoriteController) FavoriteAction() {
tokenString := c.GetString("token") // 用户鉴权
videoId, _ := strconv.Atoi(c.GetString("video_id")) // 视频id
actionType, _ := strconv.Atoi(c.GetString("action_type")) // 1-点赞,2-取消点赞
// 鉴权
if err := utils.ValidateToken(tokenString); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
}
c.ServeJSON()
return
}

// 不能给自己点赞
username, err := utils.GetUsernameFromToken(tokenString)
if err != nil {
Expand Down Expand Up @@ -104,16 +96,7 @@ func (c *FavoriteController) FavoriteList() {
// 获取必要参数
userId, _ := strconv.Atoi(c.GetString("user_id")) // 用户id
tokenString := c.GetString("token") // 用户鉴权token
// 鉴权
if err := utils.ValidateToken(tokenString); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
"video_list": nil,
}
c.ServeJSON()
return
}

// 解析token
user, err := utils.GetUserFromToken(tokenString)
if err != nil {
Expand Down
38 changes: 1 addition & 37 deletions controllers/follow.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,6 @@ func (c *FollowController) ActionRelation() {
toUserId, _ := c.GetInt("to_user_id")
actionType, _ := c.GetInt("action_type")

// 鉴权
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
}
c.ServeJSON()
return
}

fromUserId, _ := utils.GetUserIdFromToken(token)

if fromUserId == toUserId {
Expand Down Expand Up @@ -94,15 +84,7 @@ func (c *FollowController) ActionRelation() {
// 获取关注列表
func (c *FollowController) ListFollowRelation() {
token := c.GetString("token")
// 鉴权
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
}
c.ServeJSON()
return
}

userId, _ := c.GetInt("user_id")
followList, err := GetAllFollowByUserId(c, userId, token)
if err != nil {
Expand Down Expand Up @@ -134,15 +116,6 @@ func (c *FollowController) ListFollowerRelation() {
return
}
token := c.GetString("token")
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
"video_list": nil,
}
c.ServeJSON()
return
}

// 查询当前用户的粉丝关系
var follows []models.Follow
Expand Down Expand Up @@ -184,15 +157,6 @@ func (c *FollowController) ListFriendRelation() {
}

token := c.GetString("token")
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
"video_list": nil,
}
c.ServeJSON()
return
}

// 定义一个切片来存储多个粉丝关系查询结果
var follows []models.Follow
Expand Down
19 changes: 1 addition & 18 deletions controllers/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,7 @@ type MessageController struct {
func (c *MessageController) ChatMessage() {
token := c.GetString("token")
toUserId, _ := c.GetInt("to_user_id")
// 鉴权
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token鉴权失败",
}
c.ServeJSON()
return
}

fromUserId, _ := utils.GetUserIdFromToken(token)

if fromUserId == toUserId {
Expand Down Expand Up @@ -91,15 +83,6 @@ func (c *MessageController) ActionMessage() {
return
}

if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
"video_list": nil,
}
c.ServeJSON()
return
}
actionType := c.GetString("action_type")
if actionType == "1" {
toUserId, err := strconv.Atoi(c.GetString("to_user_id"))
Expand Down
10 changes: 1 addition & 9 deletions controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,7 @@ func (c *UserController) Login() {
func (c *UserController) Info() {
uid, _ := c.GetInt("user_id")
token := c.GetString("token")
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
"user": nil,
}
c.ServeJSON()
return
}

userInfo := c.GetUserInfo(uid, token)
c.Data["json"] = map[string]interface{}{
"status_code": 0,
Expand Down
13 changes: 0 additions & 13 deletions controllers/video.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,6 @@ func (c *VideoController) Feed() {
func (c *VideoController) Publish() {
token := c.GetString("token")
title := c.GetString("title")
if err := utils.ValidateToken(token); err != nil {
c.PublishFail("token验证失败")
return
}

user, _ := utils.GetUserFromToken(token)
if url := c.UploadMP4(c.GetFile("data")); url == "" {
Expand Down Expand Up @@ -134,15 +130,6 @@ func (c *VideoController) PublishFail(msg string) {
func (c *VideoController) List() {
uid, _ := c.GetInt("user_id")
token := c.GetString("token")
if err := utils.ValidateToken(token); err != nil {
c.Data["json"] = map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
"video_list": nil,
}
c.ServeJSON()
return
}
var (
videos []*models.Video
videoList []*object.VideoInfo
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package main
import (
_ "ByteRhythm/models"
_ "ByteRhythm/routers"
"ByteRhythm/utils"
"github.com/beego/beego/v2/server/web"
)

func main() {
//web.InsertFilter("*", web.BeforeRouter, utils.FilterToken)
web.InsertFilter("*", web.BeforeRouter, utils.FilterToken)
web.Run()
}
12 changes: 6 additions & 6 deletions routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ func init() {
web.NSRouter("/list/", &controllers.CommentController{}, "get:CommentList"),
),
web.NSNamespace("/relation",
web.NSRouter("/action", &controllers.FollowController{}, "post:ActionRelation"),
web.NSRouter("/follow/list", &controllers.FollowController{}, "get:ListFollowRelation"),
web.NSRouter("/follower/list", &controllers.FollowController{}, "get:ListFollowerRelation"),
web.NSRouter("/friend/list", &controllers.FollowController{}, "get:ListFriendRelation"),
web.NSRouter("/action/", &controllers.FollowController{}, "post:ActionRelation"),
web.NSRouter("/follow/list/", &controllers.FollowController{}, "get:ListFollowRelation"),
web.NSRouter("/follower/list/", &controllers.FollowController{}, "get:ListFollowerRelation"),
web.NSRouter("/friend/list/", &controllers.FollowController{}, "get:ListFriendRelation"),
),
web.NSNamespace("/message",
web.NSRouter("/chat", &controllers.MessageController{}, "get:ChatMessage"),
web.NSRouter("/action", &controllers.MessageController{}, "post:ActionMessage"),
web.NSRouter("/chat/", &controllers.MessageController{}, "get:ChatMessage"),
web.NSRouter("/action/", &controllers.MessageController{}, "post:ActionMessage"),
),
)
web.AddNamespace(ns)
Expand Down
26 changes: 6 additions & 20 deletions utils/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/context"
"github.com/dgrijalva/jwt-go"
"strings"
"time"
)

Expand Down Expand Up @@ -105,26 +104,13 @@ func GenerateToken(user models.User, expiredSeconds int) (tokenString string) {
}

var FilterToken = func(ctx *context.Context) {
logs.Info("current router path is ", ctx.Request.RequestURI)

if ctx.Request.RequestURI != "/douyin/user/login/" && ctx.Input.Header("Authorization") == "" {
logs.Error("without token, unauthorized !!")
ctx.ResponseWriter.WriteHeader(401)
ctx.ResponseWriter.Write([]byte("no permission"))
return
}

if ctx.Request.RequestURI != "/douyin/user/login/" && ctx.Input.Header("Authorization") != "" {
token := ctx.Input.Header("Authorization")
token = strings.Split(token, " ")[0] // Split by space to get the actual token

//logs.Info("current token: ", token)

// Validate token
//获取token字段的值,token在url中传递
if token := ctx.Input.Query("token"); token != "" {
if err := ValidateToken(token); err != nil {
logs.Error("invalid or expired token: ", err)
ctx.ResponseWriter.WriteHeader(401)
ctx.ResponseWriter.Write([]byte("invalid or expired token"))
ctx.Output.JSON(map[string]interface{}{
"status_code": 1,
"status_msg": "token验证失败",
}, false, false)
return
}
}
Expand Down

0 comments on commit 710df59

Please sign in to comment.