Exemplo n.º 1
0
func singleQuery(c *echo.Context) error {
	world := World{}
	if err := randomRow().Scan(&world.Id, &world.RandomNumber); err != nil {
		log.Fatalf("Error scanning world row: %s", err.Error())
	}
	return c.JSON(http.StatusOK, world)
}
Exemplo n.º 2
0
func List(c *echo.Context) error {

	user := c.Get("user").(*users.User)

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

	sessionList, err := sessions.GetAll(winUser.Sam)

	if err != nil {
		log.Error(err)
		return utils.JSON(c, http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": err.Error(),
				},
			},
		})
	}

	var response = make([]hash, len(sessionList))
	for i, val := range sessionList {
		res := hash{
			"id":         val.Id,
			"type":       "session",
			"attributes": val,
		}
		response[i] = res
	}

	return c.JSON(http.StatusOK, hash{"data": response})
}
Exemplo n.º 3
0
func GetUser(c *echo.Context) error {
	userId := c.Param("id")
	if userId == "" {
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "User id needed to retrieve account informations",
				},
			},
		})
	}

	user, err := users.GetUser(userId)
	if err != nil {
		return err
	}

	if user == nil {
		return c.JSON(http.StatusNotFound, hash{
			"error": [1]hash{
				hash{
					"detail": "User Not Found",
				},
			},
		})
	}

	return utils.JSON(c, http.StatusOK, user)
}
Exemplo n.º 4
0
func getGroups(ctx *echo.Context) error {
	list, err := allGroups(dbFromContext(ctx))
	if err != nil {
		return err
	}
	return ctx.JSON(200, list)
}
Exemplo n.º 5
0
func addBook(c *echo.Context) error {
	var b Book
	b.Author = nil

	err := c.Bind(&b)
	if err != nil {
		log.Fatal(err)
		return err
	}

	if b.Author == nil {
		var m Message
		m.Error = "Author can not be empty."
		c.JSON(203, m)
		return ErrAuthorEmpty
	}

	err = c.JSON(201, b)
	if err != nil {
		log.Fatal(err)
		return err
	}

	fmt.Println("Added ", b.Title)
	saveBook(b)
	return nil
}
Exemplo n.º 6
0
func (s *ApiServer) ChangeMasterStatus(c echo.Context) error {
	args := struct {
		Opt  string `json:"opt"`
		Node string `json:"node"`
		Addr string `json:"addr"`
	}{}

	err := c.Bind(&args)
	if err != nil {
		return err
	}

	args.Opt = strings.ToLower(args.Opt)
	if args.Opt != "up" && args.Opt != "down" {
		return errors.New("opt only can be up or down")
	}
	if args.Opt == "down" {
		err = s.proxy.DownMaster(args.Node, args.Addr)
	} else {
		err = s.proxy.UpMaster(args.Node, args.Addr)
	}
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, "ok")
}
Exemplo n.º 7
0
//get nodes status
func (s *ApiServer) GetNodesStatus(c echo.Context) error {
	var masterStatus, slaveStatus DBStatus

	dbStatus := make([]DBStatus, 0, 1)
	nodes := s.proxy.GetAllNodes()

	for nodeName, node := range nodes {
		//get master status
		masterStatus.Node = nodeName
		masterStatus.Address = node.Master.Addr()
		masterStatus.Type = "master"
		masterStatus.Status = node.Master.State()
		masterStatus.LastPing = fmt.Sprintf("%v", time.Unix(node.Master.GetLastPing(), 0))
		masterStatus.MaxConn = node.Cfg.MaxConnNum
		masterStatus.IdleConn = node.Master.IdleConnCount()
		dbStatus = append(dbStatus, masterStatus)

		//get slaves status
		for _, slave := range node.Slave {
			slaveStatus.Node = nodeName
			slaveStatus.Address = slave.Addr()
			slaveStatus.Type = "slave"
			slaveStatus.Status = slave.State()
			slaveStatus.LastPing = fmt.Sprintf("%v", time.Unix(slave.GetLastPing(), 0))
			slaveStatus.MaxConn = node.Cfg.MaxConnNum
			slaveStatus.IdleConn = slave.IdleConnCount()
			dbStatus = append(dbStatus, slaveStatus)
		}
	}
	return c.JSON(http.StatusOK, dbStatus)
}
Exemplo n.º 8
0
// errorHandler will catch all errors returned from handlers and convert them
// into a JSON response. If the error is not from the type HTTPError an internal
// server error will follow.
func errorHandler(err error, c *echo.Context) {
	if httpError, ok := err.(handler.HTTPError); ok {
		c.JSON(httpError.Code, httpError)
		return
	}
	c.Error(errors.New("internal server error"))
}
Exemplo n.º 9
0
func (b *Broker) UndoTaskCount(c *echo.Context) error {
	count, err := b.GetUndoTaskCount()
	if err != nil {
		return c.JSON(http.StatusForbidden, err.Error())
	}
	return c.JSON(http.StatusOK, count)
}
Exemplo n.º 10
0
func ListRunningVM(c *echo.Context) error {
	response, err := GetList()
	if err != nil {
		log.Error("Unable to retrieve VM states list")
		return c.JSON(http.StatusInternalServerError, hash{
			"error": [1]hash{
				hash{
					"detail": "Unable te retrieve states of VMs: " + err.Error(),
				},
			},
		})
	}

	vmList := CheckVMStates(response)
	var res = make([]hash, len(vmList))
	for i, val := range vmList {
		r := hash{
			"id":         val.Name,
			"type":       "vm",
			"attributes": val,
		}
		res[i] = r
	}
	return c.JSON(http.StatusOK, hash{"data": res})
}
Exemplo n.º 11
0
// ApiNextTaskHandler implements method for getting next task from the queue
func (h *handler) ApiNextTaskHandler(c *echo.Context) error {

	enc := json.NewDecoder(c.Request().Body)

	var taskReq common.TaskRequest
	if err := enc.Decode(&taskReq); err != nil {
		c.Request().Body.Close()
		return echo.NewHTTPError(http.StatusBadRequest, "Wrong JSON. Expected gobench.common.TaskRequest")
	}

	c.Request().Body.Close()

	// checks existing test environment by authKey received by client
	ok, err := h.back.Model.TestEnvironment.Exist(taskReq.AuthKey)
	if err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError)
	}

	if !ok {
		return echo.NewHTTPError(http.StatusBadRequest, "Wrong authKey!")
	}

	// retrives single task
	taskRow, err := h.back.Model.Task.Next(taskReq.AuthKey)
	if err != nil {
		if err == model.ErrNotFound {
			return echo.NewHTTPError(http.StatusNoContent)
		}
		return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
	}

	task := common.TaskResponse{Id: taskRow.Id.Hex(), PackageName: taskRow.PackageName, Type: []string{"benchmark"}}

	return c.JSON(http.StatusOK, task)
}
Exemplo n.º 12
0
func ProjectGetAll(ctx *echo.Context) error {
	interactor := ctx.Get("ProjectInteractor").(*usecases.ProjectInteractor)

	result := interactor.List()

	return ctx.JSON(http.StatusOK, result)
}
Exemplo n.º 13
0
func (app *App) putValues(ctx *echo.Context) (err error) {
	key := ctx.Param("key")
	value, err := readBody(ctx.Request())
	if err != nil {
		return err
	}

	app.Lock()
	entry, ok := app.store[key]
	if !ok {
		entry = newEntry()
		entry.Lock()
		app.store[key] = entry
	} else {
		entry.Lock()
	}
	app.Unlock()

	entry.value = value
	entry.lockID = generateID(32)
	app.cond.Broadcast()
	entry.Unlock()

	response := map[string]interface{}{}
	response["lock_id"] = entry.lockID
	ctx.JSON(200, response)
	return
}
Exemplo n.º 14
0
func IndexCampaign(c *echo.Context) error {
	// GET /campaign
	// returns JSON Array of Campaigns

	// Get User id from JWT Token

	userid := 5

	rows, err := db.Query("SELECT * FROM campaigns WHERE userid = $1", userid)

	if err != nil {
		log.Fatal(err)
	}

	defer rows.Close()

	var campaigns Campaigns

	for rows.Next() {
		var campaign Campaign
		err := rows.Scan(&campaign.Id, &campaign.UserId, &campaign.Name)
		if err != nil {
			log.Fatal(err)
		}

		campaigns = append(campaigns, campaign)
	}

	return c.JSON(http.StatusOK, campaigns)
}
Exemplo n.º 15
0
func GetDownloadToken(c *echo.Context) error {
	filename := c.Query("filename")
	if len(filename) == 0 {
		return c.JSON(
			http.StatusBadRequest,
			hash{
				"error": "filename not specified",
			},
		)
	}

	accessToken, fail := oauth2.GetAccessToken(c.Request())
	if fail != nil {
		return oauthError(c, fail)
	}

	user := c.Get("user").(*users.User)
	token, err := createDownloadToken(user, accessToken, filename)
	if err != nil {
		return err
	}
	return c.JSON(
		http.StatusOK,
		hash{
			"token": token,
		},
	)
}
Exemplo n.º 16
0
Arquivo: app.go Projeto: q1t/movielist
func (app *App) userLogin(c *echo.Context) error {
	userData := c.Get("userInput").(userData)
	var response struct {
		Bearer    string `json:"bearer,omitempty"`
		Timestamp int64  `json:"timestamp,omitempty"`
		Error     string `json:"error,omitempty"`
	}

	// Handle credentials here
	// If everything is alright (pass is correct)
	// proceed further

	user, err := FindUserByUsername(app.DB, userData.Username)

	if err == nil {
		if err := bcrypt.CompareHashAndPassword(
			[]byte(user.Password),
			[]byte(userData.Password),
		); err == nil {
			response.Bearer = user.GenSignedString(app.SigningKey)
			response.Timestamp = time.Now().Unix()
			// user is found and password is correct
			return c.JSON(http.StatusOK, response)
		}
	}

	response.Error = "Incorrect credentials"
	return c.JSON(http.StatusOK, response)
}
Exemplo n.º 17
0
func CreateAccount(c *echo.Context) error {
	logrus.Infof("create account")
	caRequest, err := validateCreateAccount(c.Request().Body)
	if err != nil {
		logrus.Errorf("failed create account input validation %s", err.Error())
		c.JSON(400, Response{})
		return nil
	}
	db := c.Get("db").(*mgo.Database)
	_, err = models.LoadAccount(db, caRequest.Username)
	if err == nil {
		logrus.Errorf("account taken: %s", caRequest.Username)
		c.JSON(409, Response{})
		return nil
	} else if err != models.AccountNotFound && err != nil {
		logrus.Errorf("db error in create account: %s", err.Error())
		c.JSON(500, Response{})
		return nil
	}

	a := models.Account{
		Username: caRequest.Username,
		Password: caRequest.Password,
	}
	err = models.CreateAccount(db, a)
	if err != nil {
		logrus.Errorf("failed to create account: %s", err.Error())
		c.JSON(500, Response{})
		return nil
	}

	c.JSON(200, Response{true, a})
	return nil
}
Exemplo n.º 18
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.º 19
0
func (s *ApiServer) SaveProxyConfig(c echo.Context) error {
	err := s.proxy.SaveProxyConfig()
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, "ok")
}
Exemplo n.º 20
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.º 21
0
func putHandler(c echo.Context) error {
	var val map[string]interface{}

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

	cfg := c.Get("config").(*Config)

	key := c.Param("key")
	obj, err := Put(cfg, key, val)

	if err != nil {
		// Failed validation.
		if errs, ok := err.(ResultErrors); ok {
			return c.JSON(StatusUnprocessableEntity, errs)
		}

		return err
	}

	// No change.
	if obj == nil {
		return c.NoContent(http.StatusNoContent)
	}

	return c.JSON(http.StatusOK, obj)
}
Exemplo n.º 22
0
func getAllEquipTypes(c *echo.Context) error {
	sqlResult, err := SQLMap(db, `select * from equip_type`)
	if err != nil {
		log.Println(err.Error())
	}
	return c.JSON(http.StatusOK, sqlResult)
}
Exemplo n.º 23
0
func getGroupHandler(ctx *echo.Context) error {
	g, err := getGroup(dbFromContext(ctx), ctx.Param("id"))
	if err != nil {
		return err
	}
	return ctx.JSON(200, g)
}
Exemplo n.º 24
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.º 25
0
func UserList(ctx *echo.Context) error {
	interactor := ctx.Get("UserInteractor").(*usecases.UserInteractor)

	result := interactor.List()

	return ctx.JSON(http.StatusOK, result)
}
Exemplo n.º 26
0
func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {
		// Create token
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = "Jon Snow"
		claims["admin"] = true
		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,
		})
	}

	return echo.ErrUnauthorized
}
Exemplo n.º 27
0
// Add a new log entry to the database
func Add(c *echo.Context) error {
	history := histories.History{}

	err := utils.ParseJSONBody(c, &history)
	if err != nil {
		return err
	}

	if history.UserId == "" || history.ConnectionId == "" || history.StartDate == "" || history.EndDate == "" {
		log.Error("Missing one or several parameters to create entry")
		return c.JSON(http.StatusBadRequest, hash{
			"error": [1]hash{
				hash{
					"detail": "Missing parameters",
				},
			},
		})
	}

	err = utils.ParseJSONBody(c, &history)
	newHistory, err := histories.CreateHistory(
		history.UserId,
		history.ConnectionId,
		history.StartDate,
		history.EndDate,
	)

	if err != nil {
		return err
	}

	return utils.JSON(c, http.StatusCreated, newHistory)
}
Exemplo n.º 28
0
func EnvironmentGetAll(ctx *echo.Context) error {
	interactor := ctx.Get("EnvironmentInteractor").(*usecases.EnvironmentInteractor)

	result := interactor.List()

	return ctx.JSON(http.StatusOK, result)
}
Exemplo n.º 29
0
func CustomHTTPErrorHandler(err error, c echo.Context) {
	code := http.StatusInternalServerError
	response := ErrResponse{}

	switch v := err.(type) {
	case types.ErrNotFound:
		code = http.StatusNotFound
		response = ErrResponse{"error": v.Error()}
	case types.ErrConflict:
		code = http.StatusConflict
		response = ErrResponse{"error": v.Error()}
	case types.ErrValidation:
		code = http.StatusUnprocessableEntity
		response = ErrResponse{"error": v.Errors}
	case *echo.HTTPError:
		response = ErrResponse{"error": v.Message}
	default:
		response = ErrResponse{"error": v.Error()}
	}

	if !c.Response().Committed {
		if c.Request().Method == echo.HEAD { // Issue #608
			c.NoContent(code)
		} else {
			c.JSON(code, response)
		}
	}
}
Exemplo n.º 30
0
//GET /activities
func (a *AppContext) GetActivities(c *echo.Context) error {

	var activities []st.Activity
	var err error

	var query = c.Request().URL.Query().Get("q")

	//Check for token header

	SetDefaultHeaders(c)

	//Get quote from database
	if query != "" {
		//Seperate search terms and put them into a string array
		activities, err = a.Storage.SearchActivities(strings.Split(query, ","))
	} else {
		activities, err = a.Storage.FindAllActivities()
	}

	if err != nil {
		return c.JSON(http.StatusBadRequest, Error{"Activities could not be found.", err})
	}

	return c.JSON(http.StatusOK, FormatResponse("Fetched", activities))
}