Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

416 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", "broker/", apiV1BrokerGet},
  48. {"POST", "broker/", apiV1BrokerPost},
  49. {"PUT", "broker/", apiV1BrokerPut},
  50. {"DELETE", "broker/", apiV1BrokerDelete},
  51. {"POST", "change-pass/", apiV1ChangePass},
  52. {"POST", "loan/basic/", apiV1LoanSinglePostBasic},
  53. {"GET", "avatar/", apiV1Avatar},
  54. {"POST", "avatar/", apiV1AvatarPost},
  55. {"POST", "reward/", apiV1RewardPost},
  56. {"DELETE", "reward/", apiV1RewardDelete},
  57. {"GET", "people-list/", apiV1PeopleList},
  58. {"GET", "broker-list/", apiV1BrokerList},
  59. {"POST", "sync-people/", apiV1SyncPeople},
  60. {"POST", "payIn/", apiV1PayInPost},
  61. {"DELETE", "payIn/", apiV1PayInDelete},
  62. {"POST", "pay-in-list/", apiV1PayInList},
  63. {"GET", "user-reward/", apiV1UserReward},
  64. {"GET", "login-available/", apiV1LoginAvailable},
  65. {"POST", "lender-upload/", apiV1UploadsPost},
  66. {"GET", "lender-upload/", apiV1UploadOriginalFileGet},
  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", "login", apiV1DumpRequest},
  80. }
  81. } else { //production
  82. return []apiV1HandlerMap{
  83. {"POST", "login", apiV1Login},
  84. {"*", "logout", apiV1Logout},
  85. {"GET", "chart/type-of-loans", apiV1ChartTypeOfLoans},
  86. {"GET", "chart/amount-of-loans", apiV1ChartTypeOfLoans},
  87. {"GET", "chart/past-year-monthly", apiV1ChartPastYearMonthly},
  88. {"GET", "chart/recent-10-loans", apiV1ChartRecent10Loans},
  89. {"GET", "chart/top-broker", apiV1ChartTopBroker},
  90. {"POST", "grid/loan/full-loan-overview", apiV1GridLoanFullOverview},
  91. {"GET", "chart/reward-vs-income-monthly", apiV1ChartRewardVsIncomeMonthly},
  92. {"GET", "loan/", apiV1LoanSingleGet},
  93. {"DELETE", "loan/", apiV1LoanSingleDelete},
  94. {"GET", "loan-by-client/", apiV1LoanByClient},
  95. {"GET", "people/", apiV1PeopleGet},
  96. {"POST", "people/", apiV1PeoplePost},
  97. {"PUT", "people/", apiV1PeoplePut},
  98. {"DELETE", "people/", apiV1PeopleDelete},
  99. {"GET", "people-extra/", apiV1PeopleExtraGet},
  100. {"POST", "user/", apiV1UserPost},
  101. {"PUT", "user/", apiV1UserPut},
  102. {"DELETE", "user/", apiV1UserDelete},
  103. {"POST", "user-enable/", apiV1UserEnable},
  104. {"GET", "broker/", apiV1BrokerGet},
  105. {"POST", "broker/", apiV1BrokerPost},
  106. {"PUT", "broker/", apiV1BrokerPut},
  107. {"DELETE", "broker/", apiV1BrokerDelete},
  108. {"POST", "change-pass/", apiV1ChangePass},
  109. {"POST", "loan/basic/", apiV1LoanSinglePostBasic},
  110. {"GET", "avatar/", apiV1Avatar},
  111. {"POST", "avatar/", apiV1AvatarPost},
  112. {"POST", "reward/", apiV1RewardPost},
  113. {"DELETE", "reward/", apiV1RewardDelete},
  114. {"GET", "people-list", apiV1PeopleList},
  115. {"GET", "broker-list/", apiV1BrokerList},
  116. {"POST", "sync-people/", apiV1SyncPeople},
  117. {"POST", "payIn/", apiV1PayInPost},
  118. {"DELETE", "payIn/", apiV1PayInDelete},
  119. {"POST", "pay-in-list/", apiV1PayInList},
  120. {"GET", "user-reward/", apiV1UserReward},
  121. {"GET", "login-available/", apiV1LoginAvailable},
  122. {"POST", "lender-upload/", apiV1UploadsPost},
  123. {"GET", "lender-upload/", apiV1UploadOriginalFileGet},
  124. {"GET", "upload-analysis/", apiV1UploadAnalysis},
  125. {"PUT", "upload-analysis/", apiV1UploadCreateAnalysis},
  126. {"GET", "upload-as-image/", apiV1UploadAsImage},
  127. {"PUT", "upload-as-image/", apiV1UploadCreateImage},
  128. {"GET", "upload-as-thumbnail/", apiV1UploadAsThumbnail},
  129. {"PUT", "upload-as-thumbnail/", apiV1UploadCreateThumbnail},
  130. {"GET", "upload-as-pdf/", apiV1UploadAsPDF},
  131. {"PUT", "upload-as-pdf/", apiV1UploadCreatePDF},
  132. {"GET", "upload-original/", apiV1UploadOriginalFileGet},
  133. {"GET", "upload-meta/", apiV1UploadMetaGet},
  134. {"DELETE", "upload/", apiV1UploadDelete},
  135. {"POST", "upload-meta-list/", apiV1UploadMetaList},
  136. {"GET", "login", apiV1EmptyResponse},
  137. }
  138. }
  139. }
  140. //
  141. //apiV1Main version 1 main entry for all REST API
  142. //
  143. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  144. //CORS setup
  145. setupCrossOriginResponse(&w, r)
  146. //if its options then we don't bother with other issues
  147. if r.Method == "OPTIONS" {
  148. apiV1EmptyResponse(w, r, nil)
  149. return //stop processing
  150. }
  151. if config.Debug {
  152. logRequestDebug(httputil.DumpRequest(r, true))
  153. }
  154. session := apiV1InitSession(r)
  155. if config.Debug {
  156. log.Debugf("session : %+v", session)
  157. }
  158. //search through handler
  159. path := r.URL.Path[len(apiV1Prefix):] //strip API prefix
  160. for _, node := range apiV1Handler {
  161. //log.Println(node, path, strings.HasPrefix(path, node.Path))
  162. if (r.Method == node.Method || node.Method == "*") && strings.HasPrefix(path, node.Path) {
  163. node.Handler(w, r, &session)
  164. e := session.Write() //finish this session to DB
  165. if e != nil {
  166. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  167. }
  168. return
  169. }
  170. }
  171. //Catch for all UnHandled Request
  172. e := session.Write() //finish this session to DB
  173. if e != nil {
  174. log.Warnf("Failed to Save Session %+v \n reason \n%s\n", session, e.Error())
  175. }
  176. if config.Debug {
  177. apiV1DumpRequest(w, r, &session)
  178. } else {
  179. apiV1EmptyResponse(w, r, &session)
  180. }
  181. }
  182. func apiV1InitSession(r *http.Request) (session loan.Session) {
  183. session.MarkEmpty()
  184. //track browser, and take session from cookie
  185. cookieSession, e := apiV1InitSessionByBrowserId(r)
  186. if e == nil {
  187. session = cookieSession
  188. }
  189. //try session login first, if not an empty session will be created
  190. headerSession, e := apiV1InitSessionByHttpHeader(r)
  191. if e == nil {
  192. session = headerSession
  193. }
  194. if session.IsEmpty() {
  195. session.InitGuest(time.Now().Add(loan.DefaultSessionDuration))
  196. } else {
  197. session.RenewIfExpireSoon()
  198. }
  199. //we have a session anyway
  200. session.Add("Biukop-Mid", apiV1GetMachineId(r)) //set machine id
  201. session.SetRemote(r) //make sure they are using latest remote
  202. return
  203. }
  204. func setupCrossOriginResponse(w *http.ResponseWriter, r *http.Request) {
  205. origin := r.Header.Get("Origin")
  206. if origin == "" {
  207. origin = "*"
  208. }
  209. requestedHeaders := r.Header.Get("Access-control-Request-Headers")
  210. method := r.Header.Get("Access-Control-Request-Method")
  211. (*w).Header().Set("Access-Control-Allow-Origin", origin) //for that specific origin
  212. (*w).Header().Set("Access-Control-Allow-Credentials", "true")
  213. (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, "+method)
  214. (*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)
  215. }
  216. func apiV1GetMachineId(r *http.Request) string {
  217. var mid string
  218. inCookie, e := r.Cookie("Biukop-Mid")
  219. if e == nil {
  220. mid = inCookie.Value
  221. } else {
  222. mid = gofakeit.UUID()
  223. }
  224. headerMid := r.Header.Get("Biukop-Mid")
  225. if headerMid != "" {
  226. mid = headerMid
  227. }
  228. return mid
  229. }
  230. func apiV1InitSessionByBrowserId(r *http.Request) (session loan.Session, e error) {
  231. var sid string
  232. mid := apiV1GetMachineId(r)
  233. inCookie, e := r.Cookie("Biukop-Session")
  234. if e == nil {
  235. sid = inCookie.Value
  236. if sid != "" {
  237. e = session.Read(sid)
  238. if e == nil {
  239. if mid != session.Get("Biukop-Mid") {
  240. session.MarkEmpty()
  241. }
  242. }
  243. }
  244. }
  245. return
  246. }
  247. func apiV1AddTrackingCookie(w http.ResponseWriter, r *http.Request, session *loan.Session) {
  248. //set session header too.
  249. w.Header().Add("Access-Control-Expose-Headers", "Biukop-Session")
  250. if session == nil {
  251. w.Header().Add("Biukop-Session", "")
  252. } else {
  253. w.Header().Add("Biukop-Session", session.Id)
  254. }
  255. //add tracking cookie
  256. expiration := time.Now().Add(365 * 24 * time.Hour)
  257. mid := apiV1GetMachineId(r)
  258. cookie := http.Cookie{Name: "Biukop-Mid", Value: mid, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  259. http.SetCookie(w, &cookie)
  260. if session != nil {
  261. cookie = http.Cookie{Name: "Biukop-Session", Value: session.Id, Expires: expiration, Path: "/", Secure: true, SameSite: http.SameSiteNoneMode}
  262. http.SetCookie(w, &cookie)
  263. }
  264. }
  265. func apiV1InitSessionByHttpHeader(r *http.Request) (ss loan.Session, e error) {
  266. sid := r.Header.Get("Biukop-Session")
  267. ss.MarkEmpty()
  268. //make sure session id is given
  269. if sid != "" {
  270. e = ss.Retrieve(r)
  271. if e == sql.ErrNoRows { //db does not have required session.
  272. log.Warn("DB has no corresponding session ", sid)
  273. } else if e != nil { // retrieve DB has error
  274. log.Errorf("Retrieve Session %s encountered error %s", sid, e.Error())
  275. }
  276. } else {
  277. e = errors.New("session not found: " + sid)
  278. }
  279. return
  280. return
  281. }
  282. func apiV1ErrorCheck(e error) {
  283. if nil != e {
  284. panic(e.Error()) //TODO: detailed error check, truck all caller
  285. }
  286. }
  287. func apiV1Server500Error(w http.ResponseWriter, r *http.Request) {
  288. //general setup
  289. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  290. w.WriteHeader(500)
  291. apiV1AddTrackingCookie(w, r, nil) //always the last one to set cookies
  292. fmt.Fprintf(w, "Server Internal Error "+time.Now().Format(time.RFC1123))
  293. //write log
  294. dump := logRequestDebug(httputil.DumpRequest(r, true))
  295. dump = strings.TrimSpace(dump)
  296. log.Warnf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  297. }
  298. func apiV1Client403Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  299. //general setup
  300. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  301. w.WriteHeader(403)
  302. type struct403 struct {
  303. Error int
  304. ErrorMsg string
  305. }
  306. e403 := struct403{Error: 403, ErrorMsg: "Not Authorized " + time.Now().Format(time.RFC1123)}
  307. msg403, _ := json.Marshal(e403)
  308. //before send out
  309. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  310. fmt.Fprintln(w, string(msg403))
  311. //write log
  312. dump := logRequestDebug(httputil.DumpRequest(r, true))
  313. dump = strings.TrimSpace(dump)
  314. log.Warnf("Not authorized http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  315. }
  316. func apiV1Client404Error(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  317. //general setup
  318. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  319. w.WriteHeader(404)
  320. type struct404 struct {
  321. Error int
  322. ErrorMsg string
  323. }
  324. e404 := struct404{Error: 404, ErrorMsg: "Not Found " + time.Now().Format(time.RFC1123)}
  325. msg404, _ := json.Marshal(e404)
  326. //before send out
  327. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  328. fmt.Fprintln(w, string(msg404))
  329. //write log
  330. dump := logRequestDebug(httputil.DumpRequest(r, true))
  331. dump = strings.TrimSpace(dump)
  332. log.Warnf("Not found http(%s) path= %s, %s", r.Method, r.URL.Path, dump)
  333. }
  334. func apiV1DumpRequest(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  335. dump := logRequestDebug(httputil.DumpRequest(r, true))
  336. dump = strings.TrimSpace(dump)
  337. msg := fmt.Sprintf("Unhandled Protocol = %s path= %s", r.Method, r.URL.Path)
  338. dumpLines := strings.Split(dump, "\r\n")
  339. ar := apiV1ResponseBlank()
  340. ar.Env.Msg = msg
  341. ar.Env.Session = *ss
  342. ar.Env.Session.Bin = []byte("masked data") //clear
  343. ar.Env.Session.Secret = "***********"
  344. ar.add("Body", dumpLines)
  345. ar.add("Biukop-Mid", ss.Get("Biukop-Mid"))
  346. b, _ := ar.toJson()
  347. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  348. fmt.Fprintf(w, "%s\n", b)
  349. }
  350. func apiV1EmptyResponse(w http.ResponseWriter, r *http.Request, ss *loan.Session) {
  351. //general setup
  352. w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  353. apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  354. fmt.Fprintf(w, "")
  355. }