123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package auth
- import (
- "encoding/json"
- "errors"
- "log"
- "net/http"
- "strconv"
- "../curl"
- )
- type ServiceConfig struct {
- Endpoint string
- }
- var serviceConfig ServiceConfig
- type UserData struct {
- UserId string `json:"id_user"`
- Email string `json:"email"`
- Name string `json:"name"`
- Username string `json:"username"`
- Token string `json:"token"`
- UrlToken string `json:"url_token"`
- Avatar string `json:"avatar"`
- Language string `json:"language"`
- Errors []apiError `json:"errors"`
- }
- type apiError struct {
- Type string `json:"type"`
- Parameter string `json:"parameter"`
- Message string `json:"message"`
- }
- func (user UserData) getId() int {
- id, _ := strconv.Atoi(user.UserId)
- return id
- }
- func GetUser(httpReq *http.Request) (*UserData, bool) {
- curlReq, err := curlRequest(httpReq)
- if err != nil {
- return nil, false
- }
- response, err := curl.Curl(curlReq)
- if err != nil {
- log.Print(err)
- return nil, false
- }
- var userData UserData
- err = json.Unmarshal(response, &userData)
- //fmt.Printf("%+v\n", userData)
- if err != nil {
- log.Print(err)
- return nil, false
- }
- if len(userData.Errors) > 0 {
- return nil, false
- }
- return &userData, true
- }
- func curlRequest(request *http.Request) (*curl.Request, error) {
- authToken := request.Header.Get("Auth")
- if authToken != "" {
- headers := make(map[string]string)
- headers["Auth"] = authToken
- curlReq := &curl.Request{
- Url: serviceConfig.Endpoint,
- Method: "POST",
- Headers: headers,
- }
- return curlReq, nil
- }
- return nil, errors.New("No auth token found in http request")
- }
- func Config(config ServiceConfig) {
- serviceConfig = config
- }
|