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)) + }) + }) +}