Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

367 Zeilen
11KB

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