handler.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. "github.com/dgrijalva/jwt-go"
  10. "github.com/labstack/echo"
  11. )
  12. type handler struct{}
  13. type userInfo struct {
  14. Result struct {
  15. Result struct {
  16. Sshpubkeyfp []string `json:"sshpubkeyfp"`
  17. HasKeytab bool `json:"has_keytab"`
  18. Ipasshpubkey []string `json:"ipasshpubkey"`
  19. Cn []string `json:"cn"`
  20. Krbcanonicalname []string `json:"krbcanonicalname"`
  21. Krbticketflags []string `json:"krbticketflags"`
  22. MemberofGroup []string `json:"memberof_group"`
  23. HasPassword bool `json:"has_password"`
  24. Homedirectory []string `json:"homedirectory"`
  25. Nsaccountlock bool `json:"nsaccountlock"`
  26. UID []string `json:"uid"`
  27. Title []string `json:"title"`
  28. Loginshell []string `json:"loginshell"`
  29. Uidnumber []string `json:"uidnumber"`
  30. Preserved bool `json:"preserved"`
  31. Krbextradata []struct {
  32. Base64 string `json:"__base64__"`
  33. } `json:"krbextradata"`
  34. Mail []string `json:"mail"`
  35. MemberofindirectHbacrule []string `json:"memberofindirect_hbacrule"`
  36. Dn string `json:"dn"`
  37. Displayname []string `json:"displayname"`
  38. Mepmanagedentry []string `json:"mepmanagedentry"`
  39. Ipauniqueid []string `json:"ipauniqueid"`
  40. Krbloginfailedcount []string `json:"krbloginfailedcount"`
  41. Krbpwdpolicyreference []string `json:"krbpwdpolicyreference"`
  42. Krbprincipalname []string `json:"krbprincipalname"`
  43. Givenname []string `json:"givenname"`
  44. Krblastadminunlock []struct {
  45. Datetime string `json:"__datetime__"`
  46. } `json:"krblastadminunlock"`
  47. Krbpasswordexpiration []struct {
  48. Datetime string `json:"__datetime__"`
  49. } `json:"krbpasswordexpiration"`
  50. Krblastfailedauth []struct {
  51. Datetime string `json:"__datetime__"`
  52. } `json:"krblastfailedauth"`
  53. Objectclass []string `json:"objectclass"`
  54. Gidnumber []string `json:"gidnumber"`
  55. Gecos []string `json:"gecos"`
  56. Sn []string `json:"sn"`
  57. MemberofSudorule []string `json:"memberof_sudorule"`
  58. Krblastpwdchange []struct {
  59. Datetime string `json:"__datetime__"`
  60. } `json:"krblastpwdchange"`
  61. Initials []string `json:"initials"`
  62. } `json:"result"`
  63. Value string `json:"value"`
  64. Summary interface{} `json:"summary"`
  65. } `json:"result"`
  66. Version string `json:"version"`
  67. Error interface{} `json:"error"`
  68. ID int `json:"id"`
  69. Principal string `json:"principal"`
  70. }
  71. // Most of the code is taken from the echo guide
  72. // https://echo.labstack.com/cookbook/jwt
  73. func (h *handler) login(c echo.Context) error {
  74. username := c.FormValue("username")
  75. password := c.FormValue("password")
  76. _url := "https://ipa.sf.faraborddi.dc/ipa/session/login_password"
  77. method := "POST"
  78. params := url.Values{}
  79. params.Add("user", username)
  80. params.Add("password", password)
  81. payload := strings.NewReader(params.Encode())
  82. client := &http.Client{}
  83. req, err := http.NewRequest(method, _url, payload)
  84. if err != nil {
  85. fmt.Println(err)
  86. }
  87. req.Header.Add("Referer", "https://ipa.sf.faraborddi.dc/ipa")
  88. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  89. req.Header.Add("Accept", "text/plain")
  90. res, err := client.Do(req)
  91. cockie := res.Cookies()
  92. defer res.Body.Close()
  93. fmt.Println(res.StatusCode)
  94. if res.StatusCode == 200 {
  95. user := getUserInfo(cockie, username)
  96. fmt.Println(user.Result.Value)
  97. tokens, err := generateTokenPair()
  98. if err != nil {
  99. return err
  100. }
  101. return c.JSON(http.StatusOK, tokens)
  102. }
  103. return echo.ErrUnauthorized
  104. }
  105. func getUserInfo(cockie []*http.Cookie, username string) userInfo {
  106. url := "https://ipa.sf.faraborddi.dc/ipa/session/json"
  107. method := "POST"
  108. _json := fmt.Sprintf(`
  109. {
  110. "method": "user_show",
  111. "params": [
  112. [
  113. "%s"
  114. ],
  115. {
  116. "all": true,
  117. "version": "2.215"
  118. }
  119. ],
  120. "id": 0
  121. }
  122. `, username)
  123. payload := strings.NewReader(_json)
  124. client := &http.Client{}
  125. req, err := http.NewRequest(method, url, payload)
  126. if err != nil {
  127. fmt.Println(err)
  128. }
  129. req.Header.Add("Referer", "https://ipa.sf.faraborddi.dc/ipa")
  130. req.Header.Add("Content-Type", "application/json")
  131. req.Header.Add("Accept", "text/plain")
  132. req.Header.Add("Cookie", cockie[0].Raw)
  133. res, err := client.Do(req)
  134. defer res.Body.Close()
  135. body, err := ioutil.ReadAll(res.Body)
  136. user := userInfo{}
  137. json.Unmarshal(body, &user)
  138. //fmt.Println(user.Result.Value)
  139. return user
  140. }
  141. // This is the api to refresh tokens
  142. // Most of the code is taken from the jwt-go package's sample codes
  143. // https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
  144. func (h *handler) token(c echo.Context) error {
  145. type tokenReqBody struct {
  146. RefreshToken string `json:"refresh_token"`
  147. }
  148. tokenReq := tokenReqBody{}
  149. c.Bind(&tokenReq)
  150. // Parse takes the token string and a function for looking up the key.
  151. // The latter is especially useful if you use multiple keys for your application.
  152. // The standard is to use 'kid' in the head of the token to identify
  153. // which key to use, but the parsed token (head and claims) is provided
  154. // to the callback, providing flexibility.
  155. token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
  156. // Don't forget to validate the alg is what you expect:
  157. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  158. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  159. }
  160. // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
  161. return []byte("secret"), nil
  162. })
  163. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  164. // Get the user record from database or
  165. // run through your business logic to verify if the user can log in
  166. if int(claims["sub"].(float64)) == 1 {
  167. newTokenPair, err := generateTokenPair()
  168. if err != nil {
  169. return err
  170. }
  171. return c.JSON(http.StatusOK, newTokenPair)
  172. }
  173. return echo.ErrUnauthorized
  174. }
  175. return err
  176. }
  177. // Most of the code is taken from the echo guide
  178. // https://echo.labstack.com/cookbook/jwt
  179. func (h *handler) private(c echo.Context) error {
  180. user := c.Get("user").(*jwt.Token)
  181. claims := user.Claims.(jwt.MapClaims)
  182. name := claims["name"].(string)
  183. return c.String(http.StatusOK, "Welcome "+name+"!")
  184. }