Beispiel #1
0
// AddTemplate inserts a template record
func (adaptor *Adaptor) AddTemplate(scopeTemplate ScopeTemplate) error {
	postURL := fmt.Sprintf("http://%s:%d/v1/permissions/scopesettemplates", adaptor.Host, adaptor.Port)
	b, err := json.Marshal(scopeTemplate)

	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"error": err.Error(), "method": "AddTemplate", "scopeTemplate": scopeTemplate})
		return fmt.Errorf("error marshalling scope template - %s", err)
	}
	data := bytes.NewBuffer(b)

	resp, err := http.Post(postURL, "application/json", data)
	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"error": err.Error(), "method": "AddTemplate", "scopeTemplate": scopeTemplate})
		return fmt.Errorf("error posting data '%s' to url %s", b, postURL)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusConflict {
		body, _ := ioutil.ReadAll(resp.Body)
		ln.Err("authzd adaptor error", ln.Map{"error": fmt.Sprintf("error posting data '%s' to url %s - got status %d, want 200 or 409; %s", b, postURL, resp.StatusCode, body), "method": "AddTemplate", "scopeTemplate": scopeTemplate})
		return fmt.Errorf("error posting data '%s' to url %s - got status %d, want 200 or 409; %s", b, postURL, resp.StatusCode, body)

	}

	return nil
}
Beispiel #2
0
func (b *Adaptor) ChangePackage(userID int, packageID int, immediateChange bool, addOn ...string) *adaptor.AdaptorError {
	var effectiveDate time.Time

	if immediateChange {
		effectiveDate = time.Now()
	} else {
		effectiveDate = FindDowngradeDate(time.Now())
	}

	putBody := BossUpdatePackageParams{
		PackageID:     packageID,
		AddOn:         addOn,
		EffectiveDate: effectiveDate.Format("2006-01-02"),
	}

	updatePackageURL := fmt.Sprintf("%s/billing_provider_api/v1/users/%d/user_package", b.bossURL, userID)

	authToken := fmt.Sprintf("token=%s", b.authToken)

	client := &http.Client{}

	data, err := json.Marshal(putBody)

	if err != nil {
		ln.Err("something went wrong marshalling change package put body", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("could not marshal put body")
	}

	req, err := http.NewRequest("PUT", updatePackageURL, bytes.NewReader(data))
	if err != nil {
		ln.Err("something went wrong creating http request for boss update package", ln.Map{"error": err.Error()})
		return adaptor.NewError("could not create put request")
	}
	req.Header.Set("Authorization", authToken)
	req.Header.Set("Content-Type", "application/json")

	curl := fmt.Sprintf("curl -v -X PUT %s -d '%s' --header 'Authorization: <auth token>' --header 'Content-Type: application/json'", updatePackageURL, string(data))
	resp, err := client.Do(req)

	if err != nil {
		ln.Err(fmt.Sprintf("something went wrong executing http request to boss update user package endpoint, %s", curl), ln.Map{"error": err.Error()})
		return adaptor.NewError("error when calling PUT")
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			ln.Err(fmt.Sprintf("Error reading response body, %s", curl), ln.Map{"error": err.Error(), "boss_status_code": resp.StatusCode})
			return adaptor.NewError("could not read response body")
		}

		ln.Err(fmt.Sprintf("Error posting to subscriptions, %s", curl), ln.Map{"status_code": resp.StatusCode, "response_body": string(b), "user_id": userID, "url": updatePackageURL})

		return adaptor.NewError("error when calling internal service")
	}

	return nil
}
Beispiel #3
0
// CreateUserScopeSet creates a scope set for a given user using a scope set template, returns scope_set_id
func (adaptor *Adaptor) CreateUserScopeSet(userID int, template string) (string, error) {
	postURL := fmt.Sprintf("http://%s:%d/v1/permissions/users/%d/scopeset", adaptor.Host, adaptor.Port, userID)

	data := bytes.NewBufferString(fmt.Sprintf(`{"new_template":"%s"}`, template))
	dataBackup := bytes.NewBufferString(fmt.Sprintf(`{"new_template":"%s"}`, template))
	resp, err := http.Post(postURL, "application/json", data)
	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"method": "SetUserTemplate", "user_id": userID, "template": template})
		return "", fmt.Errorf("error posting url %s - data %s - err %s", postURL, data, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated {
		body, _ := ioutil.ReadAll(resp.Body)
		ln.Err("authzd adaptor error", ln.Map{"method": "SetUserTemplate", "reason": fmt.Sprintf("error posting url %s - data %s - got status %d, want %d; body %s", postURL, dataBackup, resp.StatusCode, http.StatusCreated, body)})
		return "", fmt.Errorf("error posting url %s - data %s - got status %d, want %d; body %s", postURL, dataBackup, resp.StatusCode, http.StatusCreated, body)
	}
	var result scopeSetID

	err = json.NewDecoder(resp.Body).Decode(&result)

	if err != nil {
		return "", fmt.Errorf("error getting scope set id on create user scope set call")
	}

	return result.ID, nil

}
Beispiel #4
0
func (a *Adaptor) AssignExternalIP(userID int, ip string) *adaptor.AdaptorError {

	var eIP []ExternalIP

	err := a.apidClient.DoFunction("getExternalIp", url.Values{"ip": []string{ip}, "exclude_whitelabels": []string{strconv.Itoa(0)}}, &eIP)

	if err != nil {
		ln.Err("error when getting external ips of user", ln.Map{"error": err.Error(), "user_id": userID, "ip": ip})
		return adaptor.NewError("error when getting external ips of user")

	}
	params := url.Values{
		"ip":              []string{ip},
		"reseller_id":     []string{strconv.Itoa(userID)},
		"server_name_id":  []string{strconv.Itoa(eIP[0].ServerID)},
		"in_sender_score": []string{strconv.Itoa(eIP[0].InSenderScore)},
	}

	var result int
	err = a.apidClient.DoFunction("editExternalIp", params, &result)
	if err != nil {
		ln.Err("error when editing external ip of user", ln.Map{"error": err.Error(), "user_id": userID, "ip": ip})
		return adaptor.NewError("error when editing external ip of user")
	}

	return nil

}
Beispiel #5
0
func (b *Adaptor) Check() error {
	url := fmt.Sprintf("%s/healthcheck", b.bossURL)
	resp, err := http.Get(url)

	if err != nil {
		ln.Err(
			UnreachableErrorMessage,
			ln.Map{"error": UnreachableError,
				"bossURL": b.bossURL,
			},
		)
		return UnreachableError
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		ln.Err(
			UnreachableErrorMessage,
			ln.Map{
				"bossURL": b.bossURL,
			},
		)
		return UnreachableError
	}

	return nil
}
Beispiel #6
0
// GetCredentialScopeSetID returns the credentials's scope set id (uuid)
func (adaptor *Adaptor) GetCredentialScopeSetID(credentialID int) (string, error) {
	getURL := fmt.Sprintf("http://%s:%d/v1/permissions/credentials/%d/scopeset", adaptor.Host, adaptor.Port, credentialID)

	resp, err := http.Get(getURL)
	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"error": err.Error(), "credential_id": credentialID})
		return "", fmt.Errorf("error getting url %s - %s", getURL, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := ioutil.ReadAll(resp.Body)
		return "", fmt.Errorf("error getting url %s - got status %d, want %d; %s", getURL, resp.StatusCode, http.StatusOK, body)
	}

	data := scopeSetID{}

	err = json.NewDecoder(resp.Body).Decode(&data)
	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"error": err.Error(), "method": "GetCredentialScopeSetID", "credential_id": credentialID})
		return "", fmt.Errorf("error decoding body from url %s, %s", getURL, err)
	}

	return data.ID, nil
}
Beispiel #7
0
func (a *Adaptor) EditUserProfile(userProfile *client.UserProfile) (bool, *adaptor.AdaptorError) {
	var editSuccess int

	params, queryErr := query.Values(userProfile)

	if queryErr != nil {
		ln.Err("error query user profile", ln.Map{"err": queryErr.Error()})
		return false, adaptor.NewError("error query user profile")
	}

	err := a.apidClient.DoFunction("editUserProfile", params, &editSuccess)

	if err != nil {
		ln.Err("error updating user profile", ln.Map{"err": err.Error(), "user_profile": userProfile})
		return false, adaptor.NewError("error updating user profile")
	}

	if editSuccess == 0 {
		// check if the user exists
		user, adaptorError := a.GetUserProfile(userProfile.UserID)

		if adaptorError != nil {
			ln.Err("error when getting user profile", ln.Map{"err": adaptorError.Error(), "user_id": userProfile.UserID})
			return false, adaptor.NewError("error when getting user profile")
		}
		if user == nil {
			return false, adaptor.NewErrorWithStatus("user profile not found", http.StatusNotFound)
		}
		// no fields were changed
		return true, nil
	}

	return true, nil
}
Beispiel #8
0
func (u *urlCache) refresh() error {
	req, _ := http.NewRequest("GET", u.billingProviderURL, nil)

	req.Header.Set("Authorization", fmt.Sprintf("token=%s", u.authToken))
	req.Header.Set("Content-Type", "application/json")

	client := http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		ln.Err("could not refresh billing provider urls cache", ln.Map{"error": err.Error()})
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		ln.Err("error when getting billing provider urls", ln.Map{"code": resp.StatusCode})
		return errors.New("could not get billing provider urls")
	}

	var urls BillingProviderURLResponse
	err = json.NewDecoder(resp.Body).Decode(&urls)

	u.cache.Set(URLCacheKeyAccountUrl, urls.AccountURL)
	u.cache.Set(URLCacheKeyPackagePreviewURL, urls.PackagePreviewURL)
	u.cache.Set(URLCacheKeyAccountSubscriptionURL, urls.AccountSubscriptionURL)
	u.cache.Set(URLCacheKeyAccountPaymentMethodURL, urls.AccountPaymentMethodURL)
	u.cache.Set(URLCacheKeyAccountCollectURL, urls.AccountCollectURL)

	return nil
}
Beispiel #9
0
func (a *Adaptor) insertNewCompetitor(userID int, otherProvider string) (int, *adaptor.AdaptorError) {
	addParams := url.Values{
		"user_id":    []string{strconv.Itoa(userID)},
		"competitor": []string{otherProvider},
	}

	columns := NewCrudColumns()
	columns.AddColumns(addParams)

	// add new user package
	var ok string
	err := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"competitors"},
		"values":    []string{columns.String()},
	}, &ok)

	if err != nil {
		ln.Err("unable to add to competitor table", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	if ok != "success" {
		ln.Err("error adding to competitor table", ln.Map{"err": fmt.Sprintf("%s - %s", ok, err.Error())})
		return 0, adaptor.NewError("internal data storage error")
	}

	return a.getInvalidCompetitorID(userID, otherProvider)
}
Beispiel #10
0
func (g *Adaptor) ChangePassword(userID int, password string) error {

	changePasswordURL := fmt.Sprintf("http://%s:%d/password", g.GandalfHost, g.GandalfPort)

	changePWReq := &ChangePasswordRequest{
		UserID:   userID,
		Password: password,
	}

	data, err := json.Marshal(changePWReq)

	if err != nil {
		ln.Err("could not marshal changePassword request parameters", ln.Map{"error": err.Error(), "user_id": userID})
		return errors.New(ErrorChangePassword)
	}

	req, err := http.NewRequest("PUT", changePasswordURL, bytes.NewBuffer(data))

	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		ln.Err("error posting to gandalf password endpoint", ln.Map{"error": err.Error(), "user_id": userID})
		return errors.New(ErrorChangePassword)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		ln.Err("error calling password endpoint in gandalf", ln.Map{"status": resp.StatusCode, "user_id": userID})
		return errors.New(ErrorChangePassword)
	}

	return nil
}
Beispiel #11
0
func (a *Adaptor) PackageIDFromUUID(packageUUID string) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"tableName": []string{"package"},
		"where":     []string{fmt.Sprintf(`{"uuid":"%s"}`, packageUUID)},
	}

	var packages []struct {
		ID int `json:"id"`
	}

	err := a.apidClient.DoFunction("get", params, &packages)

	if err != nil {
		ln.Err("error calling get for user package", ln.Map{"error": err.Error(), "uuid": packageUUID})
		formattedErr := adaptor.NewError("unable to process request")
		return -1, formattedErr

	}

	if len(packages) != 1 {
		ln.Err("did not get one result back from get call for user package", ln.Map{"uuid": packageUUID})
		formattedErr := adaptor.NewError(ErrorNoPackagesFound)
		return -1, formattedErr
	}

	return packages[0].ID, nil
}
Beispiel #12
0
func (g *Adaptor) Check() error {
	resp, err := http.Get(fmt.Sprintf("http://%s:%d/healthcheck", g.GandalfHost, g.GandalfHealthcheckPort))
	if err != nil {
		ln.Err(
			ErrorUnreachable,
			ln.Map{
				"error":                    err.Error(),
				"gandalf_host":             g.GandalfHost,
				"gandalf_healthcheck_port": g.GandalfHealthcheckPort,
			},
		)
		return unreachable
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		ln.Err(
			ErrorUnreachable,
			ln.Map{
				"gandalf_host":             g.GandalfHost,
				"gandalf_healthcheck_port": g.GandalfHealthcheckPort,
			},
		)
		return unreachable
	}
	return nil
}
Beispiel #13
0
func (a *Adaptor) InsertDeactivationReason(userID int, reason string, moving bool, inHouse bool, otherProvider string, comment string) *adaptor.AdaptorError {
	reasonID, adaptorErr := a.getReasonID(reason)
	if adaptorErr != nil {
		return adaptorErr
	}

	if inHouse {
		otherProvider = "in house"
	}

	competitorID, adaptorErr := a.getValidCompetitorID(otherProvider)
	if adaptorErr != nil {
		ln.Err("unable to get competitor id - "+otherProvider, ln.Map{"err": adaptorErr})
		return adaptorErr
	}
	if competitorID == 0 {
		competitorID, adaptorErr = a.insertNewCompetitor(userID, otherProvider)
		if adaptorErr != nil {
			ln.Err("unable to set new competitor id - "+otherProvider, ln.Map{"err": adaptorErr})
			return adaptorErr
		}
	}

	params := url.Values{
		"user_id":      []string{strconv.Itoa(userID)},
		"moving":       []string{strconv.Itoa(boolToInt(moving))},
		"event_type":   []string{"Cancellation"},
		"new_provider": []string{strconv.Itoa(competitorID)},
		"notes":        []string{comment},
		"reason":       []string{strconv.Itoa(reasonID)},
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	var ok string
	err := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_churn"},
		"values":    []string{columns.String()},
	}, &ok)

	if err != nil {
		ln.Info("unable to call apid add on user_churn", ln.Map{"err": err.Error(), "user_id": userID})
		return adaptor.NewError("internal data storage error")
	}

	if ok != "success" {
		ln.Info("unexpected response from apid add on user_churn", ln.Map{"err": fmt.Sprintf("got '%s', want 'success'", ok), "user_id": userID})
	}

	return nil
}
Beispiel #14
0
func (a *Adaptor) SetUserPackage(userID int, packageID int) *adaptor.AdaptorError {
	var delSuccess int
	var userPackage string
	packageIDString := strconv.Itoa(packageID)

	pkg, adaptorErr := a.GetPackage(packageID)
	if adaptorErr != nil {
		return adaptorErr
	}

	// delete the user's old package
	err := a.apidClient.DoFunction("delete", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{`{"user_id" : "` + strconv.Itoa(userID) + `"}`},
	}, &delSuccess)

	if err != nil {
		ln.Err("Something went wrong trying to delete the user's current package", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("Something went wrong trying to delete the user's current package")
	}

	params := url.Values{
		"user_id":          []string{strconv.Itoa(userID)},
		"status":           []string{strconv.Itoa(UserStatusSendGridPaid)},
		"package_id":       []string{packageIDString},
		"package_group_id": []string{strconv.Itoa(pkg.GroupID)},
		"package_status":   []string{strconv.Itoa(PackageStatusActive)},
		"start_date":       []string{time.Now().Format("2006-01-02")},
		"end_date":         []string{now.New(time.Now().AddDate(0, 1, 0)).BeginningOfMonth().Format("2006-01-02")},
		"subusers_limit":   []string{strconv.Itoa(DefaultSubuserLimit)},
		"updated_at":       []string{time.Now().String()},
	}

	columns := NewCrudColumns()
	columns.AddColumns(params)

	// add new user package
	err = a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_package"},
		"values":    []string{columns.String()},
	}, &userPackage)

	if err != nil {
		ln.Err("Something went wrong trying to add a package for the user", ln.Map{"error": err.Error(), "user_id": userID, "package_id": packageID})
		return adaptor.NewError("Something went wrong trying to add the user's package")

	}

	return nil
}
Beispiel #15
0
func (g *Adaptor) GetAuthorizationToken(userid int) (string, error) {
	// Get existing token if it exists
	getURL := fmt.Sprintf("http://%s:%d/tokens/%d", g.GandalfHost, g.GandalfPort, userid)

	resp, err := http.Get(getURL)

	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	var tokens []gandalfToken
	err = json.NewDecoder(resp.Body).Decode(&tokens)

	if err != nil {
		ln.Err("error when decoding tokens", ln.Map{"method": "GetAuthorizationToken", "user_id": userid, "error": err.Error()})
	}

	if len(tokens) > 0 {
		return tokens[0].Token, nil
	}

	generateURL := fmt.Sprintf("http://%s:%d/generate/%d", g.GandalfHost, g.GandalfPort, userid)
	client := http.Client{}

	req, err := http.NewRequest("GET", generateURL, nil)
	req.Header.Set("Content-Type", "application/json")
	if err != nil {
		ln.Err("error when create request for the generate token url", ln.Map{"method": "GetAuthorizationToken", "user_id": userid, "error": err.Error()})
		return "", getTokenError
	}

	resp, err = client.Do(req)
	if err != nil {
		ln.Err("error when calling generate token", ln.Map{"method": "GetAuthorizationToken", "user_id": userid, "error": err.Error()})
		return "", getTokenError
	}
	defer resp.Body.Close()

	var tokenResponse TokenResponse
	err = json.NewDecoder(resp.Body).Decode(&tokenResponse)
	if err != nil {
		ln.Err("error when decoding gnereated token response", ln.Map{"method": "GetAuthorizationToken", "user_id": userid, "error": err.Error()})
		return "", getTokenError
	}

	return tokenResponse.Token, nil

}
Beispiel #16
0
func (a *Adaptor) getValidCompetitorID(otherProvider string) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"tableName": []string{"competitors"},
		"where":     []string{fmt.Sprintf(`{"competitor":"%s"}`, otherProvider)},
	}
	competition := []competitor{}

	err := a.apidClient.DoFunction("get", params, &competition)
	if err != nil {
		ln.Err("unable to get competitors value", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	if len(competition) == 0 {
		return 0, nil
	}

	if len(competition) >= 1 {
		// only return a valid competitor id if there is no user id
		for _, c := range competition {
			if c.UserID == 0 {
				return c.UserID, nil
			}
		}
	}
	// if we got here, it means all entries in the competitor table were tied to a user id
	// meaning the BI team has not vetted the entry
	ln.Info("no valid competitor found", nil)
	return 0, adaptor.NewError("internal data storage error")
}
Beispiel #17
0
func (b *Adaptor) CollectBalance(userID int) *adaptor.AdaptorError {
	ln.Debug("Boss CollectBalance()", ln.Map{"account ID": userID})

	authToken := fmt.Sprintf("token=%s", b.authToken)

	client := &http.Client{}

	accountCollectURL, err := b.urls.accountCollectURL(userID)

	if err != nil {
		ln.Err("error when collecting balance, could not get url", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError("could not get the collect url")
	}

	req, err := http.NewRequest("PUT", accountCollectURL, nil)
	if err != nil {
		ln.Err("something went wrong creating http request for boss collect", ln.Map{"error": err.Error()})
		return adaptor.NewError("could not create http request")
	}
	req.Header.Set("Authorization", authToken)
	req.Header.Set("Content-Type", "application/json")

	curl := fmt.Sprintf("curl -v -X PUT %s --header 'Authorization: <auth token>' --header 'Content-Type: application/json'", accountCollectURL)
	resp, err := client.Do(req)

	if err != nil {
		ln.Err(fmt.Sprintf("something went wrong executing http request to boss collect endpoint, %s", curl), ln.Map{"error": err.Error()})
		return adaptor.NewError("could not execute request to boss collect endpoint")
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		respBody, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			ln.Err(fmt.Sprintf("Error to read response body, %s", curl), ln.Map{"error": err.Error(), "boss_status_code": resp.StatusCode})
			return adaptor.NewError("could not read response body")
		}

		ln.Err(fmt.Sprintf("Error putting to collect, %s", curl), ln.Map{"status_code": resp.StatusCode, "response_body": string(respBody), "user_id": userID, "url": accountCollectURL})

		return adaptor.NewError("error when calling internal service")
	}

	return nil
}
Beispiel #18
0
func (g *Adaptor) ValidatePassword(username string, password string) (*PasswordValidationResponse, error) {
	authenticationURL := fmt.Sprintf("http://%s:%d/validate/password", g.GandalfHost, g.GandalfPort)

	authenticationReq := PasswordValidationRequest{
		Username: username,
		Password: password,
	}

	data, err := json.Marshal(authenticationReq)

	if err != nil {
		ln.Err("could not marshal authentication request parameters", ln.Map{"error": err.Error(), "username": username})
		return nil, errors.New(ErrorAuthentication)
	}

	req, err := http.NewRequest("POST", authenticationURL, bytes.NewBuffer(data))

	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		ln.Err("error posting to gandalf authentication endpoint", ln.Map{"error": err.Error(), "username": username})
		return nil, errors.New(ErrorAuthentication)
	}

	defer resp.Body.Close()
	var authenticationResp PasswordValidationResponse

	err = json.NewDecoder(resp.Body).Decode(&authenticationResp)

	if err != nil {
		ln.Err("error decoding response from gandalf", ln.Map{"error": err.Error(), "username": username})
		return nil, errors.New(ErrorAuthentication)
	}

	if authenticationResp.Error != "" {
		if authenticationResp.Error == "Unauthorized" {
			ln.Info("authentication failed because of bad credentials", ln.Map{"username": username})
			return nil, errors.New(ErrorBadCredentials)
		}
		ln.Err("authentication failed", ln.Map{"username": username, "error": authenticationResp.Error})
		return nil, errors.New(ErrorAuthentication)
	}

	return &authenticationResp, nil
}
Beispiel #19
0
// Get the first available IP and assign it to the user.  Set that IP as the user send IP
func (a *Adaptor) AssignFirstIP(userID int) *adaptor.AdaptorError {
	locations, err := a.getFirstIPLocation()

	if len(locations) == 0 {
		ln.Info("no locations found for first_ip policy", ln.Map{"locations": locations})
		return adaptor.NewError("no locations found for first_ip policy")
	}

	if err != nil {
		ln.Err("error when getting server locations", ln.Map{"error": err.Error()})
		return adaptor.NewError("error when getting server locations")
	}

	r := rand.New(rand.NewSource(time.Now().Unix()))

	params := url.Values{
		"userid":          []string{strconv.Itoa(userID)},
		"limit":           []string{strconv.Itoa(1)},
		"server_location": []string{strconv.Itoa(locations[r.Intn(len(locations))])},
	}

	// Grab the first available IP and immediately assign it to the user
	var IP []string
	apidErr := a.apidClient.DoFunction("assignBestAvailableOp", params, &IP)
	if apidErr != nil {
		ln.Err("error assigning best ips", ln.Map{"error": apidErr.Error(), "params": params})
		return adaptor.NewError("error assigning best available ips")
	}

	if len(IP) == 0 {
		ln.Info("no available ips", ln.Map{"locations": locations})
		return adaptor.NewError("no available ips")
	}

	// assign ip to user send ip
	_, err = a.AddUserSendIP(userID, IP[0])
	if err != nil {
		ln.Err("could not add ip to user send ips table", ln.Map{"err": err.Error(), "user_id": userID})
		return adaptor.NewError("could not add ip to user send ips table")
	}

	return nil
}
Beispiel #20
0
func (u *urlCache) accountCollectURL(userID int) (string, error) {
	url, ok := u.cache.Get(URLCacheKeyAccountCollectURL)
	if !ok {
		err := u.refresh()
		if err != nil {
			ln.Err("unable to get boss account collect url (refresh)", ln.Map{"err": err.Error(), "user_id": userID})
			return "", errors.New("could not refresh cache")
		}
		url, ok = u.cache.Get(URLCacheKeyAccountCollectURL)

		if !ok {
			ln.Err("unable to get boss account collect url (cache miss)", ln.Map{"err": err.Error(), "user_id": userID})
			return "", errors.New("missing from cache even after refresh")
		}

	}

	return strings.Replace(url, ":account_id", strconv.Itoa(userID), 1), nil
}
Beispiel #21
0
func (a *Adaptor) AddUserFingerprint(talon TalonFingerprint) (bool, *adaptor.AdaptorError) {
	var success string

	v, queryErr := query.Values(talon)

	if queryErr != nil {
		ln.Err("error query talon", ln.Map{"err": queryErr.Error()})
		return false, adaptor.NewError("error query talon")
	}

	//turn timezone into string
	tz, err := json.Marshal(talon.Timezone)

	if err != nil {
		ln.Err("error when parsing talon timezone", ln.Map{"err": err.Error()})
		return false, adaptor.NewError("error parsing timezone")
	}

	v.Set("timezone", string(tz))

	columns := NewCrudColumns()
	columns.AddColumns(v)
	addErr := a.apidClient.DoFunction("add", url.Values{
		"tableName": []string{"user_fingerprints"},
		"values":    []string{columns.String()},
	}, &success)

	if addErr != nil {
		if strings.Contains(addErr.Error(), "key exists") {
			return true, nil
		}
		ln.Err("error adding user fingerprint", ln.Map{"err": addErr.Error()})
		formattedErr := adaptor.NewError("error adding user fingerprint")
		return false, formattedErr
	}

	if success == "success" {
		return true, nil
	}

	return false, adaptor.NewError("could not add user fingerprint")
}
Beispiel #22
0
func (adaptor *Adaptor) DeleteCredentialScopeSet(credentialID int) error {
	postURL := fmt.Sprintf("http://%s:%d/v1/permissions/credentials/%d/scopeset", adaptor.Host, adaptor.Port, credentialID)
	req, _ := http.NewRequest("DELETE", postURL, nil)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		ln.Err("authzd adaptor error", ln.Map{"error": err.Error(), "method": "DeleteCredentialScopeSet", "credential_id": credentialID})
		return fmt.Errorf("error deleting credential scope set for credential %d", credentialID)
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := ioutil.ReadAll(resp.Body)
		ln.Err("authzd adaptor error", ln.Map{"error": fmt.Sprintf("error deleting data '%s' to url %s - got status %d, want 200 ; %s", postURL, resp.StatusCode, body), "method": "DeleteCredentialScopeSet", "credential_id": credentialID})
		return fmt.Errorf("error posting to url %s - got status %d, want 200; %s", postURL, resp.StatusCode, body)
	}

	return nil
}
Beispiel #23
0
func (a *Adaptor) getInvalidCompetitorID(userID int, otherProvider string) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"tableName": []string{"competitors"},
		"where":     []string{fmt.Sprintf(`{"competitor":"%s","user_id":"%d"}`, otherProvider, userID)},
	}
	competition := []competitor{}

	err := a.apidClient.DoFunction("get", params, &competition)
	if err != nil {
		ln.Err("unable to get competitors value", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	if len(competition) != 1 {
		ln.Err("did not get back single entry from competitor table", ln.Map{"err": err.Error()})
		return 0, adaptor.NewError("internal data storage error")
	}

	return competition[0].ID, nil
}
Beispiel #24
0
func (a *Adaptor) DeactivateUserPackage(userID int) *adaptor.AdaptorError {
	var result string
	err := a.apidClient.DoFunction("update", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{fmt.Sprintf(`{"user_id":"%d"}`, userID)},
		"values":    []string{fmt.Sprintf(`[{"package_status":"%d"}]`, PackageStatusPendingCancellation)},
	}, &result)
	if err != nil {
		ln.Err("Error deactivating user package", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError(err.Error())
	}
	return nil
}
Beispiel #25
0
func (a *Adaptor) GetUserPackage(userID int) (*UserPackage, *adaptor.AdaptorError) {
	params := url.Values{
		"userid": []string{strconv.Itoa(userID)},
	}
	var userPackage UserPackageWrapper

	err := a.apidClient.DoFunction("getUserPackageType", params, &userPackage)
	if err != nil {
		ln.Err("error calling getUserPackageType", ln.Map{"error": err.Error()})
		formattedErr := adaptor.NewError(err.Error())
		return nil, formattedErr
	}

	// todo - investigate if we can remove getUserPackageType in favor of get
	//        or add package id to getUserPackageType call
	nextParams := url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{fmt.Sprintf(`{"user_id":%d}`, userID)},
	}
	userPkg := []struct {
		ID int `json:"package_id"`
	}{}
	err = a.apidClient.DoFunction("get", nextParams, &userPkg)
	if err != nil {
		ln.Err("error calling get for user package", ln.Map{"error": err.Error(), "user_id": userID})
		formattedErr := adaptor.NewError("unable to process request")
		return nil, formattedErr
	}
	if len(userPkg) != 1 {
		ln.Err("did not get one result back from get call for user package", ln.Map{"user_id": userID})
		formattedErr := adaptor.NewError("unable to process request")
		return nil, formattedErr
	}

	userPackage.Package.ID = userPkg[0].ID

	return userPackage.Package, nil
}
Beispiel #26
0
func (a *Adaptor) CountExternalIP(userID int) (int, *adaptor.AdaptorError) {
	params := url.Values{
		"userid": []string{strconv.Itoa(userID)},
	}

	var countIps int
	err := a.apidClient.DoFunction("countExternalIp", params, &countIps)
	if err != nil {
		ln.Err("error retrieving external IPs count", ln.Map{"error": err.Error(), "user_id": userID})
		return 0, adaptor.NewError("error retrieving external IPs count")
	}

	return countIps, nil
}
Beispiel #27
0
func (a *Adaptor) UpdateUserBI(provision client.Provision) *adaptor.AdaptorError {
	var response string
	adaptorErr := a.apidClient.DoFunction("update", url.Values{
		"tableName": []string{"user_signup_bi"},
		"where":     []string{fmt.Sprintf(`{"user_id" : "%d"}`, provision.UserProfile.UserID)},
		"values": []string{fmt.Sprintf(
			`[{"user_persona": "%s"}, {"industry": "%s"}, {"volume": "%s"}]`,
			provision.UserPersona, provision.Industry, provision.EmailVolume)}},
		&response,
	)

	if adaptorErr != nil {
		ln.Err("unable to update user signup BI", ln.Map{"err": adaptorErr.Error(), "data": provision})
		return adaptor.NewError("error storing profile information")
	}

	if response != "success" {
		ln.Err("nonsuccessful response updating user signup BI", ln.Map{"err": "unexpected result" + response, "user_id": provision.UserProfile.UserID})
		return adaptor.NewError("error storing profile information")
	}

	return nil
}
Beispiel #28
0
func (a *Adaptor) UpdateUserInitialPackageBI(userID int, packageID int) *adaptor.AdaptorError {
	// formattedBI has the proper name mapping for the db
	type formattedBI struct {
		InitialPackage int `json:"initial_package,omitempty"`
	}

	updateData := formattedBI{
		InitialPackage: packageID,
	}

	jsonBytes, err := json.Marshal([]formattedBI{updateData})

	if err != nil {
		ln.Err(fmt.Sprintf("unable to marshal updateData"), ln.Map{"err": err.Error()})
		return adaptor.NewError(ErrorDataStorage)
	}

	// store the BI data
	var addResult string
	err = a.apidClient.DoFunction("update", url.Values{
		"tableName": []string{"user_signup_bi"},
		"values":    []string{string(jsonBytes)},
		"where":     []string{fmt.Sprintf(`{"user_id":"%d"}`, userID)},
	}, &addResult)

	if err != nil {
		ln.Err(fmt.Sprintf("unable to call apid update method on user_signup_bi"), ln.Map{"err": err.Error()})
		return adaptor.NewError(ErrorDataStorage)
	}

	if addResult != ApidSuccess {
		ln.Err(fmt.Sprintf("apid set for user_signup_bi returned '%s', want 'success'", addResult), nil)
		return adaptor.NewError(ErrorDataStorage)
	}

	return nil
}
Beispiel #29
0
func (a *Adaptor) GenScopeSetTemplateName(userID int) (string, *adaptor.AdaptorError) {
	userPkg := make([]genericUserPackage, 0)
	pkg := make([]GenericAPIDResult, 0)
	pkgGroup := make([]GenericAPIDResult, 0)

	err := a.apidClient.DoFunction("get", url.Values{
		"tableName": []string{"user_package"},
		"where":     []string{fmt.Sprintf(`{"user_id":%d}`, userID)},
	}, &userPkg)

	if err != nil || len(userPkg) != 1 {
		ln.Err("error with apid crud get for user package", ln.Map{"err": err.Error()})
		return "", adaptor.NewError("unable to get package information")
	}

	err = a.apidClient.DoFunction("get", url.Values{
		"tableName": []string{"package"},
		"where":     []string{fmt.Sprintf(`{"id":%d}`, userPkg[0].PackageID)},
	}, &pkg)

	if err != nil || len(pkg) != 1 {
		ln.Err("error with apid crud get for package", ln.Map{"err": fmt.Sprintf("%s %v", err.Error(), pkg)})
		return "", adaptor.NewError("unable to get package information")
	}

	err = a.apidClient.DoFunction("get", url.Values{
		"tableName": []string{"package_group"},
		"where":     []string{fmt.Sprintf(`{"id":%d}`, userPkg[0].PackageGroupID)},
	}, &pkgGroup)

	if err != nil || len(pkgGroup) != 1 {
		ln.Err("error with apid crud get for package group", ln.Map{"err": fmt.Sprintf("%s %v", err.Error(), pkgGroup)})
		return "", adaptor.NewError("unable to get package information")
	}

	return fmt.Sprintf("%s::%s", pkgGroup[0].Name, pkg[0].Name), nil
}
Beispiel #30
0
func (a *Adaptor) RemovePunitiveAction(userID int) *adaptor.AdaptorError {
	var result string
	currentDate := time.Now().Format("2006-01-02 15:04:05")
	err := a.apidClient.DoFunction("update", url.Values{
		"tableName": []string{"punitive_actions"},
		"where":     []string{fmt.Sprintf(`{"user_id":"%d"}`, userID)},
		"values":    []string{fmt.Sprintf(`[{"active":0}, {"last_action":"%s"}]`, currentDate)},
	}, &result)
	if err != nil {
		ln.Err("Error removing punitive action", ln.Map{"error": err.Error(), "user_id": userID})
		return adaptor.NewError(err.Error())
	}

	return nil
}