Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

326 linhas
9.9KB

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