From 3c3f18b251abc3f193fe150079ca2364920df404 Mon Sep 17 00:00:00 2001 From: hupeh Date: Mon, 2 Jan 2023 16:28:27 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20:boom:=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E6=B3=A8=E5=86=8C=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/rts.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/app/rts.go b/app/rts.go index 3e4743b..8edae5e 100644 --- a/app/rts.go +++ b/app/rts.go @@ -5,6 +5,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/jwtauth/v5" "gorm.io/gorm" + "net/http" "strings" ) @@ -434,3 +435,51 @@ func GetGoodsPrices(w *ResponseWriter, r *Request) { w.Ok(goods) } } + +// RegisterRoutes 注册路由 +func RegisterRoutes(r chi.Router) { + // 登录接口 + r.Post("/login", Handler(Login)) + + // 需要登录权限的 + r.Group(func(r chi.Router) { + r.Use(jwtauth.Verifier(tokenAuth)) + r.Use(jwtauth.Authenticator) + r.Use(CheckAuthToken) + + // 刷新令牌 + r.Get("/refresh-token", Handler(RefreshToken)) + + // 管理员 + r.Group(func(r chi.Router) { + // 验证是不是管理员 + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ut, ok := r.Context().Value("USER_TOKEN").(*UserToken) + if ok && ut.User != nil && ut.User.Admin { + next.ServeHTTP(w, r) + return + } + NewResponseWriter(w).Error(&Error{ + Status: http.StatusInternalServerError, + Code: 2, + Message: "用户信息错误", + }) + }) + }) + + r.Post("/user", Handler(CreateUser)) + r.Patch("/user/:id", Handler(UpdateUser)) + r.Delete("/user/:id", Handler(DeleteUser)) + r.Get("/users", Handler(ListUser)) + }) + + // 普通用户 + r.Group(func(r chi.Router) { + r.Post("/goods", Handler(CreateGoods)) + r.Patch("/goods/:id", Handler(UpdateGoods)) + r.Get("/goods", Handler(GetGoodsList)) + r.Get("/goods/:id/prices", Handler(GetGoodsPrices)) + }) + }) +}