Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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