auth.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package controller
  2. import (
  3. v1 "demo/api/v1"
  4. "demo/internal/app"
  5. "demo/internal/util"
  6. "fmt"
  7. "github.com/astaxie/beego/validation"
  8. "github.com/gogf/gf/v2/net/ghttp"
  9. "github.com/siddontang/go/log"
  10. "net/http"
  11. )
  12. func Auth(r *ghttp.Request) {
  13. appG := app.Ghttp{C: r}
  14. var reqInfo v1.Auth
  15. err := appG.C.Parse(&reqInfo)
  16. valid := validation.Validation{}
  17. valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
  18. valid.MaxSize(reqInfo.Password, 100, "password").Message("最长为100字符")
  19. if valid.HasErrors() {
  20. log.Error(valid.Errors)
  21. appG.Response(http.StatusInternalServerError, app.ERROR_ADD_FAIL, valid.Errors)
  22. return
  23. }
  24. isExist, err := srv.CheckUser(reqInfo.Username, reqInfo.Password)
  25. if err != nil {
  26. log.Error(err)
  27. appG.Response(http.StatusInternalServerError, app.ERROR_AUTH_CHECK_TOKEN_FAIL, err)
  28. return
  29. }
  30. if !isExist {
  31. appG.Response(http.StatusOK, app.ERROR_AUTH, "用户名或密码错误")
  32. return
  33. }
  34. token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password)
  35. if err != nil {
  36. appG.Response(http.StatusInternalServerError, app.ERROR_AUTH_TOKEN, err)
  37. return
  38. }
  39. appG.Response(http.StatusOK, app.SUCCESS, map[string]string{
  40. "token": token,
  41. })
  42. }
  43. func GetUserInfo(r *ghttp.Request) {
  44. appG := app.Ghttp{C: r}
  45. data := srv.GetUserInfo(r.Context().Value("jwt_username").(string))
  46. fmt.Println(r.Get("jwt_username").String())
  47. appG.Response(http.StatusOK, app.SUCCESS, data)
  48. }
  49. func UserLogout(r *ghttp.Request) {
  50. appG := app.Ghttp{C: r}
  51. data := make(map[string]interface{})
  52. data["name"] = ""
  53. data["avatar"] = ""
  54. data["introduction"] = ""
  55. appG.Response(http.StatusOK, app.SUCCESS, data)
  56. }