Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

554 lignes
17KB

  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", apiV1ChartAmountOfLoans},
  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. {"POST", "grid/loan/full-loan-overview", apiV1GridListLoanOverview},
  35. {"GET", "chart/reward-vs-income-monthly", apiV1ChartRewardVsIncomeMonthly},
  36. {"GET", "loan/", apiV1LoanSingleGet},
  37. {"DELETE", "loan/", apiV1LoanSingleDelete},
  38. {"GET", "loan-by-client/", apiV1LoanByClient},
  39. {"GET", "people/", apiV1PeopleGet},
  40. {"POST", "people/", apiV1PeoplePost},
  41. {"PUT", "people/", apiV1PeoplePut},
  42. {"DELETE", "people/", apiV1PeopleDelete},
  43. {"GET", "people-extra/", apiV1PeopleExtraGet},
  44. {"POST", "user/", apiV1UserPost},
  45. {"PUT", "user/", apiV1UserPut},
  46. {"DELETE", "user/", apiV1UserDelete},
  47. {"POST", "user-enable/", apiV1UserEnable},
  48. {"GET", "user-ex/", apiV1UserExGet},
  49. {"POST", "user-ex/", apiV1UserExPost},
  50. {"GET", "user-ex-list/", apiV1UserExList},
  51. {"GET", "broker/", apiV1BrokerGet},
  52. {"POST", "broker/", apiV1BrokerPost},
  53. {"PUT", "broker/", apiV1BrokerPut},
  54. {"DELETE", "broker/", apiV1BrokerDelete},
  55. {"POST", "change-pass/", apiV1ChangePass},
  56. {"POST", "loan/basic/", apiV1LoanSinglePostBasic},
  57. {"GET", "avatar/", apiV1Avatar},
  58. {"POST", "avatar/", apiV1AvatarPost},
  59. {"POST", "reward/", apiV1RewardPost},
  60. {"DELETE", "reward/", apiV1RewardDelete},
  61. {"GET", "people-list/", apiV1PeopleList},
  62. {"GET", "broker-list/", apiV1BrokerList},
  63. {"POST", "sync-people/", apiV1SyncPeople},
  64. {"POST", "payIn/", apiV1PayInPost},
  65. {"DELETE", "payIn/", apiV1PayInDelete},
  66. {"POST", "pay-in-list/", apiV1PayInList},
  67. {"POST", "pay-in-filtered-list/", apiV1FilteredPayInList},
  68. {"GET", "user-reward/", apiV1UserReward},
  69. {"GET", "login-available/", apiV1LoginAvailable},
  70. {"POST", "lender-upload/", apiV1UploadsPost},
  71. {"GET", "upload-analysis/", apiV1UploadAnalysis},
  72. {"PUT", "upload-analysis/", apiV1UploadCreateAnalysis},
  73. {"GET", "upload-as-image/", apiV1UploadAsImage},
  74. {"PUT", "upload-as-image/", apiV1UploadCreateImage},
  75. {"GET", "upload-as-thumbnail/", apiV1UploadAsThumbnail},
  76. {"PUT", "upload-as-thumbnail/", apiV1UploadCreateThumbnail},
  77. {"GET", "upload-as-pdf/", apiV1UploadAsPDF},
  78. {"PUT", "upload-as-pdf/", apiV1UploadCreatePDF},
  79. {"GET", "upload-original/", apiV1UploadOriginalFileGet},
  80. {"GET", "upload/", apiV1UploadMetaGet},
  81. {"DELETE", "upload/", apiV1UploadDelete},
  82. {"POST", "upload-meta-list/", apiV1UploadMetaList},
  83. {"GET", "lender-list/", apiV1LenderList},
  84. {"GET", "payout-ex/", apiV1PayOutExGet},
  85. {"POST", "reward-ex-list/", apiV1RewardExListPost},
  86. {"POST", "payout/", apiV1PayOutPost},
  87. {"POST", "payout-prepared/", apiV1PayOutPrepared},
  88. {"POST", "payout-unprepared/", apiV1PayOutUnprepared},
  89. {"POST", "payout-approved/", apiV1PayOutApproved},
  90. {"POST", "payout-unapproved/", apiV1PayOutUnapproved},
  91. {"POST", "payout-paid/", apiV1PayOutPaid},
  92. {"POST", "payout-unpaid/", apiV1PayOutUnpaid},
  93. {"GET", "login", apiV1DumpRequest},
  94. }
  95. } else { //production
  96. return []apiV1HandlerMap{
  97. {"POST", "login", apiV1Login},
  98. {"*", "logout", apiV1Logout},
  99. {"GET", "chart/type-of-loans", apiV1ChartTypeOfLoans},
  100. {"GET", "chart/amount-of-loans", apiV1ChartAmountOfLoans},
  101. {"GET", "chart/past-year-monthly", apiV1ChartPastYearMonthly},
  102. {"GET", "chart/recent-10-loans", apiV1ChartRecent10Loans},
  103. {"GET", "chart/top-broker", apiV1ChartTopBroker},
  104. //{"POST", "grid/loan/full-loan-overview", apiV1GridLoanFullOverview},
  105. {"POST", "grid/loan/full-loan-overview", apiV1GridListLoanOverview},
  106. {"GET", "chart/reward-vs-income-monthly", apiV1ChartRewardVsIncomeMonthly},
  107. {"GET", "loan/", apiV1LoanSingleGet},
  108. {"DELETE", "loan/", apiV1LoanSingleDelete},
  109. {"GET", "loan-by-client/", apiV1LoanByClient},
  110. {"GET", "people/", apiV1PeopleGet},
  111. {"POST", "people/", apiV1PeoplePost},
  112. {"PUT", "people/", apiV1PeoplePut},
  113. {"DELETE", "people/", apiV1PeopleDelete},
  114. {"GET", "people-extra/", apiV1PeopleExtraGet},
  115. {"POST", "user/", apiV1UserPost},
  116. {"PUT", "user/", apiV1UserPut},
  117. {"DELETE", "user/", apiV1UserDelete},
  118. {"POST", "user-enable/", apiV1UserEnable},
  119. {"GET", "user-ex/", apiV1UserExGet},
  120. {"POST", "user-ex/", apiV1UserExPost},
  121. {"GET", "user-ex-list/", apiV1UserExList},
  122. {"GET", "broker/", apiV1BrokerGet},
  123. {"POST", "broker/", apiV1BrokerPost},
  124. {"PUT", "broker/", apiV1BrokerPut},
  125. {"DELETE", "broker/", apiV1BrokerDelete},
  126. {"POST", "change-pass/", apiV1ChangePass},
  127. {"POST", "loan/basic/", apiV1LoanSinglePostBasic},
  128. {"GET", "avatar/", apiV1Avatar},
  129. {"POST", "avatar/", apiV1AvatarPost},
  130. {"POST", "reward/", apiV1RewardPost},
  131. {"DELETE", "reward/", apiV1RewardDelete},
  132. {"GET", "people-list", apiV1PeopleList},
  133. {"GET", "broker-list/", apiV1BrokerList},
  134. {"POST", "sync-people/", apiV1SyncPeople},
  135. {"POST", "payIn/", apiV1PayInPost},
  136. {"DELETE", "payIn/", apiV1PayInDelete},
  137. {"POST", "pay-in-list/", apiV1PayInList},
  138. {"POST", "pay-in-filtered-list/", apiV1FilteredPayInList},
  139. {"GET", "user-reward/", apiV1UserReward},
  140. {"GET", "login-available/", apiV1LoginAvailable},
  141. {"POST", "lender-upload/", apiV1UploadsPost},
  142. {"GET", "upload-analysis/", apiV1UploadAnalysis},
  143. {"PUT", "upload-analysis/", apiV1UploadCreateAnalysis},
  144. {"GET", "upload-as-image/", apiV1UploadAsImage},
  145. {"PUT", "upload-as-image/", apiV1UploadCreateImage},
  146. {"GET", "upload-as-thumbnail/", apiV1UploadAsThumbnail},
  147. {"PUT", "upload-as-thumbnail/", apiV1UploadCreateThumbnail},
  148. {"GET", "upload-as-pdf/", apiV1UploadAsPDF},
  149. {"PUT", "upload-as-pdf/", apiV1UploadCreatePDF},
  150. {"GET", "upload-original/", apiV1UploadOriginalFileGet},
  151. {"GET", "upload-meta/", apiV1UploadMetaGet},
  152. {"DELETE", "upload/", apiV1UploadDelete},
  153. {"POST", "upload-meta-list/", apiV1UploadMetaList},
  154. {"GET", "lender-list/", apiV1LenderList},
  155. {"GET", "payout-ex/", apiV1PayOutExGet},
  156. {"POST", "reward-ex-list/", apiV1RewardExListPost},
  157. {"POST", "payout/", apiV1PayOutPost},
  158. {"POST", "payout-prepared/", apiV1PayOutPrepared},
  159. {"POST", "payout-unprepared/", apiV1PayOutUnprepared},
  160. {"POST", "payout-approved/", apiV1PayOutApproved},
  161. {"POST", "payout-unapproved/", apiV1PayOutUnapproved},
  162. {"POST", "payout-paid/", apiV1PayOutPaid},
  163. {"POST", "payout-unpaid/", apiV1PayOutUnpaid},
  164. {"GET", "login", apiV1EmptyResponse},
  165. }
  166. }
  167. }
  168. //
  169. //apiV1Main version 1 main entry for all REST API
  170. //
  171. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  172. //CORS setup
  173. setupCrossOriginResponse(&w, r)
  174. //if its options then we don't bother with other issues
  175. if r.Method == "OPTIONS" {
  176. apiV1EmptyResponse(w, r, nil)
  177. return //stop processing
  178. }
  179. if config.Debug {
  180. logRequestDebug(httputil.DumpRequest(r, true))
  181. }
  182. session := loan.Session{}
  183. session.MarkEmpty()
  184. bypassSession := apiV1NoNeedSession(r)
  185. if !bypassSession { // no point to create session for preflight
  186. session = apiV1InitSession(r)
  187. if config.Debug {
  188. log.Debugf("session : %+v", session)
  189. }
  190. }
  191. //search through handler
  192. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  193. handled := false
  194. for _, node := range apiV1Handler {
  195. if (strings.ToUpper(r.Method) == node.Method || node.Method == "*") && strings.HasPrefix(path, node.Path) {
  196. handled = true
  197. node.Handler(w, r, &session)
  198. break //stop search handler further
  199. }
  200. }
  201. if !bypassSession { // no point to write session for preflight
  202. e := session.Write() //finish this session to DB
  203. if e != nil {
  204. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  205. }
  206. }
  207. //Catch for all UnHandled Request
  208. if !handled {
  209. if config.Debug {
  210. apiV1DumpRequest(w, r, &session)
  211. } else {
  212. apiV1EmptyResponse(w, r, &session)
  213. }
  214. }
  215. }
  216. func apiV1NoNeedSession(r *http.Request) bool {
  217. if r.Method == "OPTIONS" {
  218. return true
  219. }
  220. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  221. if r.Method == "GET" {
  222. if strings.HasPrefix(path, "avatar/") ||
  223. strings.HasPrefix(path, "upload-original/") ||
  224. strings.HasPrefix(path, "upload-as-image/") ||
  225. strings.HasPrefix(path, "upload-as-analysis/") ||
  226. strings.HasPrefix(path, "upload-as-thumbnail/") ||
  227. strings.HasPrefix(path, "upload-as-pdf/") {
  228. return true
  229. }
  230. }
  231. return false
  232. }
  233. func apiV1InitSession(r *http.Request) (session loan.Session) {
  234. session.MarkEmpty()
  235. //try session login first, if not an empty session will be created
  236. headerSession, e := apiV1InitSessionByHttpHeader(r)
  237. if e == nil {
  238. session = headerSession
  239. } else { // if session from header failed, we try cookie session
  240. // track browser, and take session from cookie
  241. // cookie has disadvantage that multiple tab will get overwritten
  242. cookieSession, e := apiV1InitSessionByCookie(r)
  243. if e == nil {
  244. session = cookieSession
  245. }
  246. }
  247. if session.IsEmpty() {
  248. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  249. } else {
  250. session.RenewIfExpireSoon()
  251. }
  252. //we have a session anyway
  253. session.Add("Biukop-Mid", apiV1GetMachineId(r)) //set machine id
  254. session.Add("Biukop-Socket", apiV1GetSocketId(r)) //set machine id
  255. session.SetRemote(r) //make sure they are using latest remote
  256. return
  257. }
  258. func setupCrossOriginResponse(w *http.ResponseWriter, r *http.Request) {
  259. origin := r.Header.Get("Origin")
  260. if origin == "" {
  261. origin = "*"
  262. }
  263. requestedHeaders := r.Header.Get("Access-control-Request-Headers")
  264. method := r.Header.Get("Access-Control-Request-Method")
  265. (*w).Header().Set("Access-Control-Allow-Origin", origin) //for that specific origin
  266. (*w).Header().Set("Access-Control-Allow-Credentials", "true")
  267. (*w).Header().Set("Access-Control-Allow-Methods", removeDupHeaderOptions("POST, GET, OPTIONS, PUT, DELETE, "+method))
  268. (*w).Header().Set("Access-Control-Allow-Headers", removeDupHeaderOptions("Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Cookie, Biukop-Session, Biukop-Socket , "+requestedHeaders))
  269. }
  270. func apiV1GetMachineId(r *http.Request) string {
  271. var mid string
  272. inCookie, e := r.Cookie("Biukop-Mid")
  273. if e == nil {
  274. mid = inCookie.Value
  275. } else {
  276. mid = gofakeit.UUID()
  277. }
  278. headerMid := r.Header.Get("Biukop-Mid")
  279. if headerMid != "" {
  280. mid = headerMid
  281. }
  282. return mid
  283. }
  284. func apiV1GetSocketId(r *http.Request) string {
  285. socketId := r.Header.Get("Biukop-Socket")
  286. return socketId
  287. }
  288. func apiV1GetCORSHeaders(r *http.Request) (ret string) {
  289. requestedHeaders := r.Header.Get("Access-control-Request-Headers")
  290. ret = "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Cookie, Biukop-Session, Biukop-Session-Token, Biukop-Session-Expire," + requestedHeaders
  291. return removeDupHeaderOptions(ret)
  292. }
  293. func removeDupHeaderOptions(inStr string) (out string) {
  294. headers := map[string]struct{}{}
  295. strings.ReplaceAll(inStr, " ", "") // remove space
  296. headerArray := strings.Split(inStr, ",") // split
  297. for _, v := range headerArray {
  298. headers[v] = struct{}{} // same key will overwrite each other
  299. }
  300. out = ""
  301. for k, _ := range headers {
  302. if out != "" {
  303. out += ", "
  304. }
  305. out += k
  306. }
  307. return
  308. }
  309. func apiV1GetMachineIdFromSession(ss *loan.Session) string {
  310. return ss.GetStr("Biukop-Mid")
  311. }
  312. func apiV1InitSessionByCookie(r *http.Request) (session loan.Session, e error) {
  313. var sid string
  314. session.MarkEmpty()
  315. mid := apiV1GetMachineId(r)
  316. inCookie, e := r.Cookie("Biukop-Session")
  317. if e == nil {
  318. sid = inCookie.Value
  319. if sid != "" {
  320. e = session.Read(sid)
  321. if e == nil {
  322. if mid != session.Get("Biukop-Mid") {
  323. session.MarkEmpty()
  324. }
  325. }
  326. }
  327. }
  328. return
  329. }
  330. func apiV1AddTrackingCookie(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  331. if strings.ToUpper(r.Method) == "OPTION" {
  332. return
  333. }
  334. w.Header().Add("Access-Control-Expose-Headers", apiV1GetCORSHeaders(r))
  335. apiV1AddTrackingSession(w, r, session)
  336. apiV1AddTrackingMachineId(w, r, session)
  337. }
  338. func apiV1AddTrackingSession(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  339. sessionId := ""
  340. if session == nil {
  341. log.Warn("non-exist session, empty Id sent", session)
  342. // w.Header().Add("Biukop-Session", "")
  343. } else {
  344. if session.Id == "" {
  345. log.Warn("empty session, empty Id sent", session)
  346. } else {
  347. w.Header().Add("Biukop-Session", session.Id)
  348. sessionId = session.Id
  349. }
  350. }
  351. cookie := http.Cookie{
  352. Name: "Biukop-Session",
  353. Value: sessionId, // may be ""
  354. Expires: time.Now().Add(365 * 24 * time.Hour),
  355. Path: "/",
  356. Secure: true,
  357. SameSite: http.SameSiteNoneMode}
  358. http.SetCookie(w, &cookie)
  359. }
  360. func apiV1AddTrackingMachineId(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  361. mid := apiV1GetMachineId(r)
  362. expiration := time.Now().Add(365 * 24 * time.Hour)
  363. w.Header().Add("Biukop-Mid", mid)
  364. cookie := http.Cookie{
  365. Name: "Biukop-Mid",
  366. Value: mid,
  367. Expires: expiration,
  368. Path: "/",
  369. Secure: true,
  370. SameSite: http.SameSiteNoneMode}
  371. http.SetCookie(w, &cookie)
  372. }
  373. func apiV1InitSessionByHttpHeader(r *http.Request) (ss loan.Session, e error) {
  374. ss.MarkEmpty()
  375. sid := apiV1GetSessionIdFromRequest(r)
  376. //make sure session id is given
  377. if sid != "" {
  378. e = ss.Retrieve(r)
  379. if e == sql.ErrNoRows { //db does not have required session.
  380. log.Warn("DB has no corresponding session ", sid)
  381. } else if e != nil { // retrieve DB has error
  382. log.Errorf("Retrieve Session %s encountered error %s", sid, e.Error())
  383. }
  384. } else {
  385. e = errors.New("session not found: " + sid)
  386. }
  387. return
  388. }
  389. func apiV1GetSessionIdFromRequest(r *http.Request) string {
  390. sid := ""
  391. inCookie, e := r.Cookie("Biukop-Session")
  392. if e == nil {
  393. sid = inCookie.Value
  394. }
  395. headerSid := r.Header.Get("Biukop-Session")
  396. if headerSid != "" {
  397. sid = headerSid
  398. }
  399. return sid
  400. }
  401. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  402. //general setup
  403. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  404. w.WriteHeader(500)
  405. apiV1AddTrackingCookie(w, r, nil) //always the last one to set cookies
  406. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  407. //write log
  408. dump := logRequestDebug(httputil.DumpRequest(r, true))
  409. dump = strings.TrimSpace(dump)
  410. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  411. }
  412. func apiV1Client403Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  413. //general setup
  414. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  415. w.WriteHeader(403)
  416. type struct403 struct {
  417. Error int
  418. ErrorMsg string
  419. }
  420. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  421. msg403, _ := json.Marshal(e403)
  422. //before send out
  423. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  424. fmt.Fprintln(w, string(msg403))
  425. //write log
  426. dump := logRequestDebug(httputil.DumpRequest(r, true))
  427. dump = strings.TrimSpace(dump)
  428. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  429. }
  430. func apiV1Client404Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  431. //general setup
  432. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  433. w.WriteHeader(404)
  434. type struct404 struct {
  435. Error int
  436. ErrorMsg string
  437. }
  438. e404 := struct404{Error: 404, ErrorMsg: "Not Found " + time.Now().Format(time.RFC1123)}
  439. msg404, _ := json.Marshal(e404)
  440. //before send out
  441. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  442. fmt.Fprintln(w, string(msg404))
  443. //write log
  444. dump := logRequestDebug(httputil.DumpRequest(r, true))
  445. dump = strings.TrimSpace(dump)
  446. log.Warnf("Not found http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  447. }
  448. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  449. dump := logRequestDebug(httputil.DumpRequest(r, true))
  450. dump = strings.TrimSpace(dump)
  451. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  452. dumpLines := strings.Split(dump, "\r\n")
  453. ar := apiV1ResponseBlank()
  454. ar.Env.Msg = msg
  455. ar.Env.Session = *ss
  456. ar.Env.Session.Bin = []byte("masked data") //clear
  457. ar.Env.Session.Secret = "***********"
  458. ar.add("Body", dumpLines)
  459. ar.add("Biukop-Mid", ss.Get("Biukop-Mid"))
  460. b, _ := ar.toJson()
  461. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  462. fmt.Fprintf(w, "%s\n", b)
  463. }
  464. func apiV1EmptyResponse(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  465. //general setup
  466. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  467. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  468. fmt.Fprintf(w, "")
  469. }