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.

324 lines
9.8KB

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