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

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