You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

178 lines
4.8KB

  1. package main
  2. import (
  3. "biukop/sfm/loan"
  4. "database/sql"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/brianvoe/gofakeit/v6"
  8. log "github.com/sirupsen/logrus"
  9. "net/http"
  10. "net/http/httputil"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. const apiV1Prefix = "/api/v1/"
  16. type apiV1HandlerMap struct {
  17. Method string
  18. Path string //regex
  19. Handler func(http.ResponseWriter, *http.Request, *loan.Session)
  20. }
  21. var apiV1Handler = []apiV1HandlerMap{
  22. {"POST", "login", apiV1Login},
  23. {"GET", "login", apiV1DumpRequest},
  24. }
  25. //apiV1Main version 1 main entry for all REST API
  26. //
  27. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  28. logRequestDebug(httputil.DumpRequest(r, true))
  29. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  30. //track browser, and take session from cookie
  31. session := loan.Session{}
  32. apiV1InitSessionByBrowserId(w, r, &session)
  33. //try session login first, if not an empty session will be created
  34. e := apiV1InitSessionByHttpHeader(r, &session)
  35. if e != nil {
  36. log.Warnf("Fail to InitSession %+v", session)
  37. apiV1Client403Error(w, r)
  38. return
  39. }
  40. session.RenewIfExpireSoon()
  41. session.SetRemote(r) //make sure they are using latest remote
  42. session.Add("mid", apiV1GetMachineId(r)) //set machine id
  43. //we have a session now, either guest or valid user
  44. //search through handler
  45. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  46. for _, node := range apiV1Handler {
  47. if r.Method == node.Method && path == node.Path {
  48. node.Handler(w, r, &session)
  49. e = session.Write() //finish this session to DB
  50. if e != nil {
  51. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  52. }
  53. return
  54. }
  55. }
  56. //Catch for all
  57. e = session.Write() //finish this session to DB
  58. apiV1DumpRequest(w, r, &session)
  59. }
  60. func apiV1GetMachineId(r *http.Request) string {
  61. var mid string
  62. inCookie, e := r.Cookie("mid")
  63. if e == nil {
  64. mid = inCookie.Value
  65. } else {
  66. mid = strconv.Itoa(int(time.Now().Unix())) + "-" + gofakeit.UUID()
  67. }
  68. return mid
  69. }
  70. func apiV1InitSessionByBrowserId(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  71. mid := apiV1GetMachineId(r)
  72. var sid string
  73. inCookie, e := r.Cookie("session")
  74. if e == nil {
  75. sid = inCookie.Value
  76. if sid != "" {
  77. e = session.Read(sid)
  78. if e == nil {
  79. if mid != session.Get("mid") {
  80. session.MarkEmpty()
  81. }
  82. }
  83. } else { //create a new session
  84. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  85. session.Add("mid", mid)
  86. }
  87. }
  88. }
  89. func apiV1AddTrackingCookie(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  90. //add tracking cookie
  91. expiration := time.Now().Add(365 * 24 * time.Hour)
  92. cookie := http.Cookie{Name: "session", Value: session.Id, Expires: expiration}
  93. http.SetCookie(w, &cookie)
  94. mid := apiV1GetMachineId(r)
  95. cookie = http.Cookie{Name: "mid", Value: mid, Expires: expiration}
  96. http.SetCookie(w, &cookie)
  97. }
  98. func apiV1InitSessionByHttpHeader(r *http.Request, ss *loan.Session) (e error) {
  99. sid := r.Header.Get("Biukop-Session")
  100. //make sure session id is given
  101. if sid != "" {
  102. //Try to retrieve a copy of DB session
  103. trial := loan.Session{}
  104. e = trial.Retrieve(r)
  105. if e == nil { //we got existing session from DB
  106. e = trial.ValidateRequest(r)
  107. if e != nil { // db session does not match request
  108. log.Warnf("failed session login %+v, %s", ss, time.Now().Format(time.RFC1123))
  109. ss.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  110. e = nil
  111. } else { //else, we have logged this user
  112. *ss = trial //overwrite the incoming session
  113. }
  114. } else if e == sql.ErrNoRows { //db does not have required session.
  115. log.Warn("DB has no corresponding session ", sid)
  116. } else { // retrieve has error
  117. log.Warnf("Retrieve Session %s encountered error %s", sid, e.Error())
  118. }
  119. }
  120. //if there is not session incoming
  121. if ss.IsEmpty() { //cookie may have initialized a session
  122. ss.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  123. e = nil //we try to init an empty one
  124. }
  125. return
  126. }
  127. func apiV1ErrorCheck(e error) {
  128. if nil != e {
  129. panic(e.Error()) //TODO: detailed error check, truck all caller
  130. }
  131. }
  132. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  133. w.WriteHeader(500)
  134. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  135. //write log
  136. dump := logRequestDebug(httputil.DumpRequest(r, true))
  137. dump = strings.TrimSpace(dump)
  138. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  139. }
  140. func apiV1Client403Error(w http.ResponseWriter, r *http.Request) {
  141. w.WriteHeader(403)
  142. type struct403 struct {
  143. Error int
  144. ErrorMsg string
  145. }
  146. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  147. msg403, _ := json.Marshal(e403)
  148. fmt.Fprintln(w, string(msg403))
  149. //write log
  150. dump := logRequestDebug(httputil.DumpRequest(r, true))
  151. dump = strings.TrimSpace(dump)
  152. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  153. }