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.

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