Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

427 lines
13KB

  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", "lender-upload/", apiV1UploadOriginalFileGet},
  68. {"GET", "upload-analysis/", apiV1UploadAnalysis},
  69. {"PUT", "upload-analysis/", apiV1UploadCreateAnalysis},
  70. {"GET", "upload-as-image/", apiV1UploadAsImage},
  71. {"PUT", "upload-as-image/", apiV1UploadCreateImage},
  72. {"GET", "upload-as-thumbnail/", apiV1UploadAsThumbnail},
  73. {"PUT", "upload-as-thumbnail/", apiV1UploadCreateThumbnail},
  74. {"GET", "upload-as-pdf/", apiV1UploadAsPDF},
  75. {"PUT", "upload-as-pdf/", apiV1UploadCreatePDF},
  76. {"GET", "upload-original/", apiV1UploadOriginalFileGet},
  77. {"GET", "upload/", apiV1UploadMetaGet},
  78. {"DELETE", "upload/", apiV1UploadDelete},
  79. {"POST", "upload-meta-list/", apiV1UploadMetaList},
  80. {"GET", "lender-list/", apiV1LenderList},
  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", "lender-upload/", apiV1UploadOriginalFileGet},
  127. {"GET", "upload-analysis/", apiV1UploadAnalysis},
  128. {"PUT", "upload-analysis/", apiV1UploadCreateAnalysis},
  129. {"GET", "upload-as-image/", apiV1UploadAsImage},
  130. {"PUT", "upload-as-image/", apiV1UploadCreateImage},
  131. {"GET", "upload-as-thumbnail/", apiV1UploadAsThumbnail},
  132. {"PUT", "upload-as-thumbnail/", apiV1UploadCreateThumbnail},
  133. {"GET", "upload-as-pdf/", apiV1UploadAsPDF},
  134. {"PUT", "upload-as-pdf/", apiV1UploadCreatePDF},
  135. {"GET", "upload-original/", apiV1UploadOriginalFileGet},
  136. {"GET", "upload-meta/", apiV1UploadMetaGet},
  137. {"DELETE", "upload/", apiV1UploadDelete},
  138. {"POST", "upload-meta-list/", apiV1UploadMetaList},
  139. {"GET", "lender-list/", apiV1LenderList},
  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 := apiV1InitSession(r)
  159. if config.Debug {
  160. log.Debugf("session : %+v", session)
  161. }
  162. //search through handler
  163. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  164. for _, node := range apiV1Handler {
  165. //log.Println(node, path, strings.HasPrefix(path, node.Path))
  166. if (r.Method == node.Method || node.Method == "*") && strings.HasPrefix(path, node.Path) {
  167. node.Handler(w, r, &session)
  168. e := session.Write() //finish this session to DB
  169. if e != nil {
  170. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  171. }
  172. return
  173. }
  174. }
  175. //Catch for all UnHandled Request
  176. e := session.Write() //finish this session to DB
  177. if e != nil {
  178. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  179. }
  180. if config.Debug {
  181. apiV1DumpRequest(w, r, &session)
  182. } else {
  183. apiV1EmptyResponse(w, r, &session)
  184. }
  185. }
  186. func apiV1InitSession(r *http.Request) (session loan.Session) {
  187. session.MarkEmpty()
  188. //track browser, and take session from cookie
  189. cookieSession, e := apiV1InitSessionByBrowserId(r)
  190. if e == nil {
  191. session = cookieSession
  192. }
  193. //try session login first, if not an empty session will be created
  194. headerSession, e := apiV1InitSessionByHttpHeader(r)
  195. if e == nil {
  196. session = headerSession
  197. }
  198. if session.IsEmpty() {
  199. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  200. } else {
  201. session.RenewIfExpireSoon()
  202. }
  203. //we have a session anyway
  204. session.Add("Biukop-Mid", apiV1GetMachineId(r)) //set machine id
  205. session.SetRemote(r) //make sure they are using latest remote
  206. return
  207. }
  208. func setupCrossOriginResponse(w *http.ResponseWriter, r *http.Request) {
  209. origin := r.Header.Get("Origin")
  210. if origin == "" {
  211. origin = "*"
  212. }
  213. requestedHeaders := r.Header.Get("Access-control-Request-Headers")
  214. method := r.Header.Get("Access-Control-Request-Method")
  215. (*w).Header().Set("Access-Control-Allow-Origin", origin) //for that specific origin
  216. (*w).Header().Set("Access-Control-Allow-Credentials", "true")
  217. (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, "+method)
  218. (*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)
  219. }
  220. func apiV1GetMachineId(r *http.Request) string {
  221. var mid string
  222. inCookie, e := r.Cookie("Biukop-Mid")
  223. if e == nil {
  224. mid = inCookie.Value
  225. } else {
  226. mid = gofakeit.UUID()
  227. }
  228. headerMid := r.Header.Get("Biukop-Mid")
  229. if headerMid != "" {
  230. mid = headerMid
  231. }
  232. return mid
  233. }
  234. func apiV1GetMachineIdFromSession(ss *loan.Session) string {
  235. return ss.GetStr("Biukop-Mid")
  236. }
  237. func apiV1InitSessionByBrowserId(r *http.Request) (session loan.Session, e error) {
  238. var sid string
  239. mid := apiV1GetMachineId(r)
  240. inCookie, e := r.Cookie("Biukop-Session")
  241. if e == nil {
  242. sid = inCookie.Value
  243. if sid != "" {
  244. e = session.Read(sid)
  245. if e == nil {
  246. if mid != session.Get("Biukop-Mid") {
  247. session.MarkEmpty()
  248. }
  249. }
  250. }
  251. }
  252. return
  253. }
  254. func apiV1AddTrackingCookie(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  255. //set session header too.
  256. w.Header().Add("Access-Control-Expose-Headers", "Biukop-Session")
  257. if session == nil {
  258. w.Header().Add("Biukop-Session", "")
  259. } else {
  260. w.Header().Add("Biukop-Session", session.Id)
  261. }
  262. //add tracking cookie
  263. expiration := time.Now().Add(365 * 24 * time.Hour)
  264. mid := apiV1GetMachineId(r)
  265. cookie := http.Cookie{Name: "Biukop-Mid", Value: mid, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  266. http.SetCookie(w, &cookie)
  267. if session != nil {
  268. cookie = http.Cookie{Name: "Biukop-Session", Value: session.Id, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  269. http.SetCookie(w, &cookie)
  270. }
  271. }
  272. func apiV1InitSessionByHttpHeader(r *http.Request) (ss loan.Session, e error) {
  273. sid := r.Header.Get("Biukop-Session")
  274. ss.MarkEmpty()
  275. //make sure session id is given
  276. if sid != "" {
  277. e = ss.Retrieve(r)
  278. if e == sql.ErrNoRows { //db does not have required session.
  279. log.Warn("DB has no corresponding session ", sid)
  280. } else if e != nil { // retrieve DB has error
  281. log.Errorf("Retrieve Session %s encountered error %s", sid, e.Error())
  282. }
  283. } else {
  284. e = errors.New("session not found: " + sid)
  285. }
  286. return
  287. return
  288. }
  289. func apiV1ErrorCheck(e error) {
  290. if nil != e {
  291. panic(e.Error()) //TODO: detailed error check, truck all caller
  292. }
  293. }
  294. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  295. //general setup
  296. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  297. w.WriteHeader(500)
  298. apiV1AddTrackingCookie(w, r, nil) //always the last one to set cookies
  299. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  300. //write log
  301. dump := logRequestDebug(httputil.DumpRequest(r, true))
  302. dump = strings.TrimSpace(dump)
  303. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  304. }
  305. func apiV1Client403Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  306. //general setup
  307. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  308. w.WriteHeader(403)
  309. type struct403 struct {
  310. Error int
  311. ErrorMsg string
  312. }
  313. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  314. msg403, _ := json.Marshal(e403)
  315. //before send out
  316. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  317. fmt.Fprintln(w, string(msg403))
  318. //write log
  319. dump := logRequestDebug(httputil.DumpRequest(r, true))
  320. dump = strings.TrimSpace(dump)
  321. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  322. }
  323. func apiV1Client404Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  324. //general setup
  325. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  326. w.WriteHeader(404)
  327. type struct404 struct {
  328. Error int
  329. ErrorMsg string
  330. }
  331. e404 := struct404{Error: 404, ErrorMsg: "Not Found " + time.Now().Format(time.RFC1123)}
  332. msg404, _ := json.Marshal(e404)
  333. //before send out
  334. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  335. fmt.Fprintln(w, string(msg404))
  336. //write log
  337. dump := logRequestDebug(httputil.DumpRequest(r, true))
  338. dump = strings.TrimSpace(dump)
  339. log.Warnf("Not found http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  340. }
  341. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  342. dump := logRequestDebug(httputil.DumpRequest(r, true))
  343. dump = strings.TrimSpace(dump)
  344. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  345. dumpLines := strings.Split(dump, "\r\n")
  346. ar := apiV1ResponseBlank()
  347. ar.Env.Msg = msg
  348. ar.Env.Session = *ss
  349. ar.Env.Session.Bin = []byte("masked data") //clear
  350. ar.Env.Session.Secret = "***********"
  351. ar.add("Body", dumpLines)
  352. ar.add("Biukop-Mid", ss.Get("Biukop-Mid"))
  353. b, _ := ar.toJson()
  354. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  355. fmt.Fprintf(w, "%s\n", b)
  356. }
  357. func apiV1EmptyResponse(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  358. //general setup
  359. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  360. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  361. fmt.Fprintf(w, "")
  362. }