No Description

auth.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package auth
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "net/http"
  7. "strconv"
  8. "../curl"
  9. )
  10. type ServiceConfig struct {
  11. Endpoint string
  12. }
  13. var serviceConfig ServiceConfig
  14. type UserData struct {
  15. UserId string `json:"id_user"`
  16. Email string `json:"email"`
  17. Name string `json:"name"`
  18. Username string `json:"username"`
  19. Token string `json:"token"`
  20. UrlToken string `json:"url_token"`
  21. Avatar string `json:"avatar"`
  22. Language string `json:"language"`
  23. Errors []apiError `json:"errors"`
  24. }
  25. type apiError struct {
  26. Type string `json:"type"`
  27. Parameter string `json:"parameter"`
  28. Message string `json:"message"`
  29. }
  30. func (user UserData) getId() int {
  31. id, _ := strconv.Atoi(user.UserId)
  32. return id
  33. }
  34. func GetUser(httpReq *http.Request) (*UserData, bool) {
  35. curlReq, err := curlRequest(httpReq)
  36. if err != nil {
  37. return nil, false
  38. }
  39. response, err := curl.Curl(curlReq)
  40. if err != nil {
  41. log.Print(err)
  42. return nil, false
  43. }
  44. var userData UserData
  45. err = json.Unmarshal(response, &userData)
  46. //fmt.Printf("%+v\n", userData)
  47. if err != nil {
  48. log.Print(err)
  49. return nil, false
  50. }
  51. if len(userData.Errors) > 0 {
  52. return nil, false
  53. }
  54. return &userData, true
  55. }
  56. func curlRequest(request *http.Request) (*curl.Request, error) {
  57. authToken := request.Header.Get("Auth")
  58. if authToken != "" {
  59. headers := make(map[string]string)
  60. headers["Auth"] = authToken
  61. curlReq := &curl.Request{
  62. Url: serviceConfig.Endpoint,
  63. Method: "POST",
  64. Headers: headers,
  65. }
  66. return curlReq, nil
  67. }
  68. return nil, errors.New("No auth token found in http request")
  69. }
  70. func Config(config ServiceConfig) {
  71. serviceConfig = config
  72. }