handlers.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package handlers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "path"
  9. "path/filepath"
  10. "reflect"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "gogs.carducci-dante.gov.it/karmen/core/config"
  15. "gogs.carducci-dante.gov.it/karmen/core/orm"
  16. "gogs.carducci-dante.gov.it/karmen/core/renderer"
  17. jwtmiddleware "github.com/auth0/go-jwt-middleware"
  18. jwt "github.com/dgrijalva/jwt-go"
  19. "github.com/gorilla/mux"
  20. "github.com/gorilla/sessions"
  21. "github.com/jinzhu/inflection"
  22. )
  23. type User struct {
  24. Name string
  25. Admin bool
  26. }
  27. type PathPattern struct {
  28. PathPattern string
  29. RedirectPattern string
  30. Methods []string
  31. }
  32. var (
  33. signingKey = []byte(config.Config.Keys.JWTSigningKey)
  34. store = sessions.NewCookieStore([]byte(config.Config.Keys.CookieStoreKey))
  35. jwtCookie = jwtmiddleware.New(jwtmiddleware.Options{
  36. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  37. return signingKey, nil
  38. },
  39. SigningMethod: jwt.SigningMethodHS256,
  40. Extractor: fromCookie,
  41. ErrorHandler: onError,
  42. })
  43. jwtHeader = jwtmiddleware.New(jwtmiddleware.Options{
  44. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  45. return signingKey, nil
  46. },
  47. SigningMethod: jwt.SigningMethodHS256,
  48. })
  49. )
  50. func (pp PathPattern) RedirectPath(model string, id ...uint) string {
  51. if len(id) > 0 {
  52. return fmt.Sprintf(pp.RedirectPattern, model, id[0], model)
  53. }
  54. return fmt.Sprintf(pp.RedirectPattern, model, model)
  55. }
  56. func (pp PathPattern) Path(model string) string {
  57. return fmt.Sprintf(pp.PathPattern, model)
  58. }
  59. func modelName(s interface{}) string {
  60. if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
  61. return t.Elem().Name()
  62. } else {
  63. return t.Name()
  64. }
  65. }
  66. func pluralizedModelName(s interface{}) string {
  67. return inflection.Plural(strings.ToLower(modelName(s)))
  68. }
  69. // Generate CRUD handlers for models
  70. func generateHandler(r *mux.Router, model interface{}) {
  71. var (
  72. patterns []PathPattern = []PathPattern{
  73. PathPattern{"/%s", "", []string{"GET"}},
  74. PathPattern{"/%s/{id}", "", []string{"GET"}},
  75. PathPattern{"/%s/create/", "/%s/%d?format=html&tpl_layout=base&tpl_content=%s_show", []string{"GET", "POST"}},
  76. PathPattern{"/%s/{id}/update", "/%s/%d?format=html&tpl_layout=base&tpl_content=%s_show", []string{"GET", "POST"}},
  77. PathPattern{"/%s/{id}/delete", "/%s?format=html&tpl_layout=base&tpl_content=%s", []string{"DELETE"}},
  78. }
  79. apiPatterns []PathPattern
  80. executePatterns []PathPattern = []PathPattern{
  81. PathPattern{"/%s/{id}/execute", "", []string{"GET"}},
  82. }
  83. filePatterns []PathPattern = []PathPattern{
  84. PathPattern{"/%s/{id}/files/{filename}", "", []string{"GET"}},
  85. }
  86. )
  87. // Generate API patterns prefixing "api" path
  88. for _, p := range patterns {
  89. apiPatterns = append(apiPatterns, PathPattern{path.Join("/", "api", p.PathPattern), "", []string{"GET"}})
  90. }
  91. // Install standard paths
  92. for _, pattern := range patterns {
  93. log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
  94. r.Handle(pattern.Path(pluralizedModelName(model)), jwtCookie.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
  95. }
  96. // Install API paths
  97. for _, pattern := range apiPatterns {
  98. log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
  99. r.Handle(pattern.Path(pluralizedModelName(model)), jwtHeader.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
  100. }
  101. if model == "documents" {
  102. for _, pattern := range executePatterns {
  103. log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
  104. r.Handle(pattern.Path(pluralizedModelName(model)), jwtCookie.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
  105. }
  106. }
  107. if model == "jobs" {
  108. for _, pattern := range filePatterns {
  109. log.Printf("Register handler %s", pattern.Path(pluralizedModelName(model)))
  110. r.Handle(pattern.Path(pluralizedModelName(model)), jwtCookie.Handler(recoverHandler(modelHandler(pluralizedModelName(model), pattern)))).Methods(pattern.Methods...)
  111. }
  112. }
  113. }
  114. func Handlers(models []interface{}) *mux.Router {
  115. r := mux.NewRouter()
  116. // Authentication
  117. r.Handle("/login", loginHandler())
  118. r.Handle("/logout", logoutHandler())
  119. // Dashboard
  120. r.Handle("/", jwtCookie.Handler(recoverHandler(homeHandler())))
  121. // Generate model handlers
  122. for _, model := range models {
  123. generateHandler(r, model)
  124. }
  125. // Token handling
  126. r.Handle("/get_token", tokenHandler())
  127. // Static file server
  128. r.PathPrefix("/").Handler(http.FileServer(http.Dir("./dist/")))
  129. return r
  130. }
  131. func onError(w http.ResponseWriter, r *http.Request, err string) {
  132. http.Redirect(w, r, "/login?tpl_layout=login&tpl_content=login", http.StatusTemporaryRedirect)
  133. }
  134. func respondWithStaticFile(w http.ResponseWriter, filename string) error {
  135. f, err := ioutil.ReadFile(filepath.Join("public/html", filename))
  136. if err != nil {
  137. return err
  138. }
  139. w.Write(f)
  140. return nil
  141. }
  142. func fromCookie(r *http.Request) (string, error) {
  143. session, err := store.Get(r, "login-session")
  144. if err != nil {
  145. return "", nil
  146. }
  147. if session.Values["token"] == nil {
  148. return "", nil
  149. }
  150. token := session.Values["token"].([]uint8)
  151. return string(token), nil
  152. }
  153. func recoverHandler(next http.Handler) http.Handler {
  154. fn := func(w http.ResponseWriter, r *http.Request) {
  155. defer func() {
  156. if err := recover(); err != nil {
  157. panicMsg := fmt.Sprintf("PANIC: %v\n\n== STACKTRACE ==\n%s", err, debug.Stack())
  158. log.Print(panicMsg)
  159. http.Error(w, panicMsg, http.StatusInternalServerError)
  160. }
  161. }()
  162. next.ServeHTTP(w, r)
  163. }
  164. return http.HandlerFunc(fn)
  165. }
  166. func get(w http.ResponseWriter, r *http.Request, model string, pattern PathPattern) {
  167. format := r.URL.Query().Get("format")
  168. getFn, err := orm.GetFunc(pattern.Path(model))
  169. if err != nil {
  170. log.Println("Error:", err)
  171. respondWithError(w, r, err)
  172. } else {
  173. data, err := getFn(mux.Vars(r), r)
  174. if err != nil {
  175. renderer.Render[format](w, r, err)
  176. } else {
  177. renderer.Render[format](w, r, data, r.URL.Query())
  178. }
  179. }
  180. }
  181. func post(w http.ResponseWriter, r *http.Request, model string, pattern PathPattern) {
  182. var (
  183. data interface{}
  184. err error
  185. )
  186. respFormat := renderer.GetContentFormat(r)
  187. postFn, err := orm.GetFunc(pattern.Path(model))
  188. if err != nil {
  189. respondWithError(w, r, err)
  190. } else {
  191. data, err = postFn(mux.Vars(r), r)
  192. if err != nil {
  193. respondWithError(w, r, err)
  194. } else if pattern.RedirectPattern != "" {
  195. if id := mux.Vars(r)["id"]; id != "" {
  196. modelId, _ := strconv.Atoi(id)
  197. http.Redirect(w, r, pattern.RedirectPath(model, uint(modelId)), http.StatusSeeOther)
  198. } else {
  199. http.Redirect(w, r, pattern.RedirectPath(model, data.(orm.IDer).GetID()), http.StatusSeeOther)
  200. }
  201. } else {
  202. renderer.Render[respFormat](w, r, data.(orm.IDer).GetID())
  203. }
  204. }
  205. }
  206. func delete(w http.ResponseWriter, r *http.Request, model string, pattern PathPattern) {
  207. var (
  208. data interface{}
  209. err error
  210. )
  211. respFormat := renderer.GetContentFormat(r)
  212. postFn, err := orm.GetFunc(pattern.Path(model))
  213. if err != nil {
  214. renderer.Render[r.URL.Query().Get("format")](w, r, err)
  215. }
  216. data, err = postFn(mux.Vars(r), r)
  217. if err != nil {
  218. renderer.Render["html"](w, r, err)
  219. } else if pattern.RedirectPattern != "" {
  220. var data struct {
  221. RedirectUrl string `json:"redirect_url"`
  222. }
  223. data.RedirectUrl = pattern.RedirectPath(model)
  224. w.Header().Set("Content-Type", "application/json")
  225. json.NewEncoder(w).Encode(data)
  226. } else {
  227. renderer.Render[respFormat](w, r, data.(orm.IDer).GetID())
  228. }
  229. }
  230. func respondWithError(w http.ResponseWriter, r *http.Request, err error) {
  231. respFormat := renderer.GetContentFormat(r)
  232. w.WriteHeader(http.StatusInternalServerError)
  233. renderer.Render[respFormat](w, r, err)
  234. }
  235. func modelHandler(model string, pattern PathPattern) http.Handler {
  236. fn := func(w http.ResponseWriter, r *http.Request) {
  237. switch r.Method {
  238. case "GET":
  239. get(w, r, model, pattern)
  240. case "POST":
  241. post(w, r, model, pattern)
  242. case "DELETE":
  243. delete(w, r, model, pattern)
  244. }
  245. }
  246. return http.HandlerFunc(fn)
  247. }
  248. func homeHandler() http.Handler {
  249. fn := func(w http.ResponseWriter, r *http.Request) {
  250. http.Redirect(w, r, "/teachers?format=html&tpl_layout=teachers&tpl_content=teachers", http.StatusSeeOther)
  251. }
  252. return http.HandlerFunc(fn)
  253. }