Example #1
1
// Info endpoint api mocking
//  	curl http://127.0.0.1:8888/api/v0/malware/info/1234567890abcdef
func infoAPI(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	hash := vars["hash"]

	if hash == "1234567890abcdef" {
		a := ArtRes{
			Ssdeep:    "1234567890",
			Md5:       "1234567890",
			Sha1:      "1234567890",
			Sha256:    "1234567890",
			Sha512:    "1234567890",
			Format:    "pe",
			Symbols:   []string{"a", "b"},
			Imports:   []string{"a", "b"},
			Sections:  []string{"a", "b"},
			Arch:      "amd64",
			Strain:    "",
			Mutations: []string{"0987654321", "5647382910", "4536789013"},
			Siblings:  []string{""},
		}

		v := DataRes{
			302,
			"Asset already analysed",
			a,
		}

		json.NewEncoder(w).Encode(v)
		return
	} else {
		v := SearchRes{404, "This element does not exist", ""}
		json.NewEncoder(w).Encode(v)
		return
	}
}
Example #2
0
func queryServerIDRetriever(w http.ResponseWriter, ids []string) {
	s := make(chan map[string]string, len(ids))
	db.ServerDB.GetHostsAndGameFromIDAPIQuery(s, ids)
	hostsgames := <-s
	if len(hostsgames) == 0 {
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(models.GetDefaultServerList()); err != nil {
			writeJSONEncodeError(w, err)
		}
		return
	}
	serverlist, err := steam.Query(hostsgames)
	if err != nil {
		setNotFoundAndLog(w, err)
		if err := json.NewEncoder(w).Encode(models.GetDefaultServerList()); err != nil {
			writeJSONEncodeError(w, err)
			return
		}
		return
	}
	if err := json.NewEncoder(w).Encode(serverlist); err != nil {
		writeJSONEncodeError(w, err)
		logger.LogWebError(err)
	}
}
Example #3
0
func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var todoId int
	var err error
	if todoId, err = strconv.Atoi(vars["todoId"]); err != nil {
		panic(err)
	}

	todo := RepoFindTodo(todoId)
	if todo.Id > 0 {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(todo); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
Example #4
0
func (s *ESAPIV0) UpdateIndexSettings(name string, settings map[string]interface{}) error {

	log.Debug("update index: ", name, settings)
	cleanSettings(settings)
	url := fmt.Sprintf("%s/%s/_settings", s.Host, name)

	if _, ok := settings["settings"].(map[string]interface{})["index"]; ok {
		if set, ok := settings["settings"].(map[string]interface{})["index"].(map[string]interface{})["analysis"]; ok {
			log.Debug("update static index settings: ", name)
			staticIndexSettings := getEmptyIndexSettings()
			staticIndexSettings["settings"].(map[string]interface{})["index"].(map[string]interface{})["analysis"] = set
			Post(fmt.Sprintf("%s/%s/_close", s.Host, name), s.Auth, "", s.HttpProxy)
			body := bytes.Buffer{}
			enc := json.NewEncoder(&body)
			enc.Encode(staticIndexSettings)
			bodyStr, err := Request("PUT", url, s.Auth, &body, s.HttpProxy)
			if err != nil {
				log.Error(bodyStr, err)
				panic(err)
				return err
			}
			delete(settings["settings"].(map[string]interface{})["index"].(map[string]interface{}), "analysis")
			Post(fmt.Sprintf("%s/%s/_open", s.Host, name), s.Auth, "", s.HttpProxy)
		}
	}

	log.Debug("update dynamic index settings: ", name)

	body := bytes.Buffer{}
	enc := json.NewEncoder(&body)
	enc.Encode(settings)
	_, err := Request("PUT", url, s.Auth, &body, s.HttpProxy)

	return err
}
Example #5
0
func listContainersHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	address := r.URL.Query().Get(":address")
	if address != "" {
		node, err := mainDockerProvisioner.Cluster().GetNode(address)
		if err != nil {
			return err
		}
		hasAccess := permission.Check(t, permission.PermNodeRead,
			permission.Context(permission.CtxPool, node.Metadata["pool"]))
		if !hasAccess {
			return permission.ErrUnauthorized
		}
		containerList, err := mainDockerProvisioner.listContainersByHost(address)
		if err != nil {
			return err
		}
		return json.NewEncoder(w).Encode(containerList)
	}
	appName := r.URL.Query().Get(":appname")
	a, err := app.GetByName(appName)
	if err != nil {
		return err
	}
	hasAccess := permission.Check(t, permission.PermNodeRead,
		permission.Context(permission.CtxPool, a.Pool))
	if !hasAccess {
		return permission.ErrUnauthorized
	}
	containerList, err := mainDockerProvisioner.listContainersByApp(appName)
	if err != nil {
		return err
	}
	return json.NewEncoder(w).Encode(containerList)
}
func DeleteAbility(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	urlParams := mux.Vars(r)
	strID := urlParams["id"]
	ability := models.Ability{}

	id, err := strconv.Atoi(strID)
	if err != nil {
		// handle error
		message := models.APIMessage{"Id format invalid"}
		json.NewEncoder(w).Encode(message)
	} else {
		database.DB.First(&ability, id)

		if ability.ID == 0 {
			message := models.APIMessage{"Ability not found"}
			json.NewEncoder(w).Encode(message)
		} else {
			database.DB.Delete(&ability)
			message := models.APIMessage{"Ability successful deleted"}
			json.NewEncoder(w).Encode(message)
		}
	}
}
Example #7
0
/*
Test with this curl command:

curl -H "Content-Type: application/json" -d '{"name":"New Todo"}' http://localhost:8080/todos

*/
func TodoCreate(w http.ResponseWriter, r *http.Request) {
	Cors(w)
	var todo Todo
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &todo); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	t := RepoCreateTodo(todo)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(t); err != nil {
		panic(err)
	}
}
Example #8
0
func (c *ApiConnection) Login(w http.ResponseWriter, r *http.Request) {
	email := r.FormValue("email")
	password := r.FormValue("password")

	connection := c.dbConnection.LoginWithCredentials(email, password)
	userID := fmt.Sprintf("%x", string(connection.Id))
	log.Println(userID)

	if connection != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)

		userMap := make(map[string]string)
		userMap["token"] = userID

		if err := json.NewEncoder(w).Encode(userMap); err != nil {
			panic(err)
		}

		return
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
/*
Test with this curl command:

*/
func TaskCreate(w http.ResponseWriter, r *http.Request) {
	var v Node
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &v); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusBadRequest) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
		return
	}

	uuid := uuid()
	tasks[uuid.ID] = &v

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusAccepted)
	if err := json.NewEncoder(w).Encode(uuid); err != nil {
		panic(err)
	}
	return
}
func getCLHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	detail, err := getCLDetail(r.FormValue("cl"))
	if err != nil {
		skutil.ReportError(w, r, err, "")
		return
	}
	if detail.Issue == 0 {
		// Return successful empty response, since the user could still be typing.
		if err := json.NewEncoder(w).Encode(map[string]interface{}{}); err != nil {
			skutil.ReportError(w, r, err, "Failed to encode JSON")
		}
		return
	}
	patch, err := getCLPatch(detail, 0)
	if err != nil {
		skutil.ReportError(w, r, err, "")
		return
	}
	clData, err := gatherCLData(detail, patch)
	if err != nil {
		skutil.ReportError(w, r, err, "")
		return
	}
	if err = json.NewEncoder(w).Encode(clData); err != nil {
		skutil.ReportError(w, r, err, "")
		return
	}
}
Example #11
0
func (s *DockerServer) taskList(w http.ResponseWriter, r *http.Request) {
	s.swarmMut.Lock()
	defer s.swarmMut.Unlock()
	if s.swarm == nil {
		w.WriteHeader(http.StatusNotAcceptable)
		return
	}
	filtersRaw := r.FormValue("filters")
	var filters map[string][]string
	json.Unmarshal([]byte(filtersRaw), &filters)
	if filters == nil {
		json.NewEncoder(w).Encode(s.tasks)
		return
	}
	var ret []*swarm.Task
	for i, task := range s.tasks {
		var srvName string
		for _, srv := range s.services {
			if task.ServiceID == srv.ID {
				srvName = srv.Spec.Name
				break
			}
		}
		if inFilter(filters["id"], task.ID) ||
			inFilter(filters["service"], task.ServiceID) ||
			inFilter(filters["service"], srvName) ||
			inFilter(filters["node"], task.NodeID) ||
			inFilter(filters["desired-state"], string(task.DesiredState)) {
			ret = append(ret, s.tasks[i])
		}
	}
	json.NewEncoder(w).Encode(ret)
}
Example #12
0
func (a *App) GET_Nodes(w http.ResponseWriter, r *http.Request) {
	sessionCopy := db.GetDatastore().Copy()
	defer sessionCopy.Close()

	params := r.URL.Query()
	admin_state_str := params.Get("state")

	collection := sessionCopy.DB(conf.SystemConfig.DBConfig.Database).C(models.COLL_NAME_STORAGE_NODES)
	var nodes models.Nodes
	if admin_state_str == "" {
		if err := collection.Find(nil).All(&nodes); err != nil {
			util.HttpResponse(w, http.StatusInternalServerError, err.Error())
			logger.Get().Error("Error getting the nodes list. error: %v", err)
			return
		}
	} else {
		nodes, err = getNodesWithState(w, admin_state_str)
		if err != nil {
			util.HttpResponse(w, http.StatusInternalServerError, err.Error())
			logger.Get().Error("Error getting the nodes list. error: %v", err)
			return
		}
	}
	if len(nodes) == 0 {
		json.NewEncoder(w).Encode([]models.Node{})
	} else {
		json.NewEncoder(w).Encode(nodes)
	}
}
Example #13
0
// SubmissionCreate accepts POST request
func SubmissionCreate(w http.ResponseWriter, r *http.Request) {
	var submission Submission

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))

	if err != nil {
		panic(err)
	}

	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	if err := json.Unmarshal(body, &submission); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(submission); err != nil {
		panic(err)
	}
}
Example #14
0
func GetPhoto(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var photoId string
	var ok bool
	if photoId, ok = vars["photoId"]; !ok {
		panic("cannot find {photoId}")
	}
	photo, err := persistence.RepoFindPhoto(photoId)
	if err == nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(photo); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(responseErrors.JSONErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
Example #15
0
func TodoCreate(w http.ResponseWriter, r *http.Request) {
	db := InitDB()
	var todo Todo
	response := TodoResponse{Error: true}
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	spew.Dump(body)

	if err != nil {
		panic(err)
	}

	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	if err := json.Unmarshal(body, &todo); err != nil {
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	} else {
		db.Create(&todo)
		response.Error = false
		response.Data = &todo
	}

	json.NewEncoder(w).Encode(response)
}
Example #16
0
//handlers for municipality
func MunicipalIndex(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	var lat float64
	var lon float64
	var err error

	if lat, err = strconv.ParseFloat(vars["lat"], 64); err != nil {
		panic(err)
	}
	if lon, err = strconv.ParseFloat(vars["lon"], 64); err != nil {
		panic(err)
	}

	m := RepoFindCourtByAddress(lat, lon)
	if m.Id >= 0 {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(m); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}
}
Example #17
0
func (c *ChatService) onGetChatHistory(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
	log.Println("Get chat history...")
	groupId := p.ByName("id")

	queryParams := req.URL.Query()
	var offset uint = 0
	var limit uint = 20

	if o, err := strconv.ParseUint(queryParams.Get("offset"), 10, 32); err == nil {
		offset = uint(o)
	}

	if l, err := strconv.ParseUint(queryParams.Get("limit"), 10, 32); err == nil {
		limit = uint(l)
	}

	log.Println("Limit =", limit, "Offset =", offset)
	log, err := c.chatStore.GetMessagesFor(groupId, offset, limit)
	if err == nil {
		response := make(map[string]interface{})
		response["limit"] = limit
		response["offset"] = offset
		response["messages"] = log
		response["id"] = groupId
		json.NewEncoder(w).Encode(response)
	} else {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(ErrorMessage{
			Error: err.Error(),
		})
	}
}
Example #18
0
//handlers for Ticket
func TicketIndex(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	driver_licenses, ok := params["driver_license"]
	if ok {
		driver_license := string(driver_licenses[0])
		tic := RepoFindTicketByDriverLicenseNumber(driver_license)
		if tic.Id > 0 {
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(http.StatusOK)
			if err := json.NewEncoder(w).Encode(tic); err != nil {
				panic(err)
			}
		} else {
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(http.StatusNotFound)
			if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
				panic(err)
			}
		}
	} else {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(gTickets); err != nil {
			panic(err)
		}
	}
}
func CreateAbility(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	var newAbility models.NewAbility

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048676))

	if err != nil {
		panic(err)
	}

	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	if err := json.Unmarshal(body, &newAbility); err != nil {
		message := models.APIMessage{"Input format invalid"}
		json.NewEncoder(w).Encode(message)
	} else {
		var ability models.Ability
		ability.Name = newAbility.Name

		database.DB.Create(&ability)

		if database.DB.NewRecord(ability) {
			message := models.APIMessage{"Error creating ability"}

			json.NewEncoder(w).Encode(message)
		} else {
			json.NewEncoder(w).Encode(ability)
		}
	}
}
Example #20
0
func CourtCreate(w http.ResponseWriter, r *http.Request) {

	var court Court
	var err error
	//Check if malicious user is trying to overload the server
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &court); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")

		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}

	}
	if court, err = RepoCreateCourt(court); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(court); err != nil {
		panic(err)
	}
}
Example #21
0
func ServerCreate(w http.ResponseWriter, r *http.Request) {
	if authentication.IsAllowed(w, r) {
		var server pulp.Server
		body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
		if err != nil {
			logger.Log("could not read POST body, Error: "+err.Error(), logger.ERROR)
		}

		if err := r.Body.Close(); err != nil {
			logger.Log("could not close POST body, Error: "+err.Error(), logger.ERROR)
		}

		if err := json.Unmarshal(body, &server); err != nil {
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(422) // unprocessable entity
			if err := json.NewEncoder(w).Encode(err); err != nil {
				logger.Log("could not json/encode error, Error: "+err.Error(), logger.ERROR)
			}
		}
		session, collection := db.InitServerCollection()
		defer session.Close()
		server.Added = time.Now()
		err = collection.Insert(server)
		if err != nil {
			logger.Log("could not insert server to DB, Error: "+err.Error(), logger.ERROR)
		}
		w.Header().Set("Content-Type", "application/json; charset=UTF=8")
		w.WriteHeader(http.StatusCreated)
		if err := json.NewEncoder(w).Encode(server); err != nil {
			panic(err)
		}
	}
}
Example #22
0
func openLogFile(fileName, fileType string, compress bool, rotateMode int, maxSize int64) (*jsonFile, error) {
	fullName := fileName + fileType
	if _, err := os.Stat(fullName); err == nil {
		os.Rename(fullName, fileName+".01"+fileType)
		fullName = fileName + ".02" + fileType
	} else if _, err := os.Stat(fileName + ".01" + fileType); err == nil {
		for fileId := 1; true; fileId++ {
			fullName = fileName + fmt.Sprintf(".%02d", fileId) + fileType
			if _, err := os.Stat(fullName); err != nil {
				break
			}
		}
	}
	file, err := os.OpenFile(fullName, os.O_WRONLY|os.O_CREATE, 0755)
	if err != nil {
		return nil, err
	}
	jsonfile := &jsonFile{file: file, curFile: fullName, rotateMode: rotateMode}
	if compress {
		jsonfile.bufio = bufio.NewWriter(jsonfile.file)
		jsonfile.gzip = gzip.NewWriter(jsonfile.bufio)
		jsonfile.json = json.NewEncoder(jsonfile.gzip)
	} else {
		jsonfile.bufio = bufio.NewWriter(jsonfile.file)
		jsonfile.json = json.NewEncoder(jsonfile.bufio)
	}
	if jsonfile.rotateMode == ROTATE_BY_SIZE && maxSize == 0 {
		jsonfile.maxSize = 1024 * 1024 * 1024 * 25
	} else {
		jsonfile.maxSize = maxSize
	}

	return jsonfile, nil
}
Example #23
0
// addNodeHandler can provide an machine and/or register a node address.
// If register flag is true, it will just register a node.
// It checks if node address is valid and accessible.
func addNodeHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	params, err := unmarshal(r.Body)
	if err != nil {
		return err
	}
	if templateName, ok := params["template"]; ok {
		params, err = iaas.ExpandTemplate(templateName)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
		}
	}
	pool := params["pool"]
	if pool == "" {
		w.WriteHeader(http.StatusBadRequest)
		return json.NewEncoder(w).Encode(map[string]string{"error": "pool is required"})
	}
	if !permission.Check(t, permission.PermNodeCreate, permission.Context(permission.CtxPool, pool)) {
		return permission.ErrUnauthorized
	}
	isRegister, _ := strconv.ParseBool(r.URL.Query().Get("register"))
	if !isRegister {
		canCreateMachine := permission.Check(t, permission.PermMachineCreate,
			permission.Context(permission.CtxIaaS, params["iaas"]))
		if !canCreateMachine {
			return permission.ErrUnauthorized
		}
	}
	response, err := mainDockerProvisioner.addNodeForParams(params, isRegister)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		response["error"] = err.Error()
	}
	return json.NewEncoder(w).Encode(response)
}
Example #24
0
// Login login user
func (c AuthController) Login(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	model := &models.LoginModel{}
	if err := json.NewDecoder(r.Body).Decode(model); err != nil {
		c.Logger.Log("AuthController login json decode.", err)
		json.NewEncoder(w).Encode(models.Response{ErrorCode: 1})
		return
	}

	conn := factory.NewDatabase().Connection()
	if err := conn.Open(); err != nil {
		c.Logger.Log("AuthController login could not open db connection.", err)
		json.NewEncoder(w).Encode(models.Response{ErrorCode: 2})
		return
	}
	defer conn.Close()

	user, err := factory.NewDatabase().User(conn).FindByEmail(model.Email)
	if err != nil || user == nil {
		c.Logger.Log("AuthController login find by email.", err)
		json.NewEncoder(w).Encode(models.Response{ErrorCode: 3})
		return
	}

	if user.Email != strings.ToLower(model.Email) || user.Password != model.Password {
		c.Logger.Log("AuthController login invalid username or password.", nil)
		json.NewEncoder(w).Encode(models.Response{ErrorCode: 4})
		return
	}

	json.NewEncoder(w).Encode(models.Response{Data: user, Success: true})
}
Example #25
0
func CreateUser(w http.ResponseWriter, r *http.Request) {
	ctx := getContext(r)

	if name, ok := ctx.jsonBody["name"]; ok {
		if password, ok := ctx.jsonBody["password"]; ok {
			err := db.SaveUser(name.(string), password.(string))
			if err != nil {
				res := responses.UnknownError(err.Error())
				w.WriteHeader(res.Code)
				json.NewEncoder(w).Encode(res)
				return
			} else {
				res := responses.Success{Ok: true}
				w.Header().Add("Content-Type", "application/json")
				w.WriteHeader(201)
				json.NewEncoder(w).Encode(res)
				return
			}
		}
	}

	res := responses.BadRequest(`You must send a JSON body with "name" and "password".`)
	w.WriteHeader(res.Code)
	json.NewEncoder(w).Encode(res)
}
Example #26
0
func addFoxToStorage(w http.ResponseWriter, r *http.Request, status int, uuid string) {
	var fox Fox
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))

	if err != nil {
		panic(err)
	}

	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	util.SendHeaders(w)

	if err := json.Unmarshal(body, &fox); err != nil {
		w.WriteHeader(422)
		if err := json.NewEncoder(w).Encode(Error{Code: 422, Message: err.Error()}); err != nil {
			panic(err)
		}
		return
	}

	w.WriteHeader(status)

	s := StoreFox(fox, uuid)
	if err := json.NewEncoder(w).Encode(s); err != nil {
		log.Critical("Error encoding the UUID")
		panic(err)
	}

}
Example #27
0
/**
 * GET A LANGUAGE BY ITS ID
 */
