Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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