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.

404 lines
12KB

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