Exemplo n.º 1
0
func saveEquipType(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	et := new(EquipType)
	if binderr := c.Bind(et); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	//log.Println(et)

	_, err := ExecDb(db,
		`update equip_type
			set name=$2,
			    is_consumable=$3,
			    is_asset=$4
			where id=$1`,
		id,
		et.Name,
		et.Consumable,
		et.Asset)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, et)
}
Exemplo n.º 2
0
// deleteBot получает команду от веб-клиента (удалить бота) и перенаправляет ее менеджеру ботов
func deleteBot(c *echo.Context) error {
	id := c.Param("id")
	action := "delete"
	MB.SendActionToBot(id, action, nil)

	return c.String(http.StatusOK, "ok\n")
}
Exemplo n.º 3
0
func upload(c *echo.Context) error {
	req := c.Request()
	req.ParseMultipartForm(16 << 20) // Max memory 16 MiB

	// Read form fields
	name := c.Form("name")
	email := c.Form("email")

	// Read files
	files := req.MultipartForm.File["files"]
	for _, f := range files {
		// Source file
		src, err := f.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		// Destination file
		dst, err := os.Create(f.Filename)
		if err != nil {
			return err
		}
		defer dst.Close()

		if _, err = io.Copy(dst, src); err != nil {
			return err
		}
	}
	return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.",
		name, email, len(files))
}
Exemplo n.º 4
0
func RemoveTodo(c echo.Context) error {
	id := c.Param("id")

	tododao.DeleteTodo(id)

	return c.String(http.StatusOK, "")
}
Exemplo n.º 5
0
// Expects username & password to be passed as JSON in the POST body
// This is how Ember does it.
func (s *APIServer) login(c echo.Context) error {
	a := new(AuthInfo)

	if err := c.Bind(a); err != nil {
		return err
	}

	dbuser, err := s.DBH.GetUserByEmail(a.Username)
	if err == nil {
		//if bcrypt.CompareHashAndPassword([]byte(dbuser.Password), []byte(a.Password)) == nil {
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = dbuser.Email
		claims["admin"] = false
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
		//}
	}

	logrus.Infof("Unknown user or bad password for: %s", a.Username)
	return c.String(http.StatusUnauthorized, "Bad username or password")
}
Exemplo n.º 6
0
func Index(c *echo.Context) error {

	authCookie, err := c.Request().Cookie("testcook")
	logrus.Infof(">>> cooki: %+v, err: %+v", authCookie, err)

	dbconn := c.Get("db").(*mgo.Database)
	counts := dbconn.C("counts")

	if err := counts.Insert(&models.TestStruct{"index"}); err != nil {
		c.String(500, fmt.Sprintf("broken: %s", err.Error()))
		return nil
	}

	t, err := template.ParseFiles("static/html/layout.html", "static/html/greet.html", "static/html/mainPage.html")
	if err != nil {
		c.String(500, fmt.Sprintf("broken: %s", err.Error()))
		return nil
	}

	loggedIn := false
	user, ok := c.Get("user").(models.Account)
	if ok {
		loggedIn = user.Username != ""
	}
	args := map[string]interface{}{
		"Username": user.Username,
		"LoggedIn": loggedIn,
		"Logout":   fmt.Sprintf("http://*****:*****@%s", viper.GetString("base_uri"))}
	t.Execute(c.Response(), args)
	return nil
}
Exemplo n.º 7
0
func (tl *TeamLeader) statusHandler(c *echo.Context) error {
	infos := make(map[string]interface{})
	infos["Version"] = "0.001"
	// utils.WriteJson(c, http.StatusOK, infos)
	c.String(http.StatusOK, "Hello World")
	return nil
}
Exemplo n.º 8
0
func login(c *echo.Context) error {
	l := new(loginCreds)
	err := c.Bind(&l)
	if err != nil {
		log.Println("Bind Error:", err.Error())
	}
	//log.Println("Login Credentials", l)

	sqlResult, _ := SQLMap(db,
		`select u.username,u.role,u.site,s.name as sitename
		from users u
			left outer join site s on (s.id=u.site)
		where u.username=$1 and u.passwd=$2`,
		l.Username,
		l.Password)
	log.Println("SQLResult", sqlResult)

	if len(sqlResult) == 1 {
		r := new(loginResponse)
		r.Username = l.Username
		r.Role = sqlResult[0]["role"]
		r.Token = "98023840238402840"
		r.Site = sqlResult[0]["site"]
		r.SiteName = sqlResult[0]["sitename"]
		return c.JSON(http.StatusOK, r)
	} else {
		return c.String(http.StatusUnauthorized, "invalid")
	}
}
Exemplo n.º 9
0
func Welcome(c *echo.Context) error {

	session, err := mgo.Dial("localhost")
	if err != nil {
		panic(err)
	}

	defer session.Close()

	mongo := session.DB("welcome").C("welcomes")

	wm := models.Welcome{
		Id:      "123456",
		Message: "Hello world",
	}

	err = mongo.Insert(&wm)

	if err != nil {
		panic(err)
	}

	result := models.Welcome{}

	err = mongo.Find(bson.M{"id": "123456"}).One(&result)

	if err != nil {
		panic(err)
	}

	return c.String(http.StatusOK, result.Message)
}
Exemplo n.º 10
0
func saveSite(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	site := new(SiteType)
	if binderr := c.Bind(site); binderr != nil {
		log.Println(binderr.Error())
		return binderr
	}
	log.Println(site)

	_, err := ExecDb(db,
		`update site
			set name=$2,
			    address=$3,
			    phone=$4,
			    contactname=$5
			where id=$1`,
		id,
		site.Name,
		site.Address,
		site.Phone,
		site.ContactName)

	if err != nil {
		log.Println(err.Error())
	}

	return c.JSON(http.StatusOK, site)
}
Exemplo n.º 11
0
func largeUnreported(c *echo.Context) error {
	data, err := data.Asset("LargeCommercialBuildingsUnreported.json")
	if err != nil {
		genericError(c)
		return err
	}
	return c.String(http.StatusOK, string(data))
}
Exemplo n.º 12
0
func Move(c *echo.Context) error {
	alpha, _ := strconv.ParseInt(c.Param("alpha"), 10, 64)
	beta, _ := strconv.ParseInt(c.Param("beta"), 10, 64)

	MoveMouse(Orientation{int(alpha), int(beta)}.ToPixels(90, 90))

	return c.String(http.StatusOK, "Hello")
}
Exemplo n.º 13
0
func Reset(c *echo.Context) error {
	err := demo.Reset()
	if err != nil {
		return c.String(1, err.Error())
	}

	return c.String(http.StatusOK, "reset success")
}
Exemplo n.º 14
0
func UserRegister(c *echo.Context) error {
	r, err := uhander.Register(c.Form("u"), "")
	if err == nil {
		return c.String(http.StatusOK, r)
	} else {
		return c.String(http.StatusInternalServerError, err.Error())
	}
}
Exemplo n.º 15
0
func RenderStatic(c echo.Context) error {
	a, err := Asset(fmt.Sprintf("static%s", c.P(0)))

	if err != nil {
		panic(err)
	}

	return c.String(http.StatusOK, string(a))
}
Exemplo n.º 16
0
// Deletes a key and it's value.
func (app *App) Delete(c *echo.Context) error {
	// Get params (check params?)
	user, key := c.Param("user"), c.Param("_*")
	err := app.Store[user].Del("store", key)
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError) // [500]
	}
	return c.String(http.StatusOK, key)
}
Exemplo n.º 17
0
// updateInfBots посылает сигнал всем обработчикам вебсокетов (websockDataBots) о том, что нужно обновить информацию на веб-клиентах
func (mw *ManagerWeb) updateInfBots(c *echo.Context) error {
	// перебрать массив каналов активных вебсокетов
	for i := 0; i < len(mw.Listch); i++ {
		ch := mw.Listch[i]
		ch <- Alarm{} // каждому отправить сигнал, что необходимо обновить информацию на веб-клиенте
	}
	fmt.Println(mw.Listch)
	return c.String(http.StatusOK, "ok\n")
}
Exemplo n.º 18
0
func hello(ctx *echo.Context) error {
	token := ""
	d := utils.GetData(ctx).(utils.Data)
	tok := d.Get("CsrfToken")
	if tok != nil {
		token = tok.(string)
	}
	return ctx.String(http.StatusOK, token)
}
Exemplo n.º 19
0
// Returns the value for the given key
func (app *App) Read(c *echo.Context) error {
	// Look for the value
	data := app.Store[c.Param("user")].Get("store", c.Param("_*"))
	if data == nil {
		return echo.NewHTTPError(http.StatusNotFound)
	}
	// Return a string? raw? mimetype?
	return c.String(http.StatusOK, string(data))
}
Exemplo n.º 20
0
func UserLogin(c *echo.Context) error {
	r, err := uhander.Login(c.Form("username"), c.Form("password"), "")

	if err == nil {
		return c.String(http.StatusOK, r)
	} else {
		return c.String(http.StatusInternalServerError, err.Error())
	}
}
Exemplo n.º 21
0
// getTarget returns the target for the present time
func getTargetHandler(ctx *echo.Context) error {
	db := dbFromContext(ctx)
	t := getTarget(db, ctx.Param("id"))
	if t == "" {
		return ctx.String(404, "Not found")
	}

	return ctx.String(200, t)
}
Exemplo n.º 22
0
func upload(c *echo.Context) error {
	mr, err := c.Request().MultipartReader()
	if err != nil {
		return err
	}

	// Read form field `name`
	part, err := mr.NextPart()
	if err != nil {
		return err
	}
	defer part.Close()
	b, err := ioutil.ReadAll(part)
	if err != nil {
		return err
	}
	name := string(b)

	// Read form field `email`
	part, err = mr.NextPart()
	if err != nil {
		return err
	}
	defer part.Close()
	b, err = ioutil.ReadAll(part)
	if err != nil {
		return err
	}
	email := string(b)

	// Read files
	i := 0
	for {
		part, err := mr.NextPart()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		defer part.Close()

		file, err := os.Create(part.FileName())
		if err != nil {
			return err
		}
		defer file.Close()

		if _, err := io.Copy(file, part); err != nil {
			return err
		}
		i++
	}
	return c.String(http.StatusOK, "Thank You! %s <%s>, %d files uploaded successfully.",
		name, email, i)
}
Exemplo n.º 23
0
func Login(context echo.Context) error {
	_, err := helpers.ValidateJWT(context)
	if err != nil {
		return context.Render(http.StatusOK, "login", os.Getenv("AUTH0_CALLBACK"))
	}

	context.Redirect(http.StatusMovedPermanently, "/frontend")

	return context.String(http.StatusOK, "Done")
}
Exemplo n.º 24
0
// createBot Создать бота и вернуть присвоенный ему ID
func createBot(c *echo.Context) error {
	mlog.Trace("Функция: createBot")
	id, err := newBot()
	if err != nil {
		mlog.Trace("Функция newBot вернула ошибку.")
		return c.String(http.StatusOK, "0")
	}
	mlog.Trace("Функция: createBot. id =", id)
	return c.String(http.StatusOK, strconv.Itoa(id))
}
Exemplo n.º 25
0
// Lists all the keys in the bucket starting from "offset" key up to "limit" number of keys.
// This returns all the keys joined by "\n" so a simple split will give back an array.
func (app *App) List(c *echo.Context) error {
	// Check that we can parse limit, ignore errors
	limit, err := strconv.ParseInt(c.Query("limit"), 10, 64)
	if err != nil {
		limit = LIMIT
	}
	// Get all keys up to limit
	data := app.Store[c.Param("user")].All("store", c.Query("offset"), int(limit))
	// Join the array with new lines
	return c.String(http.StatusOK, strings.Join(data, "\n"))
}
Exemplo n.º 26
0
// CountByInvites count leads by invite
func (h Handler) CountByInvites(c *echo.Context) error {
	hashCode := c.Param("hashCode")
	if hashCode == "" {
		return c.String(http.StatusBadRequest, "hashCode is mandatory")
	}
	count, err := h.ds.CountByInvites(hashCode)
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, count)
}
Exemplo n.º 27
0
func CrossDomain(c *echo.Context) error {
	c.Response().Header().Set("Access-Control-Allow-Origin", "*")
	c.Request().Header.Set("Access-Control-Allow-Credentials", "true")
	c.Request().Header.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	c.Request().Header.Set("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control, X-XSRFToken, Authorization")
	c.Request().Header.Set("Content-Type", "application/json")
	if c.Request().Method == "OPTIONS" {
		c.String(204, "")
	}
	return nil
}
Exemplo n.º 28
0
func connectToServer(c *echo.Context) error {
	mlog.Trace("Функция: connectToServer")
	id, err := strconv.Atoi(c.Param("id")) // преобразовать в int
	if err != nil {
		mlog.Error(err)
	} else {
		if err := connectBotToServer(id); err != nil {
			mlog.Error(err)
		}
	}
	return c.String(http.StatusOK, "ok") // сообщить, что бот изменен
}
Exemplo n.º 29
0
// path /get/sqlitefile/:DeviceID
// example /get/sqlitefile/30404
func getSqliteFile(c *echo.Context) error {
	sf := SqliteFile{DeviceID: c.Param("DeviceID")}
	has, err := g_engine.Get(&sf)
	if err != nil {
		return jsonResp(c, err.Error())
	}
	if !has {
		return jsonResp(c, "not exists")
	}

	return c.String(http.StatusOK, string(sf.Context))
}
Exemplo n.º 30
0
func getSite(c *echo.Context) error {
	id, iderr := strconv.Atoi(c.Param("id"))
	if iderr != nil {
		return c.String(http.StatusNotAcceptable, "Invalid ID")
	}

	sqlResult, err := SQLMapOne(db, `select * from site where id=$1`, id)
	if err != nil {
		log.Println(err.Error())
	}
	return c.JSON(http.StatusOK, sqlResult)
}