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.

365 lines
11KB

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