controller.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package oauth2
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/astaxie/beego/logs"
  7. "github.com/astaxie/beego/orm"
  8. "io"
  9. "nginx-ui/server/base"
  10. "nginx-ui/server/config"
  11. "nginx-ui/server/models"
  12. "nginx-ui/server/utils"
  13. )
  14. type Controller struct {
  15. base.Controller
  16. }
  17. type SSOReq struct {
  18. Code string `Json:"code"`
  19. Scope string `Json:"scope"`
  20. State string `Json:"state"`
  21. }
  22. // Get 获取oauth2.0的登录url
  23. func (c *Controller) Get() {
  24. state, err := utils.RandPassword(6)
  25. if err != nil {
  26. c.ErrorJson(err)
  27. return
  28. }
  29. url := config.OauthConfig.AuthCodeURL(state)
  30. c.AddRespData("redirect_url", url).AddRespData("state", state).Json()
  31. }
  32. // Callback 用户注册
  33. func (c *Controller) Callback() {
  34. var ssoReq SSOReq
  35. err := json.Unmarshal(c.Ctx.Input.RequestBody, &ssoReq)
  36. if err != nil {
  37. logs.Error(err, string(c.Ctx.Input.RequestBody))
  38. c.ErrorJson(err)
  39. return
  40. }
  41. oauth := config.OauthConfig
  42. if len(ssoReq.Code) == 0 {
  43. c.SetCode(-1).SetMsg("登录失败(Code):code is empty").Json()
  44. return
  45. }
  46. token, err := oauth.Exchange(context.Background(), ssoReq.Code)
  47. if err != nil {
  48. logs.Error("ExchangeToken", err)
  49. c.SetCode(-1).SetMsg("登录失败(Exchange):" + err.Error()).Json()
  50. return
  51. }
  52. client := oauth.Client(context.Background(), token)
  53. resp, err := client.Get(oauth.Userinfo)
  54. if err != nil {
  55. logs.Error("GetUserinfo", err)
  56. c.SetCode(-1).SetMsg(fmt.Sprintf("登录失败(Userinfo):%s", err.Error())).Json()
  57. return
  58. }
  59. defer resp.Body.Close()
  60. content, err := io.ReadAll(resp.Body)
  61. if err != nil {
  62. logs.Error("GetUserinfo Read Body", err)
  63. c.SetCode(-1).SetMsg(fmt.Sprintf("登录失败(Userinfo):%s", err.Error())).Json()
  64. return
  65. }
  66. user := models.User{}
  67. err = json.Unmarshal(content, &user)
  68. if err != nil {
  69. logs.Error("GetUserinfo Unmarshal", err)
  70. }
  71. if len(user.Account) == 0 {
  72. c.SetCode(-1).SetMsg("登录失败,请确认userinfo接口返回了account字段").Json()
  73. return
  74. }
  75. if len(user.Nickname) == 0 {
  76. user.Nickname = user.Account
  77. }
  78. o := orm.NewOrm()
  79. err = o.Read(&user, "Account")
  80. if err != nil {
  81. _, err = o.Insert(&user)
  82. }
  83. user.Password = ""
  84. if err != nil {
  85. c.SetCode(-1).SetMsg(fmt.Sprintf("保存用户失败:%s", err.Error())).Json()
  86. return
  87. }
  88. c.SetSession("user", user)
  89. c.SetData(user).Json()
  90. }