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.

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