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.

170 lines
4.5KB

  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. //we have a session now, either guest or valid user
  43. //search through handler
  44. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  45. for _, node := range apiV1Handler {
  46. if r.Method == node.Method && path == node.Path {
  47. node.Handler(w, r, &session)
  48. e = session.Write() //finish this session to DB
  49. if e != nil {
  50. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  51. }
  52. return
  53. }
  54. }
  55. //Catch for all
  56. e = session.Write() //finish this session to DB
  57. apiV1DumpRequest(w, r, &session)
  58. }
  59. func apiV1InitSessionByBrowserId(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  60. var mid string
  61. inCookie, e := r.Cookie("mid")
  62. if e == nil {
  63. mid = inCookie.Value
  64. } else {
  65. mid = strconv.Itoa(int(time.Now().Unix())) + "-" + gofakeit.UUID()
  66. }
  67. var sid string
  68. inCookie, e = r.Cookie("session")
  69. if e == nil {
  70. sid = inCookie.Value
  71. if sid != "" {
  72. e = session.Read(sid)
  73. if e == nil {
  74. if mid != session.Get("mid") {
  75. session.MarkEmpty()
  76. }
  77. }
  78. } else { //create a new session
  79. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  80. session.Add("mid", mid)
  81. }
  82. }
  83. //add tracking cookie
  84. expiration := time.Now().Add(365 * 24 * time.Hour)
  85. cookie := http.Cookie{Name: "session", Value: session.Id, Expires: expiration}
  86. http.SetCookie(w, &cookie)
  87. cookie = http.Cookie{Name: "mid", Value: mid, Expires: expiration}
  88. http.SetCookie(w, &cookie)
  89. }
  90. func apiV1InitSessionByHttpHeader(r *http.Request, ss *loan.Session) (e error) {
  91. sid := r.Header.Get("Biukop-Session")
  92. //make sure session id is given
  93. if sid != "" {
  94. //Try to retrieve a copy of DB session
  95. trial := loan.Session{}
  96. e = trial.Retrieve(r)
  97. if e == nil { //we got existing session from DB
  98. e = trial.ValidateRequest(r)
  99. if e != nil { // db session does not match request
  100. log.Warnf("failed session login %+v, %s", ss, time.Now().Format(time.RFC1123))
  101. ss.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  102. e = nil
  103. } else { //else, we have logged this user
  104. *ss = trial //overwrite the incoming session
  105. }
  106. } else if e == sql.ErrNoRows { //db does not have required session.
  107. log.Warn("DB has no corresponding session ", sid)
  108. } else { // retrieve has error
  109. log.Warnf("Retrieve Session %s encountered error %s", sid, e.Error())
  110. }
  111. }
  112. //if there is not session incoming
  113. if ss.IsEmpty() { //cookie may have initialized a session
  114. ss.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  115. e = nil //we try to init an empty one
  116. }
  117. return
  118. }
  119. func apiV1ErrorCheck(e error) {
  120. if nil != e {
  121. panic(e.Error()) //TODO: detailed error check, truck all caller
  122. }
  123. }
  124. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  125. w.WriteHeader(500)
  126. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  127. //write log
  128. dump := logRequestDebug(httputil.DumpRequest(r, true))
  129. dump = strings.TrimSpace(dump)
  130. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  131. }
  132. func apiV1Client403Error(w http.ResponseWriter, r *http.Request) {
  133. w.WriteHeader(403)
  134. type struct403 struct {
  135. Error int
  136. ErrorMsg string
  137. }
  138. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  139. msg403, _ := json.Marshal(e403)
  140. fmt.Fprintln(w, string(msg403))
  141. //write log
  142. dump := logRequestDebug(httputil.DumpRequest(r, true))
  143. dump = strings.TrimSpace(dump)
  144. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  145. }