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.

318 line
9.5KB

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