demo_test.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package test
  2. import (
  3. "fmt"
  4. "gfast/library/adapterUtils"
  5. "github.com/casbin/casbin/v2"
  6. "github.com/casbin/casbin/v2/util"
  7. "github.com/goflyfox/gtoken/gtoken"
  8. "github.com/gogf/gf/crypto/gaes"
  9. "github.com/gogf/gf/encoding/gbase64"
  10. "github.com/gogf/gf/frame/g"
  11. "github.com/gogf/gf/net/ghttp"
  12. "github.com/gogf/gf/os/glog"
  13. "github.com/mojocn/base64Captcha"
  14. "testing"
  15. )
  16. func TestDemo(t *testing.T) {
  17. //t.Run("demo1" ,Demo1)
  18. t.Run("Adapters_test", Adapters)
  19. //t.Run("CaptchaDemo", CaptchaDemo)
  20. //t.Run("CaptchaVerify", CaptchaVerify)
  21. //t.Run("GTokenTest", GTokenTest)
  22. //t.Run("CbcEncrypt", CbcEncrypt)
  23. }
  24. func HookDemo(t *testing.T) {
  25. // 基本事件回调使用
  26. p := "/:name/info/{uid}"
  27. s := g.Server()
  28. s.BindHookHandlerByMap(p, map[string]ghttp.HandlerFunc{
  29. ghttp.HOOK_BEFORE_SERVE: func(r *ghttp.Request) { glog.Println(ghttp.HOOK_BEFORE_SERVE) },
  30. ghttp.HOOK_AFTER_SERVE: func(r *ghttp.Request) { glog.Println(ghttp.HOOK_AFTER_SERVE) },
  31. ghttp.HOOK_BEFORE_OUTPUT: func(r *ghttp.Request) { glog.Println(ghttp.HOOK_BEFORE_OUTPUT) },
  32. ghttp.HOOK_AFTER_OUTPUT: func(r *ghttp.Request) { glog.Println(ghttp.HOOK_AFTER_OUTPUT) },
  33. })
  34. s.BindHandler(p, func(r *ghttp.Request) {
  35. r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid"))
  36. })
  37. s.SetPort(8199)
  38. s.Run()
  39. }
  40. func CbcEncrypt(t *testing.T) {
  41. b, e := gaes.EncryptCBC([]byte("yxh123456"), []byte("HqmP1KLMuz09Q0Bu"), []byte("HqmP1KLMuz09Q0Bu"))
  42. if e != nil {
  43. panic(e)
  44. }
  45. fmt.Println(gbase64.EncodeToString(b))
  46. b, _ = gaes.DecryptCBC(b, []byte("HqmP1KLMuz09Q0Bu"), []byte("HqmP1KLMuz09Q0Bu"))
  47. fmt.Println(string(b))
  48. }
  49. func Demo1(t *testing.T) {
  50. e, err := casbin.NewEnforcer("casbin_conf/model.conf", "casbin_conf/policy.csv")
  51. if err != nil {
  52. panic(err)
  53. }
  54. sub := "alice" // the user that wants to access a resource. 对象
  55. obj := "data1" // the resource that is going to be accessed. 资源
  56. act := "write" // the operation that the user performs on the resource. 操作
  57. ok, err := e.Enforce(sub, obj, act)
  58. if err != nil {
  59. fmt.Println("验证失败", err)
  60. }
  61. if ok == true {
  62. fmt.Println("权限通过")
  63. } else {
  64. fmt.Println("没有权限")
  65. }
  66. }
  67. func GTokenTest(t *testing.T) {
  68. // 启动gtoken
  69. gtoken := &gtoken.GfToken{
  70. LoginPath: "/login",
  71. LoginBeforeFunc: loginFunc,
  72. LogoutPath: "/user/logout",
  73. AuthPaths: g.SliceStr{"/system/*"},
  74. LogoutBeforeFunc: loginOutFunc,
  75. }
  76. gtoken.Start()
  77. s := g.Server()
  78. s.BindHandler("/system/admin", func(r *ghttp.Request) {
  79. r.Response.Write("hello admin")
  80. })
  81. s.SetPort(8080)
  82. s.Run()
  83. }
  84. func loginFunc(r *ghttp.Request) (string, interface{}) {
  85. return "yixiaohu", []g.MapStrStr{{"name": "张三", "age": "18"}, {"name": "李四", "age": "32"}}
  86. }
  87. func loginOutFunc(r *ghttp.Request) bool {
  88. return true
  89. }
  90. func demoCodeCaptchaCreate() {
  91. //config struct for digits
  92. //数字验证码配置
  93. /*var configD = base64Captcha.ConfigDigit{
  94. Height: 80,
  95. Width: 240,
  96. MaxSkew: 0.7,
  97. DotCount: 80,
  98. CaptchaLen: 5,
  99. }*/
  100. //config struct for audio
  101. //声音验证码配置
  102. /*var configA = base64Captcha.ConfigAudio{
  103. CaptchaLen: 6,
  104. Language: "zh",
  105. }*/
  106. //config struct for Character
  107. //字符,公式,验证码配置
  108. var configC = base64Captcha.ConfigCharacter{
  109. Height: 60,
  110. Width: 240,
  111. //const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,CaptchaModeNumberAlphabet:数字字母混合.
  112. Mode: base64Captcha.CaptchaModeNumber,
  113. ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
  114. ComplexOfNoiseDot: base64Captcha.CaptchaComplexLower,
  115. IsShowHollowLine: false,
  116. IsShowNoiseDot: false,
  117. IsShowNoiseText: false,
  118. IsShowSlimeLine: false,
  119. IsShowSineLine: false,
  120. CaptchaLen: 4,
  121. }
  122. //创建字符公式验证码.
  123. //GenerateCaptcha 第一个参数为空字符串,包会自动在服务器一个随机种子给你产生随机uiid.
  124. idKeyC, capC := base64Captcha.GenerateCaptcha("8nM77YhE2xOvU6GMQ33A", configC)
  125. //以base64编码
  126. base64stringC := base64Captcha.CaptchaWriteToBase64Encoding(capC)
  127. fmt.Println(idKeyC, "\n", base64stringC)
  128. }
  129. func CaptchaDemo(t *testing.T) {
  130. demoCodeCaptchaCreate()
  131. }
  132. func CaptchaVerify(t *testing.T) {
  133. if base64Captcha.VerifyCaptchaAndIsClear("8nM77YhE2xOvU6GMQ33A", "0870", false) {
  134. fmt.Println("验证成功")
  135. } else {
  136. fmt.Println("验证失败")
  137. }
  138. }
  139. func Adapters(t *testing.T) {
  140. a := initAdapter(t, "mysql", "root:123456@tcp(127.0.0.1:3306)/test2")
  141. testAutoSave(t, a)
  142. testSaveLoad(t, a)
  143. a = initAdapterFormOptions(t, &adapterUtils.Adapter{
  144. DriverName: "mysql",
  145. DataSourceName: "root:123456@tcp(127.0.0.1:3306)/test2",
  146. })
  147. testAutoSave(t, a)
  148. testSaveLoad(t, a)
  149. }
  150. func initAdapterFormOptions(t *testing.T, adapter *adapterUtils.Adapter) *adapterUtils.Adapter {
  151. // Create an adapter
  152. a, _ := adapterUtils.NewAdapterFromOptions(adapter)
  153. // Initialize some policy in DB.
  154. initPolicy(t, a)
  155. // Now the DB has policy, so we can provide a normal use case.
  156. // Note: you don't need to look at the above code
  157. // if you already have a working DB with policy inside.
  158. return a
  159. }
  160. func initPolicy(t *testing.T, a *adapterUtils.Adapter) {
  161. // Because the DB is empty at first,
  162. // so we need to load the policy from the file adapter (.CSV) first.
  163. e, err := casbin.NewEnforcer("casbin_conf/rbac_model.conf", "casbin_conf/rbac_policy.csv")
  164. if err != nil {
  165. panic(err)
  166. }
  167. // This is a trick to save the current policy to the DB.
  168. // We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.
  169. // The current policy means the policy in the Casbin enforcer (aka in memory).
  170. err = a.SavePolicy(e.GetModel())
  171. if err != nil {
  172. panic(err)
  173. }
  174. // Clear the current policy.
  175. e.ClearPolicy()
  176. testGetPolicy(t, e, [][]string{})
  177. // Load the policy from DB.
  178. err = a.LoadPolicy(e.GetModel())
  179. if err != nil {
  180. panic(err)
  181. }
  182. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
  183. }
  184. func testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) {
  185. myRes := e.GetPolicy()
  186. glog.Info("Policy: ", myRes)
  187. if !util.Array2DEquals(res, myRes) {
  188. t.Error("Policy: ", myRes, ", supposed to be ", res)
  189. }
  190. }
  191. func initAdapter(t *testing.T, driverName string, dataSourceName string) *adapterUtils.Adapter {
  192. // Create an adapter
  193. a, err := adapterUtils.NewAdapter(driverName, dataSourceName)
  194. if err != nil {
  195. panic(err)
  196. }
  197. // Initialize some policy in DB.
  198. initPolicy(t, a)
  199. // Now the DB has policy, so we can provide a normal use case.
  200. // Note: you don't need to look at the above code
  201. // if you already have a working DB with policy inside.
  202. return a
  203. }
  204. func testAutoSave(t *testing.T, a *adapterUtils.Adapter) {
  205. // NewEnforcer() will load the policy automatically.
  206. e, err := casbin.NewEnforcer("casbin_conf/rbac_model.conf", a)
  207. if err != nil {
  208. panic(err)
  209. }
  210. // AutoSave is enabled by default.
  211. // Now we disable it.
  212. e.EnableAutoSave(false)
  213. // Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,
  214. // it doesn't affect the policy in the storage.
  215. e.AddPolicy("alice", "data1", "write")
  216. // Reload the policy from the storage to see the effect.
  217. e.LoadPolicy()
  218. // This is still the original policy.
  219. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
  220. // Now we enable the AutoSave.
  221. e.EnableAutoSave(true)
  222. // Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,
  223. // but also affects the policy in the storage.
  224. e.AddPolicy("alice", "data1", "write")
  225. // Reload the policy from the storage to see the effect.
  226. e.LoadPolicy()
  227. // The policy has a new rule: {"alice", "data1", "write"}.
  228. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}, {"alice", "data1", "write"}})
  229. // Remove the added rule.
  230. e.RemovePolicy("alice", "data1", "write")
  231. e.LoadPolicy()
  232. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
  233. // Remove "data2_admin" related policy rules via a filter.
  234. // Two rules: {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"} are deleted.
  235. e.RemoveFilteredPolicy(0, "data2_admin")
  236. e.LoadPolicy()
  237. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}})
  238. }
  239. func testSaveLoad(t *testing.T, a *adapterUtils.Adapter) {
  240. // Initialize some policy in DB.
  241. initPolicy(t, a)
  242. // Note: you don't need to look at the above code
  243. // if you already have a working DB with policy inside.
  244. // Now the DB has policy, so we can provide a normal use case.
  245. // Create an adapter and an enforcer.
  246. // NewEnforcer() will load the policy automatically.
  247. e, _ := casbin.NewEnforcer("casbin_conf/rbac_model.conf", a)
  248. testGetPolicy(t, e, [][]string{{"alice", "data1", "read"}, {"bob", "data2", "write"}, {"data2_admin", "data2", "read"}, {"data2_admin", "data2", "write"}})
  249. }