選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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