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

272 lines
7.9KB

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