s3browser-backend/internal/httpServer.go

245 lines
5.7 KiB
Go
Raw Normal View History

2021-08-03 21:10:23 +00:00
package s3browser
import (
"context"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
2021-09-14 13:16:37 +00:00
"strings"
"time"
2021-08-03 21:10:23 +00:00
2021-09-14 13:16:37 +00:00
"github.com/golang-jwt/jwt"
2021-09-11 20:17:22 +00:00
"github.com/gorilla/mux"
2021-08-03 21:10:23 +00:00
"github.com/graphql-go/graphql"
2021-08-13 23:33:42 +00:00
"github.com/graphql-go/graphql/gqlerrors"
2021-08-03 21:10:23 +00:00
"github.com/graphql-go/handler"
"github.com/minio/minio-go/v7"
2021-08-12 15:48:28 +00:00
log "github.com/sirupsen/logrus"
2021-08-03 21:10:23 +00:00
)
2021-09-14 13:16:37 +00:00
type JWTClaims struct {
jwt.StandardClaims
}
2021-08-03 21:10:23 +00:00
// initHttp setup and start the http server. Blocking
2021-09-09 11:41:38 +00:00
func initHttp(resolveContext context.Context, schema graphql.Schema, address string) error {
2021-09-11 20:17:22 +00:00
r := mux.NewRouter()
gqlHandler := handler.New(&handler.Config{
2021-08-03 21:10:23 +00:00
Schema: &schema,
Pretty: true,
GraphiQL: false,
Playground: true,
2021-08-13 23:33:42 +00:00
FormatErrorFn: func(err error) gqlerrors.FormattedError {
switch err := err.(type) {
case gqlerrors.FormattedError:
log.Error("GQL: ", err.Message)
case *gqlerrors.Error:
log.Errorf("GQL: '%s' at '%v'", err.Message, err.Path)
}
return gqlerrors.FormatError(err)
},
2021-08-03 21:10:23 +00:00
})
2021-09-11 20:17:22 +00:00
r.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
2021-09-14 13:16:37 +00:00
token := getTokenFromRequest(r)
if token != "" {
parsedToken, err := parseJWT(token)
if err == nil && parsedToken.Valid {
2021-09-14 14:51:01 +00:00
newRequest := r.WithContext(context.WithValue(r.Context(), "jwt", parsedToken))
h.ServeHTTP(rw, newRequest)
return
2021-09-14 13:16:37 +00:00
}
}
2021-09-11 20:17:22 +00:00
h.ServeHTTP(rw, r)
})
2021-08-03 21:10:23 +00:00
})
2021-09-11 20:17:22 +00:00
r.HandleFunc("/api/graphql", func(rw http.ResponseWriter, r *http.Request) {
2021-09-14 14:51:01 +00:00
token := r.Context().Value("jwt")
gqlHandler.ContextHandler(context.WithValue(resolveContext, "jwt", token), rw, r)
2021-08-03 21:10:23 +00:00
})
2021-09-11 20:17:22 +00:00
r.HandleFunc("/api/file", func(rw http.ResponseWriter, r *http.Request) {
httpGetFile(resolveContext, rw, r)
}).Methods("GET")
r.HandleFunc("/api/file", func(rw http.ResponseWriter, r *http.Request) {
httpPostFile(resolveContext, rw, r)
}).Methods("POST")
2021-09-14 13:16:37 +00:00
r.HandleFunc("/api/cookie", setLoginCookie).Methods("POST")
2021-09-03 21:23:06 +00:00
// Init the embedded static files
2021-09-11 20:17:22 +00:00
initStatic(r)
2021-09-03 21:23:06 +00:00
2021-09-11 20:17:22 +00:00
return http.ListenAndServe(address, r)
2021-08-03 21:10:23 +00:00
}
2021-08-06 12:13:08 +00:00
func httpGetFile(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
2021-09-14 14:51:01 +00:00
if is, _ := isAuth(r.Context()); !is {
rw.WriteHeader(http.StatusUnauthorized)
return
}
2021-08-06 12:13:08 +00:00
s3Client := ctx.Value("s3Client").(*minio.Client)
2021-08-03 21:10:23 +00:00
id := r.URL.Query().Get("id")
2021-08-12 15:48:28 +00:00
log.Debug("S3 call 'StatObject': ", id)
2021-08-03 21:10:23 +00:00
objInfo, err := s3Client.StatObject(context.Background(), bucketName, id, minio.GetObjectOptions{})
if err != nil {
2021-08-06 14:31:07 +00:00
rw.WriteHeader(http.StatusInternalServerError)
2021-08-03 21:10:23 +00:00
return
}
reqEtag := r.Header.Get("If-None-Match")
if reqEtag == objInfo.ETag {
2021-08-06 14:31:07 +00:00
rw.WriteHeader(http.StatusNotModified)
2021-08-03 21:10:23 +00:00
return
}
2021-08-12 15:48:28 +00:00
log.Debug("S3 call 'GetObject': ", id)
2021-08-03 21:10:23 +00:00
obj, err := s3Client.GetObject(context.Background(), bucketName, id, minio.GetObjectOptions{})
if err != nil {
2021-08-06 14:31:07 +00:00
rw.WriteHeader(http.StatusInternalServerError)
2021-08-03 21:10:23 +00:00
return
}
rw.Header().Set("Cache-Control", "must-revalidate")
rw.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base((objInfo.Key))))
rw.Header().Set("Content-Type", objInfo.ContentType)
rw.Header().Set("ETag", objInfo.ETag)
2021-08-06 14:31:07 +00:00
_, err = io.Copy(rw, obj)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
2021-08-03 21:10:23 +00:00
}
2021-08-06 12:13:08 +00:00
func httpPostFile(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
2021-09-14 14:51:01 +00:00
if is, _ := isAuth(r.Context()); !is {
rw.WriteHeader(http.StatusUnauthorized)
return
}
2021-08-06 12:13:08 +00:00
s3Client := ctx.Value("s3Client").(*minio.Client)
2021-08-03 21:10:23 +00:00
2021-08-06 12:13:08 +00:00
id := r.URL.Query().Get("id")
2021-08-06 11:49:00 +00:00
2021-08-12 15:48:28 +00:00
log.Debug("Upload file: ", id)
2021-08-03 21:10:23 +00:00
contentType := r.Header.Get("Content-Type")
2021-08-06 11:49:00 +00:00
mimeType, _, _ := mime.ParseMediaType(contentType)
2021-08-03 21:10:23 +00:00
2021-08-12 15:48:28 +00:00
log.Debug("S3 call 'PutObject': ", id)
2021-08-06 14:31:07 +00:00
info, err := s3Client.PutObject(context.Background(), bucketName, id, r.Body, r.ContentLength, minio.PutObjectOptions{
2021-08-06 11:49:00 +00:00
ContentType: mimeType,
})
2021-08-03 21:10:23 +00:00
2021-08-06 14:31:07 +00:00
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
2021-08-06 12:13:08 +00:00
// Invalidate cache
2021-08-14 12:13:49 +00:00
invalidateCache(ctx, info.Key)
2021-08-06 12:13:08 +00:00
2021-08-06 14:31:07 +00:00
rw.WriteHeader(http.StatusCreated)
2021-08-03 21:10:23 +00:00
}
2021-09-14 13:16:37 +00:00
//parseJWT parse a JWT. does not check if token is valid. Returns error if non was provided
func parseJWT(token string) (*jwt.Token, error) {
if token == "" {
return nil, fmt.Errorf("No token provided")
}
parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte("TODO"), nil
})
if err != nil {
return nil, err
}
return parsed, nil
}
//getTokenFromRequest looks for a JWT in the "Authorization" header or in the cookies
func getTokenFromRequest(r *http.Request) string {
// get token from header
authHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ")
if len(authHeader) == 2 {
return authHeader[1]
}
// Get cookie from cookie
cookie, err := r.Cookie("jwt") //TODO: change cookie name
if err == nil && len(cookie.Value) != 0 {
return cookie.Value
}
return ""
}
//setLoginCookie if provieded a valid JWT in the body then set a httpOnly cookie with the token
func setLoginCookie(rw http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
tokenString := string(body)
token, err := parseJWT(tokenString)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
if !token.Valid {
rw.WriteHeader(http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
rw.WriteHeader(http.StatusInternalServerError)
return
}
cookie := &http.Cookie{
Name: "jwt",
Value: tokenString,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Path: "/api",
Expires: time.Unix(int64(claims["exp"].(float64)), 0),
}
http.SetCookie(rw, cookie)
rw.WriteHeader(http.StatusNoContent)
}