Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

260 Zeilen
6.3KB

  1. package main
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "math/rand"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. var cookLeadID = "biukop_cl"
  16. func crmpixelImage() (pixel []byte, err error) {
  17. b64pixel := "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QcIBzEJ3JY/6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAADUlEQVQI12NgYGBgAAAABQABXvMqOgAAAABJRU5ErkJggg=="
  18. pixel, err = base64.StdEncoding.DecodeString(b64pixel)
  19. return
  20. }
  21. func crmpixel(w http.ResponseWriter, r *http.Request) {
  22. cookie := crmpixelCookie(r)
  23. http.SetCookie(w, &cookie)
  24. //send out pixel 1x1 transparent png file
  25. pixel, err := crmpixelImage()
  26. if err == nil {
  27. w.Write(pixel)
  28. } else {
  29. fmt.Fprint(w, "decodig pixel image wrong")
  30. }
  31. }
  32. func crmpixelCookie(r *http.Request) (ret http.Cookie) {
  33. cookie, leadok := r.Cookie(cookLeadID) //crm lead
  34. if leadok != nil {
  35. ret, _ = createNewCookie(r)
  36. return
  37. }
  38. valid := isValidCookieBiukopCL(cookie.Value)
  39. if !valid {
  40. ret, _ = createNewCookie(r)
  41. return
  42. }
  43. //refresh expiration
  44. ret = *cookie
  45. ret.Expires = time.Now().Add(10 * 365 * 24 * time.Hour)
  46. return
  47. }
  48. func getLeadIDFromCookie(r *http.Request) (leadID string, ok bool) {
  49. return cookieVerifyAndGet(r, cookLeadID)
  50. }
  51. func cookieVerifyAndGet(r *http.Request, name string) (value string, ok bool) {
  52. ok = false
  53. cookie, leadok := r.Cookie(name)
  54. if leadok != nil {
  55. return
  56. }
  57. valid := isValidCookieBiukopCL(cookie.Value)
  58. if !valid {
  59. return
  60. }
  61. //correctly split string
  62. s := strings.Split(cookie.Value, "|")
  63. if len(s) != 4 || s[0] == "" {
  64. return
  65. }
  66. ok = true
  67. value = s[0]
  68. return
  69. }
  70. func createNewCookie(r *http.Request) (ret http.Cookie, info crmdLead) {
  71. info = crmCreateNewAnonymousLeadByHTTPRequest(r)
  72. ret = cookieFromLeadID(info.ID)
  73. return
  74. }
  75. func cookieFromLeadID(leadID string) (ret http.Cookie) {
  76. return cookieCreateLongTerm(cookLeadID, leadID)
  77. }
  78. func cookieCreateLongTerm(name, value string) (ret http.Cookie) {
  79. expiration := time.Now().Add(10 * 365 * 24 * time.Hour)
  80. signedValue := cookieSignValue(value)
  81. ret = http.Cookie{Name: name, Value: signedValue, Expires: expiration}
  82. return
  83. }
  84. func cookieCreate(name, value string, expireInSeconds int) (ret http.Cookie) {
  85. expiration := time.Now().Add(time.Duration(expireInSeconds) * time.Second)
  86. signedValue := cookieSignValue(value)
  87. ret = http.Cookie{Name: name, Value: signedValue, Expires: expiration}
  88. return
  89. }
  90. func crmCreateNewAnonymousLeadByHTTPRequest(r *http.Request) (info crmdLead) {
  91. info.FirstName = "Anonymous"
  92. info.LastName = "User " + r.RemoteAddr
  93. info.Password = "Password"
  94. info.Status = "Anonymous"
  95. info.Description = "Anonymous user from " + r.RemoteAddr
  96. info.ForceDuplicate = true
  97. b, err := json.Marshal(info)
  98. if err != nil {
  99. return
  100. }
  101. entity, err := crmCreateEntity("Lead", b)
  102. if err == nil || isErrIndicateDuplicate(err) {
  103. info, _ = entity.(crmdLead)
  104. }
  105. return
  106. }
  107. func isValidCookieBiukopCL(cookieValue string) (valid bool) {
  108. valid = false
  109. //correctly split string
  110. s := strings.Split(cookieValue, "|")
  111. if len(s) != 4 || s[0] == "" {
  112. return
  113. }
  114. id, nonce, timestamp, signature := s[0], s[1], s[2], s[3]
  115. //check signature
  116. combined := id + nonce
  117. expected := calculateSignature(timestamp, combined, IntraAPIConfig.CRMSecrete)
  118. if expected != signature {
  119. return
  120. }
  121. ts, err := strconv.Atoi(timestamp)
  122. if err != nil {
  123. return
  124. }
  125. if timestampOldThan(int32(ts), 86400) { //older than 1 day
  126. //find lead data
  127. _, err := crmpixelLead(id)
  128. if err != nil {
  129. return
  130. }
  131. }
  132. valid = true
  133. return
  134. }
  135. func buildBiukopCLsignature(id, nonce string) (timestamp, signature string) {
  136. combined := id + nonce
  137. timestamp = fmt.Sprintf("%d", time.Now().Unix())
  138. signature = calculateSignature(timestamp, combined, IntraAPIConfig.CRMSecrete)
  139. return
  140. }
  141. func cookieSignValue(id string) (ret string) {
  142. rand.Seed(time.Now().Unix())
  143. nonce := fmt.Sprintf("%d", rand.Intn(655352017))
  144. timestamp, signature := buildBiukopCLsignature(id, nonce)
  145. strs := []string{id, nonce, timestamp, signature} //order is very important
  146. ret = strings.Join(strs, "|")
  147. return
  148. }
  149. func crmpixelLead(id string) (info crmdLead, err error) {
  150. entity, err := crmGetEntity("Lead", id)
  151. if err != nil {
  152. return
  153. }
  154. info, ok := entity.(crmdLead)
  155. if !ok {
  156. err = errors.New("search lead, return a bad entity type")
  157. }
  158. return
  159. }
  160. //for user's initial registration, especially for wechat users
  161. //they visit a url that is specifically designed for them to
  162. //auth and input their profile data.
  163. //the url's query string will contains a token and a signature
  164. //so that it's verified, by single get request, to allow people to
  165. //enter their details into the CRM system.
  166. //
  167. //this handler, check's the query sting ,set an auth cookie to the client
  168. //and serve angular app, through an URL "/profile/edit"
  169. //or if the user has already been registered,
  170. //redirect user to a URL "/pages/dashboard"
  171. //
  172. func setTrackingCookieAndRecirect(w http.ResponseWriter, r *http.Request) {
  173. m, err := url.ParseQuery(r.URL.RawQuery)
  174. if err != nil {
  175. response400Handler(w)
  176. return
  177. }
  178. url, ok := m["url"]
  179. if !ok {
  180. response400Handler(w)
  181. return
  182. }
  183. //check request leadID - lid and my cookie lead id
  184. leadID, ok := m["lid"]
  185. myLeadID, found := getLeadIDFromCookie(r) //existing cookie
  186. expireInSeconds := 120 //default 2minute
  187. if found && ok && myLeadID == leadID[0] { //our cookie match the request lid
  188. expireInSeconds = 86400 //extended to 1 day
  189. }
  190. //check signature, prevent unauthorized request
  191. if !checkSignatureByTokenWithExpireSeconds(r, IntraAPIConfig.CRMSecrete, expireInSeconds) {
  192. response403Handler(w)
  193. return
  194. }
  195. //set cookie if any
  196. if ok {
  197. log.Println("setlead cookie :" + leadID[0])
  198. cookie := cookieFromLeadID(leadID[0])
  199. http.SetCookie(w, &cookie)
  200. } else {
  201. cookie := crmpixelCookie(r)
  202. http.SetCookie(w, &cookie)
  203. }
  204. //get expire settings if any
  205. expire := 7200 //2 hours
  206. expireTime, ok := m["expire"]
  207. if ok {
  208. expire, _ = strconv.Atoi(expireTime[0])
  209. }
  210. //set all cookie from url
  211. for k, v := range m {
  212. if k == "lid" || k == "url" || k == "expire" || k == "nonce" || k == "signature" || k == "timestamp" { //skip lead id and URL and expire
  213. continue
  214. }
  215. log.Printf("set cookie %s=%s", k, v)
  216. cookie := cookieCreate(k, v[0], expire)
  217. http.SetCookie(w, &cookie)
  218. }
  219. //perform redirect
  220. http.Redirect(w, r, url[0], 307) //302 temp redirect
  221. return
  222. }