You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
7.4KB

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