Skip to content
This repository has been archived by the owner on Aug 4, 2021. It is now read-only.

Commit

Permalink
<feat> finlly add casbin to our server .
Browse files Browse the repository at this point in the history
Signed-off-by: JackyCZJ <chenzj@esixnetwork.net>
  • Loading branch information
JackyCZJ committed Mar 2, 2020
1 parent dee5040 commit e660055
Show file tree
Hide file tree
Showing 10 changed files with 185 additions and 29 deletions.
19 changes: 6 additions & 13 deletions auth/Auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ import (
cacheClient "github.com/jackyczj/July/cache"

"github.com/jackyczj/July/handler/user"
"github.com/jackyczj/July/log"
"github.com/labstack/echo/v4"
"github.com/spf13/viper"
)

// skipper 这些不需要token
Expand All @@ -29,8 +27,11 @@ func Skipper(c echo.Context) bool {
if method != "GET" {
return false
}
if path == "" {
switch path {
case "",
"/api/v1/Goods/index":
return true

}
resource := strings.Split(path, "/")[1]
switch resource {
Expand All @@ -44,24 +45,16 @@ func Skipper(c echo.Context) bool {
}

// Validator 校验token是否合法,顺便根据token在 context中赋值 user id
func Validator(token string, c echo.Context) (bool, error) {
// 调试后门
log.Logworker.Debug("token:", token)
if viper.GetString("runmode") == "debug" {
c.Set("user_id", 1)
return true, nil
}
// 寻找token
func Validator(token string, c echo.Context) (bool, error) { // 寻找token
var t = new(user.Token)
err := cacheClient.GetCc("token:"+token, t)
if err == cache.ErrCacheMiss {
print(t)
return false, nil
} else if err != nil {
return false, err
}
// 设置用户
c.Set("user_id", t.UserID)

c.Set("role", t.Role)
return true, nil
}
81 changes: 81 additions & 0 deletions auth/casbin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package auth

import (
"fmt"
"net/http"
"strconv"

"github.com/casbin/casbin/v2"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

type (
// Config defines the config for CasbinAuth middleware.
Config struct {
// Skipper defines a function to skip middleware.
Skipper middleware.Skipper

// Enforcer CasbinAuth main rule.
// Required.
Enforcer *casbin.Enforcer
}
)

var (
// DefaultConfig is the default CasbinAuth middleware config.
DefaultConfig = Config{
Skipper: middleware.DefaultSkipper,
}
)

func MiddlewareWithConfig(config Config) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultConfig.Skipper
}

return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}

if pass, err := config.CheckPermission(c); err == nil && pass {
return next(c)
} else if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}

return echo.ErrForbidden
}
}
}

func Middleware(ce *casbin.Enforcer) echo.MiddlewareFunc {
c := DefaultConfig
c.Enforcer = ce
return MiddlewareWithConfig(c)
}

func (a *Config) CheckPermission(e echo.Context) (bool, error) {
user := e.Get("user_id")
role := e.Get("role")
if user == nil && role == nil {
user = "guest"
_, err := a.Enforcer.AddRoleForUser(user.(string), "0")
if err != nil {
return false, err
}
}
role = strconv.Itoa(role.(int))

_, err := a.Enforcer.AddRoleForUser(user.(string), role.(string))
if err != nil {
return false, err
}
method := e.Request().Method
path := e.Request().URL.Path
fmt.Println(user.(string), method, path)
return a.Enforcer.Enforce(role, path, method)
}
16 changes: 15 additions & 1 deletion cmd/buyer-server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package main
import (
"net/http"

"github.com/jackyczj/July/log"

"github.com/casbin/casbin/v2"
"github.com/jackyczj/July/handler/goods"

Auth "github.com/jackyczj/July/auth"
Expand Down Expand Up @@ -38,12 +41,22 @@ func Load(e *echo.Echo) {
AuthScheme: "Bearer",
}))

enforcer, err := casbin.NewEnforcer("conf/casbin_auth_model.conf", "conf/casbin_auth_policy.csv")
if err != nil {
log.Logworker.Fatal(err.Error())
}

e.Use(Auth.MiddlewareWithConfig(Auth.Config{
Skipper: Auth.Skipper,
Enforcer: enforcer,
}))

