helpers.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package login
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "net/url"
  10. "reflect"
  11. "strings"
  12. )
  13. func underlyingReflectType(t reflect.Type) reflect.Type {
  14. if t.Kind() == reflect.Ptr {
  15. return underlyingReflectType(t.Elem())
  16. }
  17. return t
  18. }
  19. func genHashSalt() string {
  20. b := make([]byte, 16)
  21. rand.Read(b)
  22. return hex.EncodeToString(b)
  23. }
  24. func MustSetQuery(u string, keyVals ...string) string {
  25. pu, err := url.Parse(u)
  26. if err != nil {
  27. panic(err)
  28. }
  29. if len(keyVals)%2 != 0 {
  30. panic("invalid keyVals")
  31. }
  32. q := pu.Query()
  33. for i := 0; i < len(keyVals); i += 2 {
  34. q.Set(keyVals[i], keyVals[i+1])
  35. }
  36. pu.RawQuery = ""
  37. return fmt.Sprintf("%s?%s", pu.String(), q.Encode())
  38. }
  39. func recaptchaTokenCheck(b *Builder, token string) bool {
  40. f := make(url.Values)
  41. f.Add("secret", b.recaptchaConfig.SecretKey)
  42. f.Add("response", token)
  43. res, err := http.Post("https://www.google.com/recaptcha/api/siteverify",
  44. "application/x-www-form-urlencoded", strings.NewReader(f.Encode()))
  45. if err != nil {
  46. log.Println(err)
  47. return false
  48. }
  49. defer res.Body.Close()
  50. var r struct {
  51. Success bool `json:"success"`
  52. }
  53. if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
  54. log.Println(err)
  55. return false
  56. }
  57. return r.Success
  58. }
  59. func setCookieForRequest(r *http.Request, c *http.Cookie) {
  60. oldCookies := r.Cookies()
  61. r.Header.Del("Cookie")
  62. for _, oc := range oldCookies {
  63. if oc.Name == c.Name {
  64. continue
  65. }
  66. r.AddCookie(oc)
  67. }
  68. r.AddCookie(c)
  69. }