Brak opisu

utils.go 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "github.com/dgrijalva/jwt-go"
  10. "github.com/gorilla/context"
  11. "gopkg.in/mgo.v2"
  12. )
  13. type Error struct {
  14. Reason error
  15. Internal bool
  16. Code int
  17. }
  18. type Response map[string]interface{}
  19. type TokenData struct {
  20. ID string
  21. Iat float64
  22. Exp float64
  23. }
  24. func RandToken() string {
  25. b := make([]byte, 16)
  26. rand.Read(b)
  27. return fmt.Sprintf("%x", b)
  28. }
  29. func (r *Response) String() (s string) {
  30. b, err := json.Marshal(r)
  31. if err != nil {
  32. return ""
  33. }
  34. return string(b)
  35. }
  36. func HandleModelError(w http.ResponseWriter, r *http.Request, errM *Error) {
  37. if errM.Internal {
  38. ISR(w, r, errM.Reason)
  39. return
  40. } else {
  41. if errM.Code != 0 {
  42. BR(w, r, errM.Reason, errM.Code)
  43. } else {
  44. BR(w, r, errM.Reason, http.StatusBadRequest)
  45. }
  46. return
  47. }
  48. }
  49. func ISR(w http.ResponseWriter, r *http.Request, msg error) {
  50. w.WriteHeader(http.StatusInternalServerError)
  51. log.Println(msg)
  52. }
  53. func BR(w http.ResponseWriter, r *http.Request, msg error, code int) {
  54. ServeJSON(w, r, &Response{"error": msg.Error()}, code)
  55. }
  56. func NotAllowed(w http.ResponseWriter, r *http.Request) {
  57. w.WriteHeader(http.StatusUnauthorized)
  58. }
  59. func ServeJSON(w http.ResponseWriter, r *http.Request, json *Response, code int) {
  60. w.Header().Set("Content-Type", "application/json")
  61. w.WriteHeader(code)
  62. fmt.Fprint(w, json)
  63. }
  64. func GetDB(w http.ResponseWriter, r *http.Request) *mgo.Database {
  65. db, ok := context.GetOk(r, "DB")
  66. if !ok {
  67. ISR(w, r, errors.New("Couldn't obtain DB"))
  68. return nil
  69. }
  70. return db.(*mgo.Database)
  71. }
  72. func GetToken(w http.ResponseWriter, r *http.Request) *TokenData {
  73. token, ok := context.GetOk(r, "token")
  74. if !ok {
  75. BR(w, r, errors.New("Missing Token"), http.StatusUnauthorized)
  76. return nil
  77. }
  78. tokenData := token.(*jwt.Token).Claims
  79. return &TokenData{tokenData["ID"].(string), tokenData["iat"].(float64), tokenData["exp"].(float64)}
  80. }
  81. func IsTokenSet(r *http.Request) bool {
  82. _, ok := context.GetOk(r, "token")
  83. return ok
  84. }