handlers.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package authlogger
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "regexp"
  7. "sort"
  8. "time"
  9. "imuslab.com/arozos/mod/utils"
  10. )
  11. type summaryDate []string
  12. func (s summaryDate) Len() int {
  13. return len(s)
  14. }
  15. func (s summaryDate) Swap(i, j int) {
  16. s[i], s[j] = s[j], s[i]
  17. }
  18. func (s summaryDate) Less(i, j int) bool {
  19. layout := "Jan-2006"
  20. timei, err := time.Parse(layout, s[i])
  21. if err != nil {
  22. log.Println(err)
  23. }
  24. timej, err := time.Parse(layout, s[j])
  25. if err != nil {
  26. log.Println(err)
  27. }
  28. return timei.Unix() > timej.Unix()
  29. }
  30. //Handle of listing of the logger index (months)
  31. func (l *Logger) HandleIndexListing(w http.ResponseWriter, r *http.Request) {
  32. indexes := l.ListSummary()
  33. sort.Sort(summaryDate(indexes))
  34. js, err := json.Marshal(indexes)
  35. if err != nil {
  36. utils.SendErrorResponse(w, err.Error())
  37. return
  38. }
  39. utils.SendJSONResponse(w, string(js))
  40. }
  41. //Handle of the listing of a given index (month)
  42. func (l *Logger) HandleTableListing(w http.ResponseWriter, r *http.Request) {
  43. //Get the record name request for listing
  44. month, err := utils.Mv(r, "record", true)
  45. if err != nil {
  46. utils.SendErrorResponse(w, err.Error())
  47. return
  48. }
  49. records, err := l.ListRecords(month)
  50. if err != nil {
  51. utils.SendErrorResponse(w, err.Error())
  52. return
  53. }
  54. //Filter the records before sending it to web UI
  55. results := []LoginRecord{}
  56. for _, record := range records {
  57. //Replace the username with a regex filtered one
  58. reg, _ := regexp.Compile("[^a-zA-Z0-9]+")
  59. filteredUsername := reg.ReplaceAllString(record.TargetUsername, "░")
  60. record.TargetUsername = filteredUsername
  61. results = append(results, record)
  62. }
  63. js, _ := json.Marshal(results)
  64. utils.SendJSONResponse(w, string(js))
  65. }