Example #1
0
func updateList(db *bolt.DB, params martini.Params, req *http.Request, r render.Render) {

	var l DistributionList

	body, _ := ioutil.ReadAll(req.Body)
	req.Body.Close()
	err := json.Unmarshal(body, &l)

	if err != nil {
		r.Error(http.StatusBadRequest)
		return
	}

	if params["id"] != l.Id {
		r.Error(http.StatusBadRequest)
		return
	}

	// marshal back out to json to normalize our data
	j, err := json.Marshal(l)

	db.Update(
		func(tx *bolt.Tx) error {
			b := tx.Bucket([]byte(bucketDistributionLists))
			return b.Put([]byte(l.Id), j)
		})

	r.Status(http.StatusOK)
}
Example #2
0
func Delete(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	b := banner.Banner{}

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		b.ID = int64(intID)
	}

	if err := b.Get(ctx); err != nil {
		http.Error(rw, "failed to delete banner", http.StatusInternalServerError)
		return
	}

	segs := strings.Split(b.Image, "/")
	blobstore.Delete(ctx, appengine.BlobKey(segs[len(segs)-1]))

	if err := b.Delete(ctx); err != nil {
		http.Error(rw, "failed to delete banner", http.StatusInternalServerError)
		return
	}

	r.Status(200)
	return
}
Example #3
0
File: post.go Project: jf/gwp
// Delete a post
// DELETE /post/1
func HandleDelete(post Post, r render.Render) {
	err := post.delete()
	if err != nil {
		r.Error(500)
		return
	}
	r.Status(200)
}
Example #4
0
File: post.go Project: jf/gwp
// Update a post
// PUT /post/1
func HandlePut(post Post, r render.Render) {
	err := post.update()
	if err != nil {
		r.Error(500)
		return
	}
	r.Status(200)
}
Example #5
0
// POST /validate
func PostValidate(r render.Render, req *http.Request) {
	s := req.PostFormValue("session")
	session := db.Session{}
	if db.DB.Where("uuid = ?", s).First(&session).RecordNotFound() {
		r.Error(404)
	} else {
		r.Status(200)
	}
}
Example #6
0
func routePostAd(r render.Render, req *http.Request, params martini.Params) {
	slot := params["slot"]

	advrId := advertiserId(req)
	if advrId == "" {
		r.Status(404)
		return
	}

	req.ParseMultipartForm(100000)
	asset := req.MultipartForm.File["asset"][0]
	id := nextAdId()
	key := adKey(slot, id)

	content_type := ""
	if len(req.Form["type"]) > 0 {
		content_type = req.Form["type"][0]
	}
	if content_type == "" && len(asset.Header["Content-Type"]) > 0 {
		content_type = asset.Header["Content-Type"][0]
	}
	if content_type == "" {
		content_type = "video/mp4"
	}

	title := ""
	if a := req.Form["title"]; a != nil {
		title = a[0]
	}
	destination := ""
	if a := req.Form["destination"]; a != nil {
		destination = a[0]
	}

	rd.HMSet(key,
		"slot", slot,
		"id", id,
		"title", title,
		"type", content_type,
		"advertiser", advrId,
		"destination", destination,
		"impressions", "0",
	)

	f, _ := asset.Open()
	defer f.Close()
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, f)
	asset_data := string(buf.Bytes())

	rd.Set(assetKey(slot, id), asset_data, 0)
	rd.RPush(slotKey(slot), id)
	rd.SAdd(advertiserKey(advrId), key)

	r.JSON(200, getAd(req, slot, id))
}
Example #7
0
// GET /users/:uuid/activate
func GetUsersActivate(r render.Render, params martini.Params) {
	user := db.User{}
	if db.DB.Where("activation_token = ?", params["uuid"]).First(&user).RecordNotFound() {
		r.Error(404)
	} else {
		if err := user.Activate(); err != nil {
			r.Error(500)
		}
		r.Status(200)
	}
}
Example #8
0
func SetHeading(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	h := quote.Heading{}
	h.Heading = req.FormValue("heading")

	if err := h.Save(ctx); err != nil {
		http.Error(rw, "failed to save heading", http.StatusInternalServerError)
		return
	}

	r.Status(200)
	return
}
Example #9
0
func routeGetAdCount(r render.Render, params martini.Params) {
	slot := params["slot"]
	id := params["id"]
	key := adKey(slot, id)

	exists, _ := rd.Exists(key).Result()
	if !exists {
		r.JSON(404, map[string]string{"error": "not_found"})
		return
	}

	rd.HIncrBy(key, "impressions", 1).Result()
	r.Status(204)
}
Example #10
0
func removeList(db *bolt.DB, params martini.Params, req *http.Request, r render.Render) {
	id := params["id"]

	err := db.Update(
		func(tx *bolt.Tx) error {
			b := tx.Bucket([]byte(bucketDistributionLists))
			return b.Delete([]byte(id))
		})
	if err != nil {
		r.Error(http.StatusInternalServerError)
		return
	}

	r.Status(http.StatusOK)
}
Example #11
0
// Register creates a new device
func Register(render render.Render, r doorbot.Repositories, vm DeviceViewModel) {

	repo := r.DeviceRepository()

	device, err := repo.FindByToken(r.DB(), vm.Device.Token)

	if err != nil {
		log.WithFields(log.Fields{
			"error":        err,
			"account_id":   r.AccountScope(),
			"device_token": vm.Device.Token,
			"step":         "device-find",
		}).Error("Api::Devices->Register database error")

		render.Status(http.StatusInternalServerError)
		return
	}

	if device == nil {
		render.Status(http.StatusNotFound)
		return
	}

	device.Make = vm.Device.Make
	device.DeviceID = vm.Device.DeviceID
	device.IsEnabled = true

	_, err = repo.Update(r.DB(), device)

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"device_id":  device.ID,
			"step":       "device-update",
		}).Error("Api::Devices->Register database error")

		render.Status(http.StatusInternalServerError)
		return
	}

	log.WithFields(log.Fields{
		"account_id": r.AccountScope(),
		"device_id":  device.ID,
	}).Info("Api::Devices->Put device registered")

	render.JSON(http.StatusOK, device)
}
Example #12
0
func RegisterDropbox(req *http.Request, render render.Render, registerDropboxForm RegisterDropboxForm, account *models.Account, logger *middlewares.Logger, ds *appx.Datastore) {
	logger.Infof("You are in register dropbox")

	authorization := &models.ExternalServiceAuthorization{
		AuthorizationType: models.DropBox,
		AccessToken:       registerDropboxForm.AccessToken,
		UserId:            models.DropBox.String() + "-" + registerDropboxForm.UserId,
	}

	authorization.SetParentKey(account.Key())

	err := ds.Load(authorization)
	if err != nil {
		println("I failed you becasue: %v", err.Error())
	}
	exists := err == nil

	if err := ds.Save(authorization); err != nil {
		logger.Errorf("Unable to register for dropbox %v", err)
		render.JSON(http.StatusInternalServerError, "Unable to register dropbox")
		return
	}

	if exists {
		DropboxDelta(req, ds, account, authorization)
	} else {
		DropboxInit(req, ds, account, authorization)
	}

	render.Status(http.StatusOK)
}
Example #13
0
// Delete a door
func Delete(render render.Render, r doorbot.Repositories, params martini.Params) {
	id, err := strconv.ParseUint(params["id"], 10, 32)
	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	repo := r.DoorRepository()
	door, err := repo.Find(r.DB(), uint(id))
	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"door_id":    id,
			"step":       "door-find",
		}).Error("Api::Doors->Delete database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if door == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{"The specified door does not exists"}))
		return
	}

	_, err = repo.Delete(r.DB(), door)

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"door_id":    id,
			"step":       "door-delete",
		}).Error("Api::Doors->Delete database error")

		render.Status(http.StatusInternalServerError)
		return
	}

	log.WithFields(log.Fields{
		"account_id": r.AccountScope(),
		"door_id":    door.ID,
	}).Error("Api::Doors->Post door deleted")

	render.Status(http.StatusNoContent)
}
Example #14
0
func AuthorizationAccountProvider(c appengine.Context, logger *Logger, request *http.Request, render render.Render, martiniContext martini.Context, appx *appx.Datastore) {
	authToken := extractAuthToken(request)

	if authToken == "" {
		render.Status(http.StatusUnauthorized)
		return
	}

	var currentAccount models.Account
	if err := appx.Query(models.Accounts.ByAuthToken(authToken)).Result(&currentAccount); err != nil {
		logger.Errorf("%v", err)
		render.Status(http.StatusUnauthorized)
		return
	}

	martiniContext.Map(&currentAccount)
}
Example #15
0
func Delete(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	e := equipment.Equipment{}

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		e.ID = int64(intID)
	}

	if err := e.Delete(ctx); err != nil {
		http.Error(rw, "failed to delete equipment", http.StatusInternalServerError)
		return
	}

	r.Status(200)
	return
}
Example #16
0
func routeGetReport(req *http.Request, r render.Render) {
	advrId := advertiserId(req)

	if advrId == "" {
		r.Status(401)
		return
	}

	report := map[string]*Report{}
	adKeys, _ := rd.SMembers(advertiserKey(advrId)).Result()
	for _, adKey := range adKeys {
		ad, _ := rd.HGetAllMap(adKey).Result()
		if ad == nil {
			continue
		}

		imp, _ := strconv.Atoi(ad["impressions"])
		data := &Report{
			&Ad{
				ad["slot"],
				ad["id"],
				ad["title"],
				ad["type"],
				ad["advertiser"],
				ad["destination"],
				imp,
			},
			0,
			imp,
			nil,
		}
		report[ad["id"]] = data
	}

	for adId, clicks := range getLog(advrId) {
		if _, exists := report[adId]; !exists {
			report[adId] = &Report{}
		}
		report[adId].Clicks = len(clicks)
	}
	r.JSON(200, report)
}
Example #17
0
func (web *MailWeb) updateFlags(r render.Render, curUser sessionauth.User, req *http.Request) {
	var (
		watneyUser *auth.WatneyUser = curUser.(*auth.WatneyUser)
		folder     string
		uid        string
		addFlags   bool
		flags      mail.Flags
		err        error
	)
	if watneyUser.ImapCon.IsAuthenticated() {
		// 1) Get the folder
		folder = req.FormValue("folder")
		// 2) Check the UID
		if _, err := strconv.ParseInt(req.FormValue("uid"), 10, 32); err != nil {
			web.notifyError(r, 200,
				fmt.Sprintf("Given UID '%s' is not a valid ID", req.FormValue("uid")), err.Error())
			return
		} else {
			uid = req.FormValue("uid")
		}
		// 3) Check the add/remove form value
		if addFlags, err = strconv.ParseBool(req.FormValue("add")); err != nil {
			web.notifyError(r, 200,
				fmt.Sprintf("Couldn't parse string '%s' into bool", req.FormValue("add")),
				err.Error())
			return
		}
		// 4) Check the flags
		if err = json.Unmarshal([]byte(req.FormValue("flags")), &flags); err != nil {
			fmt.Println("error:", err)
			r.Error(500)
			return
		}
		if err = watneyUser.ImapCon.UpdateMailFlags(folder, uid, &flags, addFlags); err != nil {
			web.notifyError(r, 500, fmt.Sprintf("Error while performing UpdateMailFlags"), err.Error())
		} else {
			r.Status(200)
		}
	} else {
		web.notifyAuthTimeout(r, "Request mail flag update")
	}
}
Example #18
0
func UpdateAccount(render render.Render, accountUpdateForm AccountUpdateForm, account *models.Account, db *appx.Datastore) {
	account.FirstName = accountUpdateForm.FirstName
	account.LastName = accountUpdateForm.LastName
	account.Email = accountUpdateForm.Email

	if err := db.Save(account); err != nil {
		render.JSON(http.StatusInternalServerError, "Unable to register dropbox")
	}

	render.Status(http.StatusOK)
}
Example #19
0
// Get return a specific account
func Get(render render.Render, r doorbot.Repositories, params martini.Params, session *auth.Authorization) {
	id, err := strconv.ParseUint(params["id"], 10, 32)

	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	repo := r.AccountRepository()

	account, err := repo.Find(r.DB(), uint(id))

	if err != nil {
		log.WithFields(log.Fields{
			"account_id": id,
			"error":      err,
		}).Error("Api::Accounts->Get database error.")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if account == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{}))
		return
	}

	// Switch the view model depending on who/what requests the information.
	switch session.Type {
	case auth.AuthorizationAdministrator:
		render.JSON(http.StatusOK, AccountViewModel{Account: account})
	case auth.AuthorizationPerson:
		if session.Person.IsAccountManager() {
			render.JSON(http.StatusOK, AccountViewModel{Account: account})
			return
		}

		// Display a reduced version of the account.
		public := PublicAccount{
			ID:   account.ID,
			Name: account.Name,
			Host: account.Host,
		}

		render.JSON(http.StatusOK, PublicAccountViewModel{Account: public})
	default:
		render.Status(http.StatusForbidden)
		return
	}
}
Example #20
0
// Disable a device
func Disable(render render.Render, r doorbot.Repositories, params martini.Params) {
	id, err := strconv.ParseUint(params["id"], 10, 32)

	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"the id must be an unsigned integer"}))
		return
	}

	repo := r.DeviceRepository()
	device, err := repo.Find(r.DB(), uint(id))
	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"device_id":  id,
			"step":       "device-find",
		}).Error("Api::Devices->Disable database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if device == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{"The specified deevice does not exists."}))
		return
	}

	_, err = repo.Enable(r.DB(), device, false)

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"device_id":  id,
			"step":       "device-disable",
		}).Error("Api::Devices->Disable database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	log.WithFields(log.Fields{
		"account_id": r.AccountScope(),
		"device_id":  id,
	}).Info("Api::Devices->Disabled device disabled")

	render.Status(http.StatusNoContent)
}
Example #21
0
// Get a specific person
func Get(render render.Render, r doorbot.Repositories, params martini.Params, session *auth.Authorization) {
	id, err := strconv.ParseUint(params["id"], 10, 32)

	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	repo := r.PersonRepository()
	person, err := repo.Find(r.DB(), uint(id))

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"person_id":  id,
		}).Error("Api::People->Get database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if person == nil {
		err := doorbot.NewEntityNotFoundResponse([]string{"The specified person does not exists"})
		render.JSON(http.StatusNotFound, err)
		return
	}

	switch session.Type {
	case auth.AuthorizationAdministrator:
		render.JSON(http.StatusOK, PersonViewModel{Person: person})

	case auth.AuthorizationDevice:
		render.JSON(http.StatusOK, PublicPersonViewModel{Person: newPublicPerson(person)})

	case auth.AuthorizationPerson:
		// Display detailed info if the requesting user is an account manager or it is the same person
		if session.Person.IsAccountManager() || session.Person.ID == person.ID {
			render.JSON(http.StatusOK, PersonViewModel{Person: person})
			return
		}

		render.JSON(http.StatusOK, PublicPersonViewModel{Person: newPublicPerson(person)})
	default:
		render.Status(http.StatusForbidden)
	}
}
Example #22
0
// Delete an account ( admin panel )
func Delete(render render.Render, r doorbot.Repositories, params martini.Params, administrator *doorbot.Administrator) {
	id, err := strconv.ParseUint(params["id"], 10, 32)

	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	repo := r.AccountRepository()

	account, err := repo.Find(r.DB(), uint(id))
	if err != nil {
		log.WithFields(log.Fields{
			"error":            err.Error(),
			"account_id":       account.ID,
			"administrator_id": administrator.ID,
		}).Error("Api::Accounts->Delete database find error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if account == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{"The specified account does not exists."}))
		return
	}

	_, err = repo.Delete(r.DB(), account)

	if err != nil {
		log.WithFields(log.Fields{
			"error":            err.Error(),
			"administrator_id": administrator.ID,
			"account_id":       account.ID,
		}).Error("Api::Accounts->Delete database delete error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	log.WithFields(log.Fields{
		"administrator_id": administrator.ID,
		"account_id":       account.ID,
	}).Info("Api::Accounts->Delete account deleted by administrator.")

	render.Status(http.StatusNoContent)
}
Example #23
0
func (ws WebhookService) Handle(r render.Render, req *http.Request, params martini.Params) {
	gitServiceStr := params["git_service"]
	gitService, exists := registeredGitServices[gitServiceStr]
	if !exists {
		utils.Log.Warning("No git integration found for recieved webhook %v", gitServiceStr)
		r.Status(200)
		return
	}

	defer req.Body.Close()
	payload, err := ioutil.ReadAll(req.Body)
	if err != nil {
		utils.Log.Error("Failed to ready the webhook payload: %v", err)
		r.Status(200)
		return
	}

	go gitService.HandleWebhookEvent(payload)
	r.Status(200)
}
Example #24
0
// Sync doorbot users with a foreign data source using a bridge.
func Sync(render render.Render, r doorbot.Repositories, b bridges.Bridges, a *doorbot.Account, session *auth.Authorization) {

	var bUsers []*doorbot.BridgeUser
	var registered []*doorbot.BridgeUser
	var err error

	personRepo := r.PersonRepository()
	bUserRepo := r.BridgeUserRepository()

	var bridgesToSync = []uint{bridges.BridgeHub, bridges.BridgeHipChat}

	for _, bridgeId := range bridgesToSync {
		f := func() bool {
			users, err := b.GetUsers(bridgeId)

			for _, u := range users {
				log.WithFields(log.Fields{"user": *u}).Info("User")
			}
			if err != nil {
				log.WithFields(log.Fields{
					"error":      err,
					"account_id": a.ID,
					"bridge_id":  bridgeId,
				}).Error("Api::People->Sync bridge error")

				return false
			}

			existing, err := bUserRepo.FindByBridgeID(r.DB(), bridgeId)

			if err != nil {
				log.WithFields(log.Fields{
					"error":      err,
					"account_id": r.AccountScope(),
					"step":       "bridge-user-find-by-bridge-id",
					"bridge_id":  bridgeId,
				}).Error("Api::People->Sync database error")

				return false
			}

			registered = append(registered, existing...)
			bUsers = append(bUsers, users...)

			return true
		}

		f()
	}

	tx, err := r.Transaction()

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"step":       "transaction-create",
		}).Error("Api::People->Sync database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	var buser *doorbot.BridgeUser

	for _, u := range bUsers {
		log.WithFields(log.Fields{
			"account_id":        r.AccountScope(),
			"bridge_user_id":    u.UserID,
			"bridge_user_email": u.Email,
			"bridge_user_name":  u.Name,
		}).Debug("Api::People->Sync bridge user")

		buser = findRegistered(registered, u.UserID)

		if buser != nil {

			log.WithFields(log.Fields{
				"account_id":     r.AccountScope(),
				"bridge_user_id": buser.UserID,
				"person_id":      buser.PersonID,
			}).Debug("Api::People->Sync registered user found")

			person, err := personRepo.Find(tx, buser.PersonID)
			if err != nil {
				log.WithFields(log.Fields{
					"error":          err,
					"account_id":     r.AccountScope(),
					"bridge_user_id": buser.UserID,
					"person_id":      buser.PersonID,
					"step":           "person-find-from-bridge-id",
				}).Error("Api::People->Sync database error")

				break
			}

			person.Name = u.Name
			person.Email = u.Email
			person.PhoneNumber = u.PhoneNumber

			_, err = personRepo.Update(tx, person)

			if err != nil {
				log.WithFields(log.Fields{
					"error":          err,
					"account_id":     r.AccountScope(),
					"bridge_user_id": buser.UserID,
					"person_id":      buser.PersonID,
					"step":           "person-update-from-bridge-data",
				}).Error("Api::People->Sync database error")

				break
			}

			log.WithFields(log.Fields{
				"account_id":     r.AccountScope(),
				"bridge_user_id": buser.UserID,
				"person_id":      buser.PersonID,
			}).Info("Api::People->Sync person updated from bridge data")

			continue
		}

		log.WithFields(log.Fields{
			"account_id":        r.AccountScope(),
			"bridge_user_id":    u.UserID,
			"bridge_user_email": u.Email,
			"bridge_user_name":  u.Name,
		}).Info("Api::People->Sync new bridge user")

		// User does not exists. Create them
		args := doorbot.PersonArguments{
			Name:  u.Name,
			Email: u.Email,
		}

		person := doorbot.NewPerson(args)

		err = personRepo.Create(tx, person)
		if err != nil {
			log.WithFields(log.Fields{
				"error":          err,
				"account_id":     r.AccountScope(),
				"bridge_user_id": buser.UserID,
				"step":           "person-create-from-bridge-data",
			}).Error("Api::People->Sync database error")

			break
		}

		u.PersonID = person.ID
		err = bUserRepo.Create(tx, u)
		if err != nil {
			log.WithFields(log.Fields{
				"error":          err,
				"account_id":     r.AccountScope(),
				"bridge_user_id": buser.UserID,
				"step":           "bridge-user-create",
			}).Error("Api::People->Sync database error")

			break
		}
		continue
	}

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
		}).Error("Api::People->Sync error")

		tx.Rollback()

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	err = tx.Commit()
	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"step":       "transaction-commit",
		}).Error("Api::People->Sync database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	log.WithFields(log.Fields{
		"account_id": r.AccountScope(),
	}).Info("Api::People->Sync bridge sync completed.")

	render.Status(http.StatusNoContent)
}
Example #25
0
// Delete a person
func Delete(render render.Render, r doorbot.Repositories, params martini.Params, a *doorbot.Account, session *auth.Authorization) {
	id, err := strconv.ParseUint(params["id"], 10, 32)
	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	var logFields log.Fields
	var logMessage string

	switch session.Type {
	case auth.AuthorizationAdministrator:
		logFields = log.Fields{
			"account_id":      r.AccountScope(),
			"person_id":       id,
			"admnistrator_id": session.Administrator.ID,
		}
		logMessage = "Api::People->Delete user deleted by administrator"

	case auth.AuthorizationPerson:
		if !session.Person.IsAccountManager() {
			log.WithFields(log.Fields{
				"account_id":        r.AccountScope(),
				"person_id":         id,
				"request_person_id": session.Person.ID,
			}).Warn("Api::People->Delete forbidden")

			render.Status(http.StatusForbidden)
			return
		}

		logFields = log.Fields{
			"account_id":     r.AccountScope(),
			"person_id":      id,
			"modified_by_id": session.Person.ID,
		}

		logMessage = "Api::People->Put user deleted by user"

	default:
		log.WithFields(log.Fields{
			"account_id":        r.AccountScope(),
			"person_id":         id,
			"request_person_id": session.Person.ID,
		}).Warn("Api::People->Delete forbidden")

		render.Status(http.StatusForbidden)
		return
	}

	repo := r.PersonRepository()
	person, err := repo.Find(r.DB(), uint(id))

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"person_id":  person.ID,
			"step":       "person-find",
		}).Error("Api::People->Delete database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if person == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{"The specified person does not exists"}))
		return
	}

	_, err = repo.Delete(r.DB(), person)

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"person_id":  person.ID,
			"step":       "person-delete",
		}).Error("Api::People->Delete database error")

		render.Status(http.StatusInternalServerError)
		return
	}

	log.WithFields(logFields).Info(logMessage)

	render.Status(http.StatusNoContent)
}
Example #26
0
// Put updates a person
func Put(render render.Render, r doorbot.Repositories, params martini.Params, vm PersonViewModel, session *auth.Authorization) {
	id, err := strconv.ParseUint(params["id"], 10, 32)
	if err != nil {
		render.JSON(http.StatusBadRequest, doorbot.NewBadRequestErrorResponse([]string{"The id must be an unsigned integer"}))
		return
	}

	var logFields log.Fields
	var logMessage string
	canUpdateAccountType := false

	switch session.Type {
	case auth.AuthorizationAdministrator:
		logFields = log.Fields{
			"account_id":      r.AccountScope(),
			"person_id":       id,
			"admnistrator_id": session.Administrator.ID,
		}
		logMessage = "Api::People->Put user updated by administrator"

		canUpdateAccountType = true

	case auth.AuthorizationPerson:
		if uint(id) != session.Person.ID {
			if session.Person.IsAccountManager() {
				canUpdateAccountType = true
			} else {
				log.WithFields(log.Fields{
					"account_id":        r.AccountScope(),
					"person_id":         id,
					"request_person_id": session.Person.ID,
				}).Warn("Api::People->Delete forbidden")

				render.Status(http.StatusForbidden)
				return
			}
		}

		logFields = log.Fields{
			"account_id":        r.AccountScope(),
			"person_id":         id,
			"request_person_id": session.Person.ID,
		}

		logMessage = "Api::People->Put user updated by user"

	default:
		log.WithFields(log.Fields{
			"account_id":        r.AccountScope(),
			"person_id":         id,
			"request_person_id": session.Person.ID,
		}).Warn("Api::People->Put forbidden")

		render.Status(http.StatusForbidden)
		return
	}

	repo := r.PersonRepository()
	person, err := repo.Find(r.DB(), uint(id))

	if err != nil {
		log.WithFields(log.Fields{
			"error":      err,
			"account_id": r.AccountScope(),
			"person_id":  id,
			"step":       "person-find",
		}).Error("Api::People->Put database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	if person == nil {
		render.JSON(http.StatusNotFound, doorbot.NewEntityNotFoundResponse([]string{"The specified person does not exists"}))
		return
	}

	person.Name = vm.Person.Name
	person.Email = vm.Person.Email
	person.PhoneNumber = vm.Person.PhoneNumber
	person.Title = vm.Person.Title
	person.IsVisible = vm.Person.IsVisible
	person.IsAvailable = vm.Person.IsAvailable
	person.NotificationsEnabled = vm.Person.NotificationsEnabled
	person.NotificationsAppEnabled = vm.Person.NotificationsAppEnabled
	person.NotificationsChatEnabled = vm.Person.NotificationsChatEnabled
	person.NotificationsEmailEnabled = vm.Person.NotificationsEmailEnabled
	person.NotificationsSMSEnabled = vm.Person.NotificationsSMSEnabled

	if canUpdateAccountType {
		person.AccountType = vm.Person.AccountType
	}

	_, err = repo.Update(r.DB(), person)

	if err != nil {
		log.WithFields(log.Fields{
			"error":             err,
			"account_id":        r.AccountScope(),
			"person_id":         person.ID,
			"request_person_id": session.Person.ID,
			"step":              "person-update",
		}).Error("Api::People->Put database error")

		render.JSON(http.StatusInternalServerError, doorbot.NewInternalServerErrorResponse([]string{}))
		return
	}

	vm.Person = person

	log.WithFields(logFields).Info(logMessage)

	render.JSON(http.StatusOK, vm)
}
Example #27
0
func routeGetFinalReport(req *http.Request, r render.Render) {
	advrId := advertiserId(req)

	if advrId == "" {
		r.Status(401)
		return
	}

	reports := map[string]*Report{}
	adKeys, _ := rd.SMembers(advertiserKey(advrId)).Result()
	for _, adKey := range adKeys {
		ad, _ := rd.HGetAllMap(adKey).Result()
		if ad == nil {
			continue
		}

		imp, _ := strconv.Atoi(ad["impressions"])
		data := &Report{
			&Ad{
				ad["slot"],
				ad["id"],
				ad["title"],
				ad["type"],
				ad["advertiser"],
				ad["destination"],
				imp,
			},
			0,
			imp,
			nil,
		}
		reports[ad["id"]] = data
	}

	logs := getLog(advrId)

	for adId, report := range reports {
		log, exists := logs[adId]
		if exists {
			report.Clicks = len(log)
		}

		breakdown := &BreakdownReport{
			map[string]int{},
			map[string]int{},
			map[string]int{},
		}
		for i := range log {
			click := log[i]
			incr_map(&breakdown.Gender, click.Gender)
			incr_map(&breakdown.Agents, click.Agent)
			generation := "unknown"
			if click.Age != -1 {
				generation = strconv.Itoa(click.Age / 10)
			}
			incr_map(&breakdown.Generations, generation)
		}
		report.Breakdown = breakdown
		reports[adId] = report
	}

	r.JSON(200, reports)
}
Example #28
0
func Status(render render.Render) {

	//TODO setup a way to determine if the status should be different than 200
	render.Status(http.StatusOK)
}
Example #29
0
func routeGetAdAsset(r render.Render, res http.ResponseWriter, req *http.Request, params martini.Params) {
	slot := params["slot"]
	id := params["id"]
	ad := getAd(req, slot, id)
	if ad == nil {
		r.JSON(404, map[string]string{"error": "not_found"})
		return
	}
	content_type := "application/octet-stream"
	if ad.Type != "" {
		content_type = ad.Type
	}

	res.Header().Set("Content-Type", content_type)
	data, _ := rd.Get(assetKey(slot, id)).Result()

	range_str := req.Header.Get("Range")
	if range_str == "" {
		r.Data(200, []byte(data))
		return
	}

	re := regexp.MustCompile("^bytes=(\\d*)-(\\d*)$")
	m := re.FindAllStringSubmatch(range_str, -1)

	if m == nil {
		r.Status(416)
		return
	}

	head_str := m[0][1]
	tail_str := m[0][2]

	if head_str == "" && tail_str == "" {
		r.Status(416)
		return
	}

	head := 0
	tail := 0

	if head_str != "" {
		head, _ = strconv.Atoi(head_str)
	}
	if tail_str != "" {
		tail, _ = strconv.Atoi(tail_str)
	} else {
		tail = len(data) - 1
	}

	if head < 0 || head >= len(data) || tail < 0 {
		r.Status(416)
		return
	}

	range_data := data[head:(tail + 1)]
	content_range := fmt.Sprintf("bytes %d-%d/%d", head, tail, len(data))
	res.Header().Set("Content-Range", content_range)
	res.Header().Set("Content-Length", strconv.Itoa(len(range_data)))

	r.Data(206, []byte(range_data))
}
Example #30
0
func routePostAd(r render.Render, req *http.Request, params martini.Params) {
	slot := params["slot"]

	advrId := advertiserId(req)
	if advrId == "" {
		r.Status(404)
		return
	}

	req.ParseMultipartForm(100000)
	asset := req.MultipartForm.File["asset"][0]
	id := nextAdId()
	key := adKey(slot, id)

	content_type := ""
	if len(req.Form["type"]) > 0 {
		content_type = req.Form["type"][0]
	}
	if content_type == "" && len(asset.Header["Content-Type"]) > 0 {
		content_type = asset.Header["Content-Type"][0]
	}
	if content_type == "" {
		content_type = "video/mp4"
	}

	title := ""
	if a := req.Form["title"]; a != nil {
		title = a[0]
	}
	destination := ""
	if a := req.Form["destination"]; a != nil {
		destination = a[0]
	}

	rd.HMSet(key,
		"slot", slot,
		"id", id,
		"title", title,
		"type", content_type,
		"advertiser", advrId,
		"destination", destination,
		"impressions", "0",
	)

	f, _ := asset.Open()
	defer f.Close()
	buf := bytes.NewBuffer(nil)
	io.Copy(buf, f)

	fname := assetFile(slot, id)
	err := os.MkdirAll(filepath.Dir(fname), os.ModePerm)
	if err != nil {
		panic(err)
	}
	err = ioutil.WriteFile(fname, buf.Bytes(), os.ModePerm)
	if err != nil {
		panic(err)
	}

	if *isMaster {
		for i, ip := range internalIP {
			if i == 0 {
				continue
			}
			_, err := http.Post("http://"+ip+"/fs"+assetFile(slot, id), content_type, bytes.NewReader(buf.Bytes()))
			if err != nil {
				panic(err)
			}
		}
	}

	rd.RPush(slotKey(slot), id)
	rd.SAdd(advertiserKey(advrId), key)

	r.JSON(200, getAd(req, slot, id))
}