2022-12-01 12:57:07 +03:00
|
|
|
package helpers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2022-12-01 13:11:45 +03:00
|
|
|
"errors"
|
2022-12-01 12:57:07 +03:00
|
|
|
"github.com/muety/wakapi/config"
|
2022-12-01 13:11:45 +03:00
|
|
|
"github.com/muety/wakapi/models"
|
2022-12-01 12:57:07 +03:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2022-12-01 13:11:45 +03:00
|
|
|
func ExtractCookieAuth(r *http.Request, config *config.Config) (username *string, err error) {
|
|
|
|
cookie, err := r.Cookie(models.AuthCookieKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.New("missing authentication")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := config.Security.SecureCookie.Decode(models.AuthCookieKey, cookie.Value, &username); err != nil {
|
|
|
|
return nil, errors.New("cookie is invalid")
|
|
|
|
}
|
|
|
|
|
|
|
|
return username, nil
|
2022-12-01 12:57:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func RespondJSON(w http.ResponseWriter, r *http.Request, status int, object interface{}) {
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.WriteHeader(status)
|
|
|
|
if err := json.NewEncoder(w).Encode(object); err != nil {
|
|
|
|
config.Log().Request(r).Error("error while writing json response: %v", err)
|
|
|
|
}
|
|
|
|
}
|