func goGetLanguageById(w http.ResponseWriter, r *http.Request) {
	//parse array of input from request message
	vars := mux.Vars(r)

	//get id input
	var langId string
	langId = vars["languageId"]

	//execute get method
	lang := getLanguageById(langId)

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	if lang.Id != "" {
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(lang); err != nil {
			panic(err)
		}
		return
	}

	// If we didn't find it, 404
	w.WriteHeader(http.StatusNotFound)
	if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil {
		panic(err)
	}

}
Example #28
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)
}
Example #29
0
func PostsCreateHandler(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
	//  fmt.Fprintln(rw, "posts index")
	//String id;
	var todo Todo

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &todo); err != nil {
		rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
		rw.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(rw).Encode(err); err != nil {
			panic(err)
		}
	}

	/*
	    todos := Todos{
	    Todo{Name: r.FormValue("name")},
	    Todo{Name: "Host meetup"},
	}*/
	var newtodo NewTodo
	newtodo.Greeting = "Hello, " + todo.Name + "!"
	json.NewEncoder(rw).Encode(newtodo)

}
Example #30
-1
func TestMain(m *testing.M) {
	generateMetrics()

	masterRouter := http.NewServeMux()
	masterRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(masterMetrics)
	})
	masterTestServer = httptest.NewServer(masterRouter)

	slaveRouter := http.NewServeMux()
	slaveRouter.HandleFunc("/metrics/snapshot", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(slaveMetrics)
	})
	slaveRouter.HandleFunc("/monitor/statistics", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode([]map[string]interface{}{slaveTaskMetrics})
	})
	slaveTestServer = httptest.NewServer(slaveRouter)

	rc := m.Run()

	masterTestServer.Close()
	slaveTestServer.Close()
	os.Exit(rc)
}