Exemplo n.º 1
0
func Get(w http.ResponseWriter, r *http.Request) {
	rawuser, oauthErr := oauth2.GetUser(w, r)
	if rawuser == nil || oauthErr != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}

	user := rawuser.(*users.User)

	winUser, err := user.WindowsCredentials()
	if err != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}

	sam := winUser.Sam
	winServer := utils.Env("PLAZA_ADDRESS", "iaas-module")

	request, err := http.NewRequest("GET", "http://"+winServer+":"+utils.Env("PLAZA_PORT", "9090")+"/upload?sam="+url.QueryEscape(sam), nil)
	if err != nil {
		log.Println("Unable de create request ", err)
	}

	request.Header = r.Header
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		log.Println("request error", err)
	}
	if resp.StatusCode == http.StatusTeapot {
		http.Error(w, "", http.StatusSeeOther)
	}
	return
}
Exemplo n.º 2
0
// Get checks a chunk.
// If it doesn't exist then flowjs tries to upload it via Post.
func Get(w http.ResponseWriter, r *http.Request) {
	user, oauthErr := oauth2.GetUser(w, r)
	if user == nil || oauthErr != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}

	chunkPath := filepath.Join(
		kUploadDir,
		user.(*users.User).Id,
		"incomplete",
		r.FormValue("flowFilename"),
		r.FormValue("flowChunkNumber"),
	)
	if _, err := os.Stat(chunkPath); err != nil {
		http.Error(w, "chunk not found", http.StatusSeeOther)
		return
	}
}
Exemplo n.º 3
0
func Post(w http.ResponseWriter, r *http.Request) {
	filename := r.URL.Query()["filename"][0]

	rawuser, oauthErr := oauth2.GetUser(w, r)
	if rawuser == nil || oauthErr != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}

	user := rawuser.(*users.User)

	winUser, err := user.WindowsCredentials()
	if err != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}

	sam := winUser.Sam
	winServer := utils.Env("PLAZA_ADDRESS", "iaas-module")

	request, err := http.NewRequest(
		"POST",
		"http://"+winServer+":"+utils.Env("PLAZA_PORT", "9090")+"/upload?sam="+url.QueryEscape(sam)+"&userId="+url.QueryEscape(user.Id)+"&filename="+url.QueryEscape(filename),
		r.Body,
	)
	if err != nil {
		log.Println("Unable de create request ", err)
	}
	request.Header = r.Header
	client := &http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		log.Println("Unable to send request ", err)
	}

	log.Error(resp)
	http.Error(w, "", resp.StatusCode)
	return
}
Exemplo n.º 4
0
func oAuth2(c *echo.Context, handler echo.HandlerFunc) error {
	r := c.Request()
	w := c.Response()

	user, err := oauth2.GetUser(w, r)
	if err != nil {
		b, fail := err.ToJSON()
		if fail != nil {
			return fail
		}

		w.WriteHeader(err.HTTPStatusCode)
		w.Header().Set("Content-Type", "application/json")
		w.Write(b)
		return nil
	}

	if user != nil {
		c.Set("user", user)
		return handler(c)
	}
	return errors.New("unable to authenticate the user")
}
Exemplo n.º 5
0
func Get(c *echo.Context) error {
	w := c.Response()
	r := c.Request()

	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Cashe-Control", "no-store")
	w.Header().Set("Expires", "Sat, 01 Jan 2000 00:00:00 GMT")
	w.Header().Set("Pragma", "no-cache")

	path := c.Query("path")

	filename := c.Query("filename")
	if len(filename) == 0 {
		return c.JSON(
			http.StatusBadRequest,
			hash{
				"error": "Invalid Path",
			},
		)
	}

	var user *users.User
	var err error

	downloadToken := c.Query("token")
	if len(downloadToken) > 0 {
		user, err = checkDownloadToken(downloadToken, filename)
		if err != nil {
			return c.JSON(
				http.StatusBadRequest,
				hash{
					"error": "Invalid Download Token",
				},
			)
		}
	}

	if user == nil {
		u, fail := oauth2.GetUser(w, r)
		if u == nil {
			return errors.New("no authenticated user")
		}

		if fail != nil {
			return oauthError(c, fail)
		}

		user = u.(*users.User)
	}

	winUser, err := user.WindowsCredentials()
	if err != nil {
		return err
	}

	if filename[0] == '.' {
		path = filepath.Join(
			fmt.Sprintf(
				utils.Env("PLAZA_USER_DIR", "C:\\Users\\%s\\Desktop\\Nanocloud"),
				winUser.Sam,
			),
			filename,
		)
	} else {
		filename = strings.Replace(filename, "/", "\\", -1)
		path = filename
	}

	resp, err := http.Get("http://" + utils.Env("PLAZA_ADDRESS", "iaas-module") + ":" + utils.Env("PLAZA_PORT", "9090") + "/files?create=true&path=" + url.QueryEscape(path))
	if err != nil {
		log.Error(err)
		return apiErrors.WindowsNotOnline.Detail(err.Error())
	}

	if resp.StatusCode == http.StatusNotFound {
		jsonResponse(w, r, http.StatusNotFound, hash{
			"error": "File Not Found",
		})
		return nil
	}

	if resp.StatusCode != http.StatusOK {
		contents, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return errors.New("Unable to retrieve the file")
		}

		return apiErrors.NeedFirstConnection.Detail(string(contents))
	}

	var contentType string
	rContentType, exists := resp.Header["Content-Type"]
	if !exists || len(rContentType) == 0 || len(rContentType[0]) == 0 {
		contentType = "application/octet-stream"
	} else {
		contentType = rContentType[0]
	}

	var sent int64
	var lastBuffSize int64

	contentLength := resp.ContentLength

	var f string
	splt := strings.Split(path, "\\")
	if len(splt) > 0 {
		f = splt[len(splt)-1]
	} else {
		f = path
	}

	w.Header().Set("Content-Type", contentType)
	w.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
	w.Header().Set("Content-Disposition", "attachment; filename=\""+f+"\"")

	var buff []byte

	for sent < contentLength {
		remaining := contentLength - sent
		if remaining > 4096 {
			remaining = 4096
		}

		if buff == nil || remaining != lastBuffSize {
			buff = make([]byte, remaining)
			lastBuffSize = remaining
		}

		nRead, readErr := resp.Body.Read(buff)

		if nRead > 0 {
			nWrite, writeErr := w.Write(buff[0:nRead])
			sent = sent + int64(nWrite)

			if writeErr != nil {
				log.Errorf("Write error: %s\n", writeErr.Error())
				break
			}
		}

		if readErr != nil && readErr.Error() != "EOF" {
			log.Errorf("Read error: %s\n", readErr.Error())
			break
		}
	}
	return nil
}
Exemplo n.º 6
0
// Post tries to get and save a chunk.
func Post(w http.ResponseWriter, r *http.Request) {
	rawuser, oauthErr := oauth2.GetUser(w, r)
	if rawuser == nil || oauthErr != nil {
		http.Error(w, "", http.StatusUnauthorized)
		return
	}
	user := rawuser.(*users.User)
	userPath := filepath.Join(kUploadDir, user.Id)

	// get the multipart data
	err := r.ParseMultipartForm(2 * 1024 * 1024) // chunkSize
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	chunkNum, err := strconv.Atoi(r.FormValue("flowChunkNumber"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	totalChunks, err := strconv.Atoi(r.FormValue("flowTotalChunks"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	filename := r.FormValue("flowFilename")
	// module := r.FormValue("module")

	err = writeChunk(filepath.Join(userPath, "incomplete", filename), strconv.Itoa(chunkNum), r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// it's done if it's not the last chunk
	if chunkNum < totalChunks {
		return
	}

	upPath := filepath.Join(userPath, filename)

	// now finish the job
	err = assembleUpload(userPath, filename)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.WithFields(log.Fields{
			"error": err,
		}).Error("unable to assemble the uploaded chunks")
		return
	}
	log.WithFields(log.Fields{
		"path": upPath,
	}).Info("file uploaded")

	syncOut, err := syncUploadedFile(upPath, user.Sam, user.WindowsPassword)
	if err != nil {
		log.WithFields(log.Fields{
			"output": syncOut,
			"error":  err,
		}).Error("unable to scp the uploaded file to Windows")
	}
	log.WithFields(log.Fields{
		"path":   upPath,
		"output": syncOut,
	}).Info("file synced")
}