// init config
//Account := e.Group("/user/", middleware.CSRF())
Account := e.Group("/user")
{
Account.POST("/login", user.Login)
Account.GET("/logout", user.Logout)
Account.POST("/logout", user.Logout)
Account.POST("/register", user.Register)

}
Expand All @@ -61,6 +74,7 @@ func Load(e *echo.Echo) {
{
//Goods.GET("/Goods/:str",goodsHandler.Search) //search
Goods.GET("/index", goods.Index) //index goods list
Goods.GET("/:id", goods.Get)
}

cart := api.Group("/cart")
Expand Down
14 changes: 14 additions & 0 deletions conf/casbin_auth_model.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*")
32 changes: 32 additions & 0 deletions conf/casbin_auth_policy.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
p , 3 , /*, (GET|POST|PUT|DELETE)

p , 0 , /user/login , POST
p , 0 , /user/register , POST

p , 1 , /user/logout , POST
p , 2 , /user/logout , POST

p , 1 , /user/setting/* , (GET|POST|PUT|DELETE)
p , 2 , /user/setting/* , (GET|POST|PUT|DELETE)


p, 0 , /api/v1/Goods/* , GET
p, 1 , /api/v1/Goods/* , GET
p, 2 , /api/v1/Goods/* , (GET|POST|PUT|DELETE)

p , 1 , /api/v1/Order/:id , (GET|POST|PUT|DELETE)
p , 1 , /api/v1/Order , (POST|PUT)
p , 2 , /api/v1/Order/:id/* , (GET|POST|PUT|DELETE)


p, 0 , /api/v1/Shop/* , GET
p, 1 , /api/v1/Shop/* , GET
p, 2 , /api/v1/Shop/* , (GET|POST|PUT|DELETE)
p, 2 , /api/v1/Shop/setting/* , (GET|POST|PUT|DELETE)


p, 0 , /api/v1/Cart , (GET|POST|PUT|DELETE)
p, 1 , /api/v1/Cart , (GET|POST|PUT|DELETE)
p, 2 , /api/v1/Cart , (GET|POST|PUT|DELETE)


3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
github.com/aristanetworks/goarista v0.0.0-20191023202215-f096da5361bb // indirect
github.com/bilibili/kratos v0.2.3 // indirect
github.com/casbin/casbin v1.9.1
github.com/casbin/casbin/v2 v2.2.1
github.com/coreos/bbolt v1.3.3 // indirect
github.com/coreos/etcd v3.3.15+incompatible // indirect
github.com/coreos/go-semver v0.3.0 // indirect
Expand Down Expand Up @@ -49,7 +50,7 @@ require (
github.com/klauspost/reedsolomon v1.9.3 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/labstack/echo v3.3.10+incompatible
github.com/labstack/echo-contrib v0.6.0
github.com/labstack/echo-contrib v0.8.1-0.20200115200653-2d4a7f3c41d8
github.com/labstack/echo/v4 v4.1.6
github.com/leodido/go-urn v1.2.0 // indirect
github.com/magiconair/properties v1.8.1 // indirect
Expand Down
14 changes: 14 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798 h1:2T/jmrHeTezcCM58lvEQXs0UpQJCo5SoGAcg+mbSTIg=
github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible h1:1G1pk05UrOh0NlF1oeaaix1x8XzrfjIDK47TY0Zehcw=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/OneOfOne/xxhash v1.2.5/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdIIOT9Um7Q=
Expand All @@ -35,6 +36,7 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/appleboy/gofight/v2 v2.1.2/go.mod h1:frW+U1QZEdDgixycTj4CygQ48yLTUhplt43+Wczp3rw=
github.com/aristanetworks/fsnotify v1.4.2/go.mod h1:D/rtu7LpjYM8tRJphJ0hUBYpjai8SfX+aSNsWDTq/Ks=
github.com/aristanetworks/glog v0.0.0-20180419172825-c15b03b3054f/go.mod h1:KASm+qXFKs/xjSoWn30NrWBBvdTTQq+UjkhjEJHfSFA=
github.com/aristanetworks/goarista v0.0.0-20190912214011-b54698eaaca6/go.mod h1:Z4RTxGAuYhPzcq8+EdRM+R8M48Ssle2TsWtwRKa+vns=
Expand All @@ -50,12 +52,17 @@ github.com/bilibili/kratos v0.2.3/go.mod h1:6+zElXcSSpHmz+hhR3ttQOO+aPaa2akUTXda
github.com/casbin/casbin v1.8.2/go.mod h1:z8uPsfBJGUsnkagrt3G8QvjgTKFMBJ32UP8HpZllfog=
github.com/casbin/casbin v1.9.1 h1:ucjbS5zTrmSLtH4XogqOG920Poe6QatdXtz1FEbApeM=
github.com/casbin/casbin v1.9.1/go.mod h1:z8uPsfBJGUsnkagrt3G8QvjgTKFMBJ32UP8HpZllfog=
github.com/casbin/casbin/v2 v2.0.0 h1:OIcnP8SxwF1gmGxOn7Kod/O/7yJikpHWQz0qiBJpG/U=
github.com/casbin/casbin/v2 v2.0.0/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/casbin/casbin/v2 v2.2.1 h1:ijrSMfBfbQlDc4LnMTGtGYWmhKuuR6RLSQRj8vHrMzc=
github.com/casbin/casbin/v2 v2.2.1/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/cespare/xxhash/v2 v2.1.0/go.mod h1:dgIUBU3pDso/gPgZ1osOZ0iQf77oPR28Tjxl5dIMyVM=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cockroachdb/datadriven v0.0.0-20190531201743-edce55837238/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=
github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=
github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/bbolt v1.3.3/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
Expand Down Expand Up @@ -245,6 +252,8 @@ github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8
github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s=
github.com/labstack/echo-contrib v0.6.0 h1:WT+TwJkJXrK+9n+x5VcI8f17VkUsiY33H5Mw3Pe8OfI=
github.com/labstack/echo-contrib v0.6.0/go.mod h1:uQPocfnb5ZG2Nl0wsNaGEMTvGK16NF5vo/GHECCuJz4=
github.com/labstack/echo-contrib v0.8.1-0.20200115200653-2d4a7f3c41d8 h1:cyQ4DlCCMM/W992FJ13BDhCJhcyEoAzrSQAAUM89LSw=
github.com/labstack/echo-contrib v0.8.1-0.20200115200653-2d4a7f3c41d8/go.mod h1:TsFE5Vv0LRpZLoh4mMmaaAxzcTH+1CBFiUtVhwlegzU=
github.com/labstack/echo/v4 v4.1.6 h1:WOvLa4T1KzWCRpANwz0HGgWDelXSSGwIKtKBbFdHTv4=
github.com/labstack/echo/v4 v4.1.6/go.mod h1:kU/7PwzgNxZH4das4XNsSpBSOD09XIF5YEPzjpkGnGE=
github.com/labstack/echo/v4 v4.1.11 h1:z0BZoArY4FqdpUEl+wlHp4hnr/oSR6MTmQmv8OHSoww=
Expand Down Expand Up @@ -424,6 +433,9 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tsuna/gohbase v0.0.0-20190502052937-24ffed0537aa/go.mod h1:3HfLQly3YNLGxNv/2YOfmz30vcjG9hbuME1GpxoLlGs=
github.com/tsuna/gohbase v0.0.0-20190823190353-a66bcc9075db/go.mod h1:3HfLQly3YNLGxNv/2YOfmz30vcjG9hbuME1GpxoLlGs=
github.com/uber-go/atomic v1.4.0/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g=
github.com/uber/jaeger-client-go v2.19.1-0.20191002155754-0be28c34dabf+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.2.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/ugorji/go v1.1.4 h1:j4s+tAvLfL3bZyefP2SEWmhBzmuIlH/eqNuPdFPgngw=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
Expand Down Expand Up @@ -702,6 +714,8 @@ gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
1 change: 0 additions & 1 deletion handler/goods/goods.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ func Index(ctx echo.Context) error {
fmt.Println(err.Error())
return ctx.JSON(200, nil)
}
fmt.Println(data)
return handler.Response(ctx, handler.ResponseStruct{
Code: 0,
Message: "",
Expand Down
2 changes: 2 additions & 0 deletions handler/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
type Token struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
Role int `json:"role"`
UserID string `json:"-"`
}

Expand Down Expand Up @@ -87,6 +88,7 @@ func Login(e echo.Context) error {
t := &Token{
Token: utils.NewUUID(),
ExpiresAt: time.Now().Add(time.Hour * 76),
Role: u.Role,
UserID: strconv.FormatUint(uint64(u.Id), 10),
}
cache.SetCc("token:"+t.Token, t, time.Hour*76)
Expand Down
32 changes: 19 additions & 13 deletions store/goods.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type Product struct {
CreateAt time.Time `json:"create_at" bson:"create_at,omitempty"` //创建时间
Shelves bool `json:"shelves" bson:"shelves,omitempty"` //是否上架
IsDelete bool `json:"is_delete" bson:"is_delete,omitempty"` //是否已删除
sync.RWMutex `bson:"_"`
sync.RWMutex `json:"_" bson:"_"`
}

type Type struct {
Expand Down Expand Up @@ -140,31 +140,37 @@ func (p *Product) Update() error {
})
}

func GetRandom() ([]Product, error) {
var pList []Product
func GetRandom() ([]bson.M, error) {
var pList []bson.M
result, err := Client.db.Collection("good").Aggregate(context.Background(),
mongo.Pipeline{
bson.D{{"$match", bson.D{
{"shelves",
bson.D{
{"$eq", true},
}},
}}},
bson.D{
{
"$sample",
{"$match",
bson.D{
{"size", 10},
{"shelves",
bson.D{
{"$eq", true},
},
},
},
},
},
//},
//bson.D{
// {
// "$sample",
// bson.D{
// {"size", 10},
// },
// },
//},
})
if err != nil {
return nil, err
}

for result.Next(context.TODO()) {
var res Product
var res bson.M
_ = result.Decode(&res)
pList = append(pList, res)
}
Expand Down

0 comments on commit e660055

Please sign in to comment.