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.

255 lines
7.0KB

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