demo_test.go 7.8 KB

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