Esempio n. 1
1
func (s *Server) DeleteMessageHandler(w http.ResponseWriter, r *http.Request) {
	login, err := getYandexLogin(r)
	if login == "" || err != nil {
		writeError(w, 403, "forbidden")
		return
	}

	subject := r.FormValue("subject")
	if subject != "" {
		log.Printf("DELETE login=%s subject=%s", login, subject)
		err = s.deleteMessagesBySubject(login, subject)
		if err != nil {
			writeError(w, 500, "failed to delete message: "+err.Error())
			return
		}
	}

	id := r.FormValue("id")
	if id != "" {
		log.Printf("DELETE login=%s id=%s", login, id)
		err = s.deleteMessagesByID(login, id)
		if err != nil {
			writeError(w, 500, "failed to delete message: "+err.Error())
			return
		}
	}

	writeResponse(w, 200, map[string]interface{}{
		"status": "success",
	})
}
Esempio n. 2
0
// key HandleFunc for the http /key endpoint. This only happens if the client
// doesn't support websockets.
func (t *tbfe) key(w http.ResponseWriter, req *http.Request) {
	log.Debug("key: %s", req)
	kc := req.FormValue("keyCode")
	var kp keys.KeyPress
	v, _ := strconv.ParseInt(kc, 10, 32)

	if req.FormValue("altKey") == "true" {
		kp.Alt = true
	}
	if req.FormValue("ctrlKey") == "true" {
		kp.Ctrl = true
	}
	if req.FormValue("metaKey") == "true" {
		kp.Super = true
	}
	if req.FormValue("shiftKey") == "true" {
		kp.Shift = true
	}

	if !kp.Shift {
		v = int64(unicode.ToLower(rune(v)))
	}
	kp.Key = keys.Key(v)
	kp.Text = string(v)
	backend.GetEditor().HandleInput(kp)
}
Esempio n. 3
0
func (c *ClassifierHandler) ServeHTTP(w http.ResponseWriter,
	req *http.Request) {
	sample := core.NewSample()
	if req.Method != "POST" {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	features := req.FormValue("features")
	if len(features) == 0 {
		http.Error(w, "need input features", http.StatusInternalServerError)
		return
	}
	fs := make(map[string]float64)
	err := json.Unmarshal([]byte(features), &fs)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	for k, v := range fs {
		f := core.Feature{
			Id:    util.Hash(k),
			Value: v,
		}
		sample.AddFeature(f)
	}
	p := c.classifier.Predict(sample)
	output, err := json.Marshal(map[string]interface{}{
		"prediction": p,
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprint(w, output)
}
Esempio n. 4
0
func invalidate(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	ii := instance_mgt.GetByContext(c)

	mkk := r.FormValue("mkk")
	sii := r.FormValue("senderInstanceId")

	if ll > 2 {
		aelog.Infof(c, " %s  ---------  %s\n", sii, mkk)
	}

	w.WriteHeader(http.StatusOK)

	if ii.InstanceID == sii {
		w.Write([]byte("Its ME " + mkk + "\n"))
		w.Write([]byte(sii))
	} else {
		w.Write([]byte("got it " + mkk + "\n"))
		w.Write([]byte(sii + "\n"))
		w.Write([]byte(ii.InstanceID))
	}

}
Esempio n. 5
0
func PortBindingDelete(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	port := params.Get(":port")
	host := r.FormValue("host")
	hostPort := r.FormValue("host_port")

	i, binding, err := getPortBinding(port, false)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}

	if binding == nil {
		w.Write([]byte("{}"))
		return
	}
	if host != "" && hostPort != "" {
		binding.RemoveBackend(host, hostPort)
	}
	currentHost, err := h.GetCurrentHost()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	if len(binding.Backends) == 0 || (host == "" && hostPort == "") {
		binding.Stop()
		copy(currentHost.PortBindings[i:], currentHost.PortBindings[i+1:])
		currentHost.PortBindings[len(currentHost.PortBindings)-1] = nil
		currentHost.PortBindings = currentHost.PortBindings[:len(currentHost.PortBindings)-1]
	}
	w.Write([]byte("{\"success\": true}"))
	currentHost.Persist()
}
Esempio n. 6
0
func Register(w http.ResponseWriter, r *http.Request) {

	user := models.User{}

	if r.FormValue("displayName") != "" {
		user.DisplayName = r.FormValue("displayName")
	} else {
		user.DisplayName = "NULL"
	}

	_email := r.FormValue("email")
	if _email != "" {
		user.Email.Scan(_email)
	}

	if r.FormValue("password") != "" {
		user.Password = r.FormValue("password")
	} else {
		user.Password = "******"
	}

	createUserToken(&user)

	if err := repository.CreateUser(&user).Error; err != nil {
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(err)
		return
	}

	log.Println(user)

	json.NewEncoder(w).Encode(user)
}
Esempio n. 7
0
func (srv *Server) serveHTTP(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	srv.mutex.Lock()
	defer srv.mutex.Unlock()
	action := req.FormValue("Action")
	if action == "" {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "MissingAction",
			Message:    "Missing action",
		})
	}
	if a, ok := actions[action]; ok {
		reqId := fmt.Sprintf("req%0X", srv.reqId)
		srv.reqId++
		if resp, err := a(srv, w, req, reqId); err == nil {
			if err := xml.NewEncoder(w).Encode(resp); err != nil {
				panic(err)
			}
		} else {
			switch err.(type) {
			case *iam.Error:
				srv.error(w, err.(*iam.Error))
			default:
				panic(err)
			}
		}
	} else {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "InvalidAction",
			Message:    "Invalid action: " + action,
		})
	}
}
Esempio n. 8
0
func (srv *Server) createGroup(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) {
	if err := srv.validate(req, []string{"GroupName"}); err != nil {
		return nil, err
	}
	name := req.FormValue("GroupName")
	path := req.FormValue("Path")
	for _, group := range srv.groups {
		if group.Name == name {
			return nil, &iam.Error{
				StatusCode: 409,
				Code:       "EntityAlreadyExists",
				Message:    fmt.Sprintf("Group with name %s already exists.", name),
			}
		}
	}
	group := iam.Group{
		Id:   "GROUP " + reqId + "EXAMPLE",
		Arn:  fmt.Sprintf("arn:aws:iam:::123456789012:group%s%s", path, name),
		Name: name,
		Path: path,
	}
	srv.groups = append(srv.groups, group)
	return iam.CreateGroupResp{
		RequestId: reqId,
		Group:     group,
	}, nil
}
Esempio n. 9
0
func cookiehmac(res http.ResponseWriter, req *http.Request) {
	cookie, err := req.Cookie("session")
	if err == http.ErrNoCookie {
		cookie = &http.Cookie{
			Name:  "session",
			Value: "",
			//Secure: true,
			HttpOnly: true,
		}
	}
	if req.FormValue("name") != "" {
		needsSalt := req.FormValue("name")
		cookie.Value = needsSalt + " | " + getCode(needsSalt)
	}
	fmt.Fprint(res, `
		<!DOCTYPE html>
		<html>
			<body>
				<form method = "POST">
					`+cookie.Value+`
					<input type = "text" name = "name">
					<input type = "submit">
				</form>
			</body>
		</htmlcd>
	`)
}
Esempio n. 10
0
func registerHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Query()["post"] != nil {
		switch tryRegister(r.FormValue("email")) {
		case 0:
			displayPage(w, "generic",
				GenericPage{
					Title: "Register",
					Body:  "You are registered, please check your inbox"},
			)
		case 1:
			displayPage(w, "generic",
				GenericPage{
					Title: "Register",
					Body:  "Failed to register. Your email seems to be invalid!"},
			)
		case 2:
			displayPage(w, "generic",
				GenericPage{
					Title: "Register",
					Body:  "You are already registered!"},
			)
		}
	} else {
		displayPage(w, "register", nil)
	}
}
Esempio n. 11
0
func getID(w http.ResponseWriter, r *http.Request) string {

	var userUUID string
	var cookie *http.Cookie

	cookie, err := r.Cookie("session-id")

	if err == http.ErrNoCookie {
		userUUID = r.FormValue("id")

		if userUUID == "" {
			uuid, _ := uuid.NewV4()
			userUUID = uuid.String()
			http.Redirect(w, r, "/?id="+userUUID, 303)
		}

		modelForCookie := model{
			Name:  "session-id",
			State: false,
			Pictures: []string{
				"one.jpg",
			},
			ID: userUUID,
		}

		makeCookie(modelForCookie, userUUID, r)
		http.SetCookie(w, cookie)

		return userUUID

	}
	return cookie.Value
}
Esempio n. 12
0
func shipoptionselect(w http.ResponseWriter, q *http.Request) {
	if q.Method == "POST" {
		err := q.ParseForm()
		if err != nil {
			// Handle error
			fmt.Println(err)
		}
		session, _ := store.Get(q, sessionname)

		order := *session.Values["Order"].(*Order)
		//here put shipping method and price shipping
		order.Shipping = Shipping{
			ShippingMethod: q.FormValue("shippingOfferingId"),
			ShippingCost:   0,
		}
		session.Values["Order"] = order
		session.Save(q, w)
		http.Redirect(w, q, "/payselect", http.StatusFound)
	} else {
		session, _ := store.Get(q, sessionname)
		order := *session.Values["Order"].(*Order)
		newmap := map[string]interface{}{"adress": order.ShippingAdress}
		render(w, "shipoptionselect", newmap)
	}

}
Esempio n. 13
0
func addItem(w http.ResponseWriter, q *http.Request) {
	//check if SKU exist, if not then generate SKU
	err := q.ParseMultipartForm(32 << 20)

	if err != nil {
		// Handle error
		fmt.Println(err)
	}
	if q.FormValue("SKU") != "" {

		slice := []string{"Image", "Image1", "Image2", "Image3"}

		images := checkifImageneedUpload(q, slice, q.FormValue("SKU"))

		product := Product{
			Title:       q.FormValue("Title"),
			Price:       q.FormValue("Price"),
			SKU:         q.FormValue("SKU"),
			Image:       images,
			Description: q.FormValue("Description"),
		}

		db := dbinit()
		defer db.Close()
		_, err = r.Db("goShop").Table("items").Insert(product).RunWrite(db)
		if err != nil {
			log.Println(err)
		}

		//fmt.Println(q.FormValue("cat"))

		http.Redirect(w, q, "/items", http.StatusFound)
	}

}
Esempio n. 14
0
func (h *ManagerKickHandler) ServeHTTP(
	w http.ResponseWriter, req *http.Request) {
	h.mgr.Kick(req.FormValue("msg"))
	MustEncode(w, struct {
		Status string `json:"status"`
	}{Status: "ok"})
}
Esempio n. 15
0
// Disable or enable the sniffer
func statusSnifferHandler(w http.ResponseWriter, r *http.Request) {
	if r.FormValue("status") == "stop" {
		snifferActive = false
	} else {
		snifferActive = true
	}
}
Esempio n. 16
0
func pubHandler(w http.ResponseWriter, req *http.Request) {
	name := req.FormValue("topic")
	if name == "" {
		http.Error(w, "missing topic", 403)
		return
	}
	size, err := strconv.Atoi(req.FormValue("size"))
	if err != nil {
		http.Error(w, err.Error(), 403)
		return
	}

	var (
		msg    *message.Ins
		header message.Header
		msgs   = make([]*message.Ins, 0, size)
	)
	for !logex.Equal(err, io.EOF) {
		msg, err = message.ReadMessage(&header, req.Body, message.RF_DEFAULT)
		if err != nil {
			break
		}
		msgs = append(msgs, msg)
	}

	t, err := getTopic(name)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	t.PutSync(msgs)
	w.Write([]byte("hello"))
}
Esempio n. 17
0
func (srv *Server) createUser(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) {
	if err := srv.validate(req, []string{"UserName"}); err != nil {
		return nil, err
	}
	path := req.FormValue("Path")
	if path == "" {
		path = "/"
	}
	name := req.FormValue("UserName")
	for _, user := range srv.users {
		if user.Name == name {
			return nil, &iam.Error{
				StatusCode: 409,
				Code:       "EntityAlreadyExists",
				Message:    fmt.Sprintf("User with name %s already exists.", name),
			}
		}
	}
	user := iam.User{
		Id:   "USER" + reqId + "EXAMPLE",
		Arn:  fmt.Sprintf("arn:aws:iam:::123456789012:user%s%s", path, name),
		Name: name,
		Path: path,
	}
	srv.users = append(srv.users, user)
	return iam.CreateUserResp{
		RequestId: reqId,
		User:      user,
	}, nil
}
Esempio n. 18
0
func (h httpAddVolumeHandler) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
	var (
		ok       bool
		err      error
		storeErr StoreError
		vid      int64
		res      = map[string]interface{}{"ret": RetOK}
	)
	if r.Method != "POST" {
		http.Error(wr, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer HttpPostWriter(r, wr, time.Now(), res)
	if vid, err = strconv.ParseInt(r.FormValue("vid"), 10, 32); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", r.FormValue("vid"),
			err)
		res["ret"] = RetParamErr
		return
	}
	if _, err = h.s.AddVolume(int32(vid)); err != nil {
		if storeErr, ok = err.(StoreError); ok {
			res["ret"] = int(storeErr)
		} else {
			res["ret"] = RetInternalErr
		}
	}
	return
}
Esempio n. 19
0
func (srv *Server) getUserPolicy(w http.ResponseWriter, req *http.Request, reqId string) (interface{}, error) {
	if err := srv.validate(req, []string{"UserName", "PolicyName"}); err != nil {
		return nil, err
	}
	policyName := req.FormValue("PolicyName")
	userName := req.FormValue("UserName")
	index := -1
	for i, policy := range srv.userPolicies {
		if policyName == policy.Name && userName == policy.UserName {
			index = i
			break
		}
	}
	if index < 0 {
		return nil, &iam.Error{
			StatusCode: 404,
			Code:       "NoSuchEntity",
			Message:    "No such user policy",
		}
	}
	return iam.GetUserPolicyResp{
		Policy:    srv.userPolicies[index],
		RequestId: reqId,
	}, nil
}
Esempio n. 20
0
func (h httpCompactVolumeHandler) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
	var (
		err error
		vid int64
		res = map[string]interface{}{"ret": RetOK}
	)
	if r.Method != "POST" {
		http.Error(wr, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer HttpPostWriter(r, wr, time.Now(), res)
	if vid, err = strconv.ParseInt(r.FormValue("vid"), 10, 32); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", r.FormValue("vid"),
			err)
		res["ret"] = RetParamErr
		return
	}
	// long time processing, not block, we can from info stat api get status.
	go func() {
		if err = h.s.CompactVolume(int32(vid)); err != nil {
			log.Errorf("s.CompactVolume() error(%v)", err)
		}
	}()
	res["ret"] = RetOK
	return
}
Esempio n. 21
0
func UpdateUser(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userId, _ := strconv.Atoi(vars["userId"])
	user := repository.GetUserById(userId)

	// oldPassword := r.FormValue("oldPassword")
	// newPassword := r.FormValue("newPassword")

	// if oldPassword != "" && newPassword != "" {
	// 	result := updatePassword(&user, oldPassword, newPassword)

	// 	if result {
	// 		w.Write([]byte(`{"result":true}`))
	// 	} else {
	// 		w.Write([]byte(`{"result":false}`))
	// 	}

	// 	return
	// }

	// User is exist
	displayName := r.FormValue("displayName")
	email := r.FormValue("email")
	if displayName != "" {
		user.DisplayName = displayName
	}
	user.Email.Scan(email)

	repository.UpdateUser(&user)
	json.NewEncoder(w).Encode(user)
}
Esempio n. 22
0
func handleSearch(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	query := req.FormValue("q")
	model := &searchModel{
		Query: query,
	}

	index, err := search.Open("movies")
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	iterator := index.Search(ctx, query, nil)
	for {
		var movie Movie
		_, err := iterator.Next(&movie)
		if err == search.Done {
			break
		} else if err != nil {
			http.Error(res, err.Error(), 500)
			return
		}
		model.Movies = append(model.Movies, movie)
	}

	err = tpl.ExecuteTemplate(res, "search", model)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
}
Esempio n. 23
0
func PortBindingCreate(w http.ResponseWriter, r *http.Request) {
	port := r.FormValue("port")
	host := r.FormValue("host")
	hostPort := r.FormValue("host_port")
	currentHost, err := h.GetCurrentHost()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	_, binding, err := getPortBinding(port, true)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	binding.AddBackend(host, hostPort)
	err = currentHost.Persist()
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	go binding.Start()
	content, err := json.Marshal(binding)
	if err != nil {
		w.Write([]byte("{\"error\": \"" + err.Error() + "\"}"))
		return
	}
	log.Println("exposed " + binding.String())
	w.Write(content)
}
Esempio n. 24
0
func signupTeamConfirm(c *api.Context, w http.ResponseWriter, r *http.Request) {
	email := r.FormValue("email")

	page := NewHtmlTemplatePage("signup_team_confirm", "Signup Email Sent")
	page.Props["Email"] = email
	page.Render(c, w)
}
Esempio n. 25
0
func getID(res http.ResponseWriter, req *http.Request) (string, error) {
	var id, origin string
	var cookie *http.Cookie
	// try to get the id from the COOKIE
	origin = "COOKIE"
	cookie, err := req.Cookie("session-id")
	if err == http.ErrNoCookie {
		// try to get the id from the URL
		origin = "URL"
		id := req.FormValue("id")
		if id == "" {
			// no id, so create one BRAND NEW
			origin = "BRAND NEW VIA LOGOUT"
			log.Println("ID CAME FROM", origin)
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return id, errors.New("ERROR: redirect to /logout because no session id accessible")
		}
		// try to store id for later use in COOKIE
		cookie = &http.Cookie{
			Name:  "session-id",
			Value: id,
			// Secure: true,
			HttpOnly: true,
		}
		http.SetCookie(res, cookie)
	}
	id = cookie.Value
	log.Println("ID CAME FROM", origin)
	return id, nil
}
Esempio n. 26
0
func handleOauth2Callback(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	api := NewGithubAPI(ctx)
	// get the session
	session := getSession(ctx, req)

	state := req.FormValue("state")
	code := req.FormValue("code")

	if state != session.State {
		http.Error(res, "invalid state", 401)
		return
	}

	accessToken, err := api.getAccessToken(state, code)
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}
	api.accessToken = accessToken

	username, err := api.getUsername()
	if err != nil {
		http.Error(res, err.Error(), 500)
		return
	}

	session.Username = username
	session.AccessToken = accessToken
	putSession(ctx, res, session)

	delayedGetStats.Call(ctx, accessToken, username)
	http.Redirect(res, req, "/github-info", 302)

}
Esempio n. 27
0
func writeJson(w http.ResponseWriter, r *http.Request, obj interface{}) (err error) {
	w.Header().Set("Content-Type", "application/javascript")
	var bytes []byte
	if r.FormValue("pretty") != "" {
		bytes, err = json.MarshalIndent(obj, "", "  ")
	} else {
		bytes, err = json.Marshal(obj)
	}
	if err != nil {
		return
	}
	callback := r.FormValue("callback")
	if callback == "" {
		_, err = w.Write(bytes)
	} else {
		if _, err = w.Write([]uint8(callback)); err != nil {
			return
		}
		if _, err = w.Write([]uint8("(")); err != nil {
			return
		}
		fmt.Fprint(w, string(bytes))
		if _, err = w.Write([]uint8(")")); err != nil {
			return
		}
	}
	return
}
Esempio n. 28
0
func deleteData(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)
	u := user.Current(ctx)
	keyVal := req.FormValue("keyVal")
	key, err := datastore.DecodeKey(keyVal)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	var l list
	err = datastore.Get(ctx, key, &l)
	if err != nil {
		http.Error(res, "Invalid data", http.StatusBadRequest)
		log.Warningf(ctx, err.Error())
		return
	}
	if l.Owner != u.Email {
		http.Error(res, "Not authorized to delete this entry", http.StatusUnauthorized)
		log.Warningf(ctx, err.Error())
		return
	}
	err = datastore.Delete(ctx, key)
	if err != nil {
		http.Error(res, "Server Error", http.StatusInternalServerError)
		log.Errorf(ctx, err.Error())
		return
	}
}
Esempio n. 29
0
func (api *API) query(r *http.Request) (interface{}, *apiError) {
	var ts model.Time
	if t := r.FormValue("time"); t != "" {
		var err error
		ts, err = parseTime(t)
		if err != nil {
			return nil, &apiError{errorBadData, err}
		}
	} else {
		ts = api.now()
	}

	qry, err := api.QueryEngine.NewInstantQuery(r.FormValue("query"), ts)
	if err != nil {
		return nil, &apiError{errorBadData, err}
	}

	res := qry.Exec()
	if res.Err != nil {
		switch res.Err.(type) {
		case promql.ErrQueryCanceled:
			return nil, &apiError{errorCanceled, res.Err}
		case promql.ErrQueryTimeout:
			return nil, &apiError{errorTimeout, res.Err}
		}
		return nil, &apiError{errorExec, res.Err}
	}
	return &queryData{
		ResultType: res.Value.Type(),
		Result:     res.Value,
	}, nil
}
Esempio n. 30
0
func (s *GardenServer) handleSetGraceTime(w http.ResponseWriter, r *http.Request) {
	handle := r.FormValue(":handle")

	var graceTime time.Duration
	if !s.readRequest(&graceTime, w, r) {
		return
	}

	hLog := s.logger.Session("set-grace-time", lager.Data{
		"handle": handle,
	})

	container, err := s.backend.Lookup(handle)
	if err != nil {
		s.writeError(w, err, hLog)
		return
	}

	container.SetGraceTime(graceTime)

	s.bomberman.Defuse(container.Handle())
	s.bomberman.Strap(container)

	s.writeSuccess(w)
}