Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

320 lines
9.6KB

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