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.

524 lines
16KB

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