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.

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