oauth2.go 2.0 KB

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