Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

261 line
7.3KB

  1. package main
  2. import (
  3. "biukop.com/sfm/loan"
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/brianvoe/gofakeit/v6"
  9. log "github.com/sirupsen/logrus"
  10. "net/http"
  11. "net/http/httputil"
  12. "strings"
  13. "time"
  14. )
  15. const apiV1Prefix = "/api/v1/"
  16. const apiV1WebSocket = apiV1Prefix + "ws"
  17. type apiV1HandlerMap struct {
  18. Method string
  19. Path string //regex
  20. Handler func(http.ResponseWriter, *http.Request, *loan.Session)
  21. }
  22. var apiV1Handler = setupApiV1Handler()
  23. func setupApiV1Handler() []apiV1HandlerMap {
  24. if config.Debug { //debug only
  25. return []apiV1HandlerMap{
  26. {"POST", "login", apiV1Login},
  27. {"*", "logout", apiV1Logout},
  28. {"GET", "chart/type-of-loans", apiV1ChartTypeOfLoans},
  29. {"GET", "chart/amount-of-loans", apiV1ChartTypeOfLoans},
  30. {"GET", "login", apiV1DumpRequest},
  31. }
  32. } else { //production
  33. return []apiV1HandlerMap{
  34. {"POST", "login", apiV1Login},
  35. {"*", "logout", apiV1Logout},
  36. {"GET", "chart/type-of-loans", apiV1ChartTypeOfLoans},
  37. {"GET", "chart/amount-of-loans", apiV1ChartTypeOfLoans},
  38. {"GET", "login", apiV1EmptyResponse},
  39. }
  40. }
  41. }
  42. //
  43. //apiV1Main version 1 main entry for all REST API
  44. //
  45. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  46. //general setup
  47. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  48. //CORS setup
  49. setupCrossOriginResponse(&w, r)
  50. //if its options then we don't bother with other issues
  51. if r.Method == "OPTIONS" {
  52. apiV1EmptyResponse(w, r, nil)
  53. return //stop processing
  54. }
  55. if config.Debug {
  56. logRequestDebug(httputil.DumpRequest(r, true))
  57. }
  58. session := apiV1InitSession(r)
  59. if config.Debug {
  60. log.Debugf("session : %+v", session)
  61. }
  62. //search through handler
  63. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  64. for _, node := range apiV1Handler {
  65. if (r.Method == node.Method || node.Method == "*") && path == node.Path {
  66. node.Handler(w, r, &session)
  67. e := session.Write() //finish this session to DB
  68. if e != nil {
  69. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  70. }
  71. return
  72. }
  73. }
  74. //Catch for all Uhandled Request
  75. e := session.Write() //finish this session to DB
  76. if e != nil {
  77. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  78. }
  79. if config.Debug {
  80. apiV1DumpRequest(w, r, &session)
  81. } else {
  82. apiV1EmptyResponse(w, r, &session)
  83. }
  84. }
  85. func apiV1InitSession(r *http.Request) (session loan.Session) {
  86. session.MarkEmpty()
  87. //track browser, and take session from cookie
  88. cookieSession, e := apiV1InitSessionByBrowserId(r)
  89. if e == nil {
  90. session = cookieSession
  91. }
  92. //try session login first, if not an empty session will be created
  93. headerSession, e := apiV1InitSessionByHttpHeader(r)
  94. if e == nil {
  95. session = headerSession
  96. }
  97. if session.IsEmpty() {
  98. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  99. } else {
  100. session.RenewIfExpireSoon()
  101. }
  102. //we have a session anyway
  103. session.Add("Biukop-Mid", apiV1GetMachineId(r)) //set machine id
  104. session.SetRemote(r) //make sure they are using latest remote
  105. return
  106. }
  107. func setupCrossOriginResponse(w *http.ResponseWriter, r *http.Request) {
  108. origin := r.Header.Get("Origin")
  109. if origin == "" {
  110. origin = "*"
  111. }
  112. requestedHeaders := r.Header.Get("Access-control-Request-Headers")
  113. method := r.Header.Get("Access-Control-Request-Method")
  114. (*w).Header().Set("Access-Control-Allow-Origin", origin) //for that specific origin
  115. (*w).Header().Set("Access-Control-Allow-Credentials", "true")
  116. (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, "+method)
  117. (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Cookie, Biukop-Session, Biukop-Session-Token, Biukop-Session-Expire, "+requestedHeaders)
  118. }
  119. func apiV1GetMachineId(r *http.Request) string {
  120. var mid string
  121. inCookie, e := r.Cookie("Biukop-Mid")
  122. if e == nil {
  123. mid = inCookie.Value
  124. } else {
  125. mid = gofakeit.UUID()
  126. }
  127. headerMid := r.Header.Get("Biukop-Mid")
  128. if headerMid != "" {
  129. mid = headerMid
  130. }
  131. return mid
  132. }
  133. func apiV1InitSessionByBrowserId(r *http.Request) (session loan.Session, e error) {
  134. var sid string
  135. mid := apiV1GetMachineId(r)
  136. inCookie, e := r.Cookie("Biukop-Session")
  137. if e == nil {
  138. sid = inCookie.Value
  139. if sid != "" {
  140. e = session.Read(sid)
  141. if e == nil {
  142. if mid != session.Get("Biukop-Mid") {
  143. session.MarkEmpty()
  144. }
  145. }
  146. }
  147. }
  148. return
  149. }
  150. func apiV1AddTrackingCookie(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  151. //add tracking cookie
  152. expiration := time.Now().Add(365 * 24 * time.Hour)
  153. mid := apiV1GetMachineId(r)
  154. cookie := http.Cookie{Name: "Biukop-Mid", Value: mid, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  155. http.SetCookie(w, &cookie)
  156. if session != nil {
  157. cookie = http.Cookie{Name: "Biukop-Session", Value: session.Id, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  158. http.SetCookie(w, &cookie)
  159. }
  160. }
  161. func apiV1InitSessionByHttpHeader(r *http.Request) (ss loan.Session, e error) {
  162. sid := r.Header.Get("Biukop-Session")
  163. ss.MarkEmpty()
  164. //make sure session id is given
  165. if sid != "" {
  166. e = ss.Retrieve(r)
  167. if e == sql.ErrNoRows { //db does not have required session.
  168. log.Warn("DB has no corresponding session ", sid)
  169. } else if e != nil { // retrieve DB has error
  170. log.Errorf("Retrieve Session %s encountered error %s", sid, e.Error())
  171. }
  172. } else {
  173. e = errors.New("session not found: " + sid)
  174. }
  175. return
  176. }
  177. func apiV1ErrorCheck(e error) {
  178. if nil != e {
  179. panic(e.Error()) //TODO: detailed error check, truck all caller
  180. }
  181. }
  182. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  183. w.WriteHeader(500)
  184. apiV1AddTrackingCookie(w, r, nil) //always the last one to set cookies
  185. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  186. //write log
  187. dump := logRequestDebug(httputil.DumpRequest(r, true))
  188. dump = strings.TrimSpace(dump)
  189. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  190. }
  191. func apiV1Client403Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  192. w.WriteHeader(403)
  193. type struct403 struct {
  194. Error int
  195. ErrorMsg string
  196. }
  197. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  198. msg403, _ := json.Marshal(e403)
  199. //before send out
  200. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  201. fmt.Fprintln(w, string(msg403))
  202. //write log
  203. dump := logRequestDebug(httputil.DumpRequest(r, true))
  204. dump = strings.TrimSpace(dump)
  205. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  206. }
  207. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  208. dump := logRequestDebug(httputil.DumpRequest(r, true))
  209. dump = strings.TrimSpace(dump)
  210. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  211. dumpLines := strings.Split(dump, "\r\n")
  212. ar := apiV1ResponseBlank()
  213. ar.Env.Msg = msg
  214. ar.Env.Session = *ss
  215. ar.Env.Session.Bin = []byte("masked data") //clear
  216. ar.Env.Session.Secret = "***********"
  217. ar.add("Body", dumpLines)
  218. ar.add("Biukop-Mid", ss.Get("Biukop-Mid"))
  219. b, _ := ar.toJson()
  220. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  221. fmt.Fprintf(w, "%s\n", b)
  222. }
  223. func apiV1EmptyResponse(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  224. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  225. fmt.Fprintf(w, "")
  226. }