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.

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