Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

255 lines
6.1KB

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