// ContainerAccessRuleGetAll returns all the rules selected for a container func ContainerAccessRuleGetAll(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println("ContainerRulesGetAll: authorize error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ContainerID := r.PathParam("ID") if ContainerID == "" { rest.Error(w, "ID required", http.StatusBadRequest) return } cars, err := GetAllContainerAccessRule(dbConn, ContainerID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) w.WriteJson(&cars) }
func (t *TypesController) DeleteType(w rest.ResponseWriter, r *rest.Request) { appId := r.PathParam("appId") typeName := r.PathParam("typeName") app, err := GetAppFromRequest(r) if err != nil { RestError(w, err) return } appsDb := neutrino.NewAppsDbService(r.Env["user"].(string)) appsDb.UpdateId(app["_id"], bson.M{ "$pull": bson.M{ "types": typeName, }, }, ) db := neutrino.NewTypeDbService(appId, typeName) session, collection := db.GetCollection() defer session.Close() dropError := collection.DropCollection() if dropError != nil { RestError(w, dropError) return } w.WriteHeader(http.StatusOK) }
func (u Util) FailedToAuthenticate(w rest.ResponseWriter) { w.WriteHeader(401) w.WriteJson(types.Json{ "response": "Failed to authenticate user request", "reason": "Missing, illegal or expired token", }) }
func registerUser(w rest.ResponseWriter, r *rest.Request, db neutrino.DbService) { var u bson.M if err := r.DecodeJsonPayload(&u); err != nil { RestErrorInvalidBody(w) return } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u["password"].(string)), 10) if err != nil { RestError(w, err) return } doc := bson.M{ "_id": u["email"].(string), "password": hashedPassword, "createdAt": time.Now(), } if err := db.Insert(doc); err != nil { RestError(w, err) return } w.WriteHeader(http.StatusOK) }
func (routes *Routes) sendRegistrationResponse(w rest.ResponseWriter, r *rest.Request, sir *store.ServiceInstance) { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], }).Infof("Instance %s registered", sir) ttl := uint32(sir.TTL / time.Second) linksURL := r.BaseUrl() if middleware.IsUsingSecureConnection(r) { // request came in over a secure connection, continue using it linksURL.Scheme = "https" } links := BuildLinks(linksURL.String(), sir.ID) instance := &ServiceInstance{ ID: sir.ID, TTL: ttl, Links: links, } w.Header().Set("Location", links.Self) w.WriteHeader(http.StatusCreated) if err := w.WriteJson(instance); err != nil { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": err, }).Warnf("Failed to write registration response for instance %s", sir) i18n.Error(r, w, http.StatusInternalServerError, i18n.ErrorEncoding) } }
func (api *Api) DeletePost(w rest.ResponseWriter, r *rest.Request) { _, err := api.validateAuthHeader(r.Request) if err != nil { rest.Error(w, "Authorization invalid", http.StatusUnauthorized) return } _id := r.PathParam("id") id, err := strconv.ParseInt(_id, 10, 64) post := db.Post{} if err = api.First(&post, id).Error; err != nil { if err == gorm.RecordNotFound { rest.NotFound(w, r) return } else { log.Println(gormLoadError("post"), err) rest.Error(w, INTERNALERROR, http.StatusInternalServerError) return } } if err := api.Delete(&post).Error; err != nil { log.Println(gormDeleteError("post"), err) rest.Error(w, INTERNALERROR, http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }
func (api *ChessApi) PostCreateGame(res rest.ResponseWriter, req *rest.Request) { user := getUser(req) type createBody struct { Color game.Color `json:"Color"` } body := new(createBody) err := req.DecodeJsonPayload(body) if err != nil || body.Color == "" { idx := rand.Perm(2)[0] body.Color = []game.Color{game.White, game.Black}[idx] } ok, msg := api.Commands.ExecCommand( commands.CreateGame, user.Uuid, map[string]interface{}{ "color": body.Color, }, ) if ok { res.WriteHeader(http.StatusAccepted) res.WriteJson("ok") } else { res.WriteHeader(http.StatusBadRequest) res.WriteJson(map[string]string{"error": msg}) } }
func DeleteRole(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-user") if err != nil { logit.Error.Println("GetAllRoles: validate token error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } if r.PathParam("ID") == "" { logit.Error.Println("DeleteRole: error ID required") rest.Error(w, "ID required", http.StatusBadRequest) return } err = secimpl.DeleteRole(dbConn, r.PathParam("ID")) if err != nil { logit.Error.Println("DeleteRole: error secimpl call" + err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) status := SimpleStatus{} status.Status = "OK" w.WriteJson(&status) }
func GetRole(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println("GetRole: validate token error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } Name := r.PathParam("Name") if Name == "" { logit.Error.Println("GetRole: error Name required") rest.Error(w, "Name required", http.StatusBadRequest) return } var role sec.Role role, err = secimpl.GetRole(dbConn, Name) if err != nil { logit.Error.Println("GetRole: error secimpl call" + err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.WriteJson(&role) }
func GetUser(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println("GetUser: validate token error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("GetUser: error User ID required") rest.Error(w, "User ID required", http.StatusBadRequest) return } status := SimpleStatus{} status.Status = "OK" w.WriteHeader(http.StatusOK) w.WriteJson(&status) }
func GetAllUsers(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println("GetAllUsers: validate token error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } usersList, err := secimpl.GetAllUsers(dbConn) if err != nil { logit.Error.Println("GetAllUsers: error " + err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } for i := range usersList { logit.Info.Println("GetAllUsers: secimpl.GetAllUsers userName=" + usersList[i].Name) } w.WriteHeader(http.StatusOK) w.WriteJson(&usersList) }
func AddComment(w rest.ResponseWriter, req *rest.Request) { requesterID := GetRequesterID(req) var comment types.Comment err := req.DecodeJsonPayload(&comment) if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } comment.Time = time.Now().UTC() comment.PostID = req.PathParam("pid") comment.CreatorID = requesterID comment.ID = base64.RawURLEncoding.EncodeToString(uuid.NewRandom()) err = comment.Validate() if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } err = transactions.AddComment(requesterID, &comment) if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } insertedComment, err := transactions.GetComment(requesterID, comment.ID) if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteJson(insertedComment) w.WriteHeader(http.StatusOK) }
func ContainerLoadTest(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println("ContainerLoadTest: authorize error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { rest.Error(w, "ID required", http.StatusBadRequest) return } Writes := r.PathParam("Writes") if Writes == "" { rest.Error(w, "Writes required", http.StatusBadRequest) return } var writes int writes, err = strconv.Atoi(Writes) if err != nil { logit.Error.Println("ContainerLoadTest:" + err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } node, err := admindb.GetContainer(dbConn, ID) if err != nil { logit.Error.Println("ContainerLoadTest:" + err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } var host = node.Name if KubeEnv { host = node.Name + "-db" } results, err2 := loadtest(dbConn, node.Name, host, writes) if err2 != nil { logit.Error.Println("ContainerLoadTest:" + err2.Error()) rest.Error(w, err2.Error(), http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) w.WriteJson(&results) }
// RulesGetAll returns all the access rule definitions func RulesGetAll(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } rules, err := GetAllRules(dbConn) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) w.WriteJson(&rules) }
func GetStatus(w rest.ResponseWriter, r *rest.Request) { Token := r.PathParam("Token") if Token == "" { rest.Error(w, "Token required", 400) return } dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, Token, "perm-read") if err != nil { logit.Error.Println("GetStatus: validate token error " + err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { rest.Error(w, "ID required", 400) return } stat, err := backup.GetStatus(dbConn, ID) if err != nil { logit.Error.Println("GetStatus: " + err.Error()) rest.Error(w, err.Error(), 400) return } w.WriteHeader(http.StatusOK) w.WriteJson(stat) }
func Logout(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println("BackupNow: error " + err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() token := r.PathParam("Token") if token == "" { logit.Error.Println("Logout: Token not supplied") rest.Error(w, "Token not supplied", http.StatusBadRequest) } err = secimpl.Logout(dbConn, token) if err != nil { logit.Error.Println("Logout: error secimpl call" + err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) status := SimpleStatus{} status.Status = "OK" w.WriteJson(&status) }
func (u *Users) DeleteUser(w rest.ResponseWriter, r *rest.Request) { id := r.PathParam("id") u.Lock() delete(u.Store, id) u.Unlock() w.WriteHeader(http.StatusOK) }
func addContactsToGroupHandler(w rest.ResponseWriter, r *rest.Request) { user := castedValidateUserAndLogInIfNecessary(w, r) if user == nil { return } body := addContactsToGroupBody{} err := r.DecodeJsonPayload(&body) if err != nil { rest.Error(w, err.Error(), http.StatusBadRequest) log.Println(err.Error()) return } if err := db.AddUsersToGroup( body.ContactUserIds, body.GroupId); err == nil { w.WriteHeader(http.StatusOK) fm.addToGroup <- &userIdsGroupId{ userIds: body.ContactUserIds, groupId: body.GroupId, } } else { rest.Error(w, err.Error(), http.StatusInternalServerError) } }
func DeleteCountry(w rest.ResponseWriter, r *rest.Request) { code := r.PathParam("code") lock.Lock() delete(store, code) lock.Unlock() w.WriteHeader(http.StatusOK) }
func addContactHandler(w rest.ResponseWriter, r *rest.Request) { user := castedValidateUserAndLogInIfNecessary(w, r) if user == nil { return } body := addContactBody{} err := r.DecodeJsonPayload(&body) if err != nil { rest.Error(w, err.Error(), http.StatusBadRequest) log.Println(err.Error()) return } groupId, err := db.AddContact(user.Id, body.Email) if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) } else { group, err := db.GetGroup(groupId) if err != nil { log.Println(err) rest.Error(w, err.Error(), http.StatusInternalServerError) } else { w.WriteHeader(http.StatusOK) fm.addToGroup <- &userIdsGroupId{ userIds: group.UserIDs, groupId: groupId, } } } }
// PostDoc uses save to save a document func PostDoc(w rest.ResponseWriter, r *rest.Request) { id := r.PathParam("id") collection := r.PathParam("collection") // Make sure that the user owns what they are trying to save _, ok := r.Env["JWT_PAYLOAD"].(map[string]interface{})["backend"] if !ok && r.Env["REMOTE_USER"] != id { rest.Error(w, "Cannot modify another users data", http.StatusInternalServerError) return } var doc map[string]interface{} err := r.DecodeJsonPayload(&doc) if err != nil { rest.Error(w, err.Error(), http.StatusInternalServerError) return } fmt.Println(doc) err = save.Save(collection, doc) if err != nil { log.Println(err) rest.Error(w, "Could not save", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.(http.ResponseWriter).Write(variables.BlankResponse) }
func HandleOwnIdentitiesPost(w rest.ResponseWriter, r *rest.Request) { fmt.Println("POST /identities") var identity Identity = Identity{} err := r.DecodeJsonPayload(&identity) if err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(422) // unprocessable entity w.WriteJson("nop") } else { if identity.Hostname == "" { clientError(w, "Missing hostname") return } identity, err = FetchIdentity(identity.GetURI()) fmt.Println("ER", err) if err != nil { clientError(w, "Could not retrieve identity") return } _, err = db.C("identities").UpsertId(identity.ID, &identity) if err != nil { fmt.Println(err) internal(w, "Could not upsert identity") return } w.WriteJson(identity) } }
func (routes *Routes) renewInstance(w rest.ResponseWriter, r *rest.Request) { iid := r.PathParam(RouteParamInstanceID) if iid == "" { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": "instance id is required", }).Warn("Failed to renew instance") i18n.Error(r, w, http.StatusBadRequest, i18n.ErrorInstanceIdentifierMissing) return } catalog := routes.catalog(w, r) if catalog == nil { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": "catalog is nil", }).Errorf("Failed to renew instance %s", iid) return } if err := catalog.Renew(iid); err != nil { routes.logger.WithFields(log.Fields{ "namespace": r.Env["REMOTE_USER"], "error": err, }).Warnf("Failed to renew instance %s", iid) i18n.Error(r, w, statusCodeFromError(err), i18n.ErrorInstanceHeartbeatFailed) return } w.WriteHeader(http.StatusOK) }
func (api *Api) DeleteProfile(w rest.ResponseWriter, r *rest.Request) { _, err := api.validateAuthHeader(r.Request) if err != nil { rest.Error(w, "Authorization invalid", http.StatusUnauthorized) return } _id := r.PathParam("id") id, err := strconv.ParseInt(_id, 10, 64) profile := db.Profile{} if err = api.Find(&profile, db.Profile{Id: id}).Error; err != nil { rest.Error(w, err.Error(), http.StatusNotFound) return } self := api.GetSelfOnion() var circles []db.Circle api.Model(&profile).Related(&circles, "Circles") if err := api.Unscoped().Delete(&profile).Error; err != nil { rest.Error(w, "Deleting profile failed", http.StatusInternalServerError) return } if profile.OnionId == self.Id { api.ProfileDeleted(circles) } w.WriteHeader(http.StatusOK) }
// StartCluster starts all nodes in a cluster func StartCluster(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-cluster") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("StartCluster: error cluster ID required") rest.Error(w, "cluster ID required", http.StatusBadRequest) return } cluster, err := admindb.GetCluster(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } //start docker containers containers, err := admindb.GetAllContainersForCluster(dbConn, cluster.ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } i := 0 i = 0 var response swarmapi.DockerStartResponse for i = range containers { req := &swarmapi.DockerStartRequest{} req.ContainerName = containers[i].Name logit.Info.Println("will attempt to start container " + req.ContainerName) response, err = swarmapi.DockerStart(req) if err != nil { logit.Error.Println("StartCluster: error when trying to start container" + err.Error()) } logit.Info.Println("StartCluster: started " + response.Output) i++ } status := types.SimpleStatus{} status.Status = "OK" w.WriteHeader(http.StatusOK) w.WriteJson(&status) }
func (api *Api) DeleteProfilePicture(w rest.ResponseWriter, r *rest.Request) { _, err := api.validateAuthHeader(r.Request) if err != nil { rest.Error(w, "Authorization invalid", http.StatusUnauthorized) return } self := api.GetSelfOnion() id := api.GetProfilePictureId(self.Id) if id == 0 { rest.Error(w, "Profile picture not found", http.StatusNotFound) return } var profilePicture db.Profile err = api.First(&profilePicture, id).Error if err != nil { rest.Error(w, "Profile picture not found", http.StatusNotFound) return } var circles []db.Circle api.Model(&profilePicture).Related(&circles, "Circles") api.Unscoped().Delete(&profilePicture) api.ProfileDeleted(circles) w.WriteHeader(http.StatusOK) }
func (u Util) SimpleJsonValidationReason(w rest.ResponseWriter, code int, err []error) { errorMessage := decodeValidatorErrors(err) w.WriteHeader(code) w.WriteJson(types.Json{ "reason": errorMessage, }) }
// DeleteAddress deletes the address with the specified ID func DeleteAddress(w rest.ResponseWriter, req *rest.Request) { id := req.PathParam("address") address := addressStruct{} err := db.View(func(tx *bolt.Tx) (err error) { tmp := tx.Bucket([]byte(addressBucket)).Get([]byte(id)) err = json.Unmarshal(tmp, &address) return }) if err != nil { log.Printf(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } if err = deleteIP(address); err != nil { log.Printf(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } err = db.Update(func(tx *bolt.Tx) (err error) { err = tx.Bucket([]byte(addressBucket)).Delete([]byte(id)) return }) if err != nil { log.Printf(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }
func DeleteOS(w rest.ResponseWriter, r *rest.Request) { Distribution := r.PathParam("Distribution") lock.Lock() delete(store, Distribution) lock.Unlock() w.WriteHeader(http.StatusOK) }
// RulesDelete deletes a given rule func RulesDelete(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { rest.Error(w, "ID required", http.StatusBadRequest) return } err = DeleteRule(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } status := types.SimpleStatus{} status.Status = "OK" w.WriteHeader(http.StatusOK) w.WriteJson(&status) }