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.

338 lines
10KB

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