// ApproveInvite approves an invitation of a user into an organzation by
// encoding them into a Keyring.
356014
func (e *Engine) ApproveInvite(ctx context.Context, notifier *observer.Notifier,
	InviteID *identity.ID) (*envelope.OrgInvite, error) {

	n := notifier.Notifier(3)

	invite, err := e.client.OrgInvites.Get(ctx, InviteID)
	if err != nil {
		log.Printf("could not fetch org invitation: %s", err)
		return nil, err
	}

	if invite.Body.State != primitive.OrgInviteAcceptedState {
		log.Printf("invitation not in accepted state: %s", invite.Body.State)
		return nil, &apitypes.Error{
			Type: apitypes.BadRequestError,
			Err:  []string{"Invite must be accepted before it can be approved"},
		}
	}

	n.Notify(observer.Progress, "Invite retrieved", true)

	v1members, v2members, err := createKeyringMemberships(ctx, e.crypto,
		e.client, e.session, invite.Body.OrgID, invite.Body.InviteeID)
	if err != nil {
		return nil, err
	}

	n.Notify(observer.Progress, "Keyring memberships created", true)

	invite, err = e.client.OrgInvites.Approve(ctx, InviteID)
	if err != nil {
		log.Printf("could not approve org invite: %s", err)
		return nil, err
	}

	n.Notify(observer.Progress, "Invite approved", true)

	if len(v1members) != 0 {
		_, err = e.client.KeyringMember.Post(ctx, v1members)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return nil, err
		}
	}

	for _, member := range v2members {
		err = e.client.Keyring.Members.Post(ctx, member)
		if err != nil {
			log.Printf("error uploading memberships: %s", err)
			return nil, err
		}
	}

	return invite, nil
}
1292917
func (service *IYOEmailAddressValidationService) SendOrganizationInviteEmail(request *http.Request, invite *invitations.JoinOrganizationInvitation) (err error) {
	InviteURL := fmt.Sprintf(invitations.InviteURL, request.Host, url.QueryEscape(invite.Code))
	templateParameters := EmailWithButtonTemplateParams{
		Url:        InviteURL,
		Username:   invite.EmailAddress,
		Title:      "It's You Online organization invitation",
		Text:       fmt.Sprintf("You have been invited to the %s organization on It's You Online. Click the button below to accept the invitation.", invite.Organization),
		ButtonText: "Accept invitation",
		Reason:     "You’re receiving this email because someone invited you to an organization at ItsYou.Online. If you think this was a mistake please ignore this email.",
		LogoUrl:    fmt.Sprintf("https://%s/assets/img/its-you-online.png", request.Host),
	}
	message, err := tools.RenderTemplate(emailWithButtonTemplateName, templateParameters)
	if err != nil {
		return
	}
	subject := fmt.Sprintf("You have been invited to the %s organization", invite.Organization)
	recipients := []string{invite.EmailAddress}
	go service.EmailService.Send(recipients, subject, message)
	return
}
811327
func (o *OrgInvitesClient) Send(ctx context.Context, email string, orgID, inviterID identity.ID, teamIDs []identity.ID) error {
	now := time.Now()

	inviteBody := primitive.OrgInvite{
		OrgID:        &orgID,
		InviterID:    &inviterID,
		PendingTeams: teamIDs,
		Email:        email,
		Created:      &now,
		// Null values below
		InviteeID:  nil,
		ApproverID: nil,
		Accepted:   nil,
		Approved:   nil,
	}

	ID, err := identity.NewMutable(&inviteBody)
	if err != nil {
		return err
	}

	invite := envelope.OrgInvite{
		ID:      &ID,
		Version: 1,
		Body:    &inviteBody,
	}

	return o.client.RoundTrip(ctx, "POST", "/org-invites", nil, &invite, nil)
}
659345
func (s *ShareResult) SetInviteePrincipalId(v string) *ShareResult {
	s.InviteePrincipalId = &v
	return s
}
660777
func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
	body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID))
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}
1307317
func (s *invitationServiceImpl) Rescind(ctx context.Context, rescindingUserID, invitationID uuid.UUID) error {
	// Locate the invitation
	inv, err := s.Repositories().InvitationRepository().Load(ctx, invitationID)
	if err != nil {
		return errors.NewNotFoundErrorFromString(fmt.Sprintf("invalid identifier '%s' provided for invitation", invitationID.String()))
	}

	// Create the permission service
	permService := s.Services().PermissionService()

	if inv.InviteTo != nil {
		// Lookup identity with InviteTo ID
		inviteToIdentity, err := s.Repositories().Identities().Load(ctx, *inv.InviteTo)
		if err != nil {
			return errors.NewNotFoundErrorFromString(fmt.Sprintf("invalid identifier '%s' provided for organization, team or security group", inv.InviteTo.String()))
		}

		if !inviteToIdentity.IdentityResourceID.Valid {
			return errors.NewNotFoundErrorFromString(fmt.Sprintf("specified identity '%s' has no resource", inv.InviteTo.String()))
		}

		identityResource, err := s.Repositories().ResourceRepository().Load(ctx, inviteToIdentity.IdentityResourceID.String)
		if err != nil {
			return errors.NewInternalError(ctx, err)
		}

		// Confirm that the rescinding user has the necessary scope to manage members for the organization, team or security group
		err = permService.RequireScope(ctx, rescindingUserID, inviteToIdentity.IdentityResourceID.String, authorization.ScopeForManagingRolesInResourceType(identityResource.ResourceType.Name))
		if err != nil {
			return err
		}
	} else if inv.ResourceID != nil {
		// Lookup a resource with the ResourceID value
		inviteToResource, err := s.Repositories().ResourceRepository().Load(ctx, *inv.ResourceID)
		if err != nil {
			return errors.NewNotFoundErrorFromString(fmt.Sprintf("invalid identifier '%s' provided for resource", *inv.ResourceID))
		}

		// Confirm that the rescinding user has the manage members scope for the resource
		err = permService.RequireScope(ctx, rescindingUserID, inviteToResource.ResourceID, authorization.ScopeForManagingRolesInResourceType(inviteToResource.ResourceType.Name))
		if err != nil {
			return err
		}
	}

	err = s.ExecuteInTransaction(func() error {
		// Delete the invitation
		return s.Repositories().InvitationRepository().Delete(ctx, invitationID)
	})
	return err
}
986592
func (authy *Authy) SendApprovalRequest(userID string, message string, details Details, params url.Values) (*ApprovalRequest, error) {
	addParamsForOneTouch(params, message, details)
	path := fmt.Sprintf(`/onetouch/json/users/%s/approval_requests`, url.QueryEscape(userID))

	response, err := authy.DoRequest("POST", path, params)
	if err != nil {
		return nil, err
	}

	defer closeResponseBody(response)
	return NewApprovalRequest(response)
}
305986
func (o *InvitationManager) FilterByUser(username string, status string) ([]JoinOrganizationInvitation, error) {
	orgRequests := []JoinOrganizationInvitation{}
	if status == "" {
		return o.GetByUser(username)
	}
	qry := bson.M{
		"user":   username,
		"status": status,
	}
	err := o.collection.Find(qry).All(&orgRequests)
	return orgRequests, err
}
833274
func NewInvitationManager(r *http.Request) *InvitationManager {
	session := db.GetDBSession(r)
	return &InvitationManager{
		session:    session,
		collection: getOrganizationRequestCollection(session),
	}
}
1232073
func (api OrganizationsAPI) RemovePendingInvitation(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]
	searchString := mux.Vars(r)["searchstring"]
	invitationMgr := invitations.NewInvitationManager(r)

	usr, err := SearchUser(r, searchString)
	if err != nil {
		if db.IsNotFound(err) {
			log.Debug("Could not find existing user for whom to remove the invitation")
			usr = &user.User{}
			// http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			// return
		} else {
			log.Error("Error while searching user: ", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}

	err = invitationMgr.Remove(globalID, usr.Username, searchString)
	if err == mgo.ErrNotFound {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}
	if err != nil {
		log.Error("Error while remove invite: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
682525
func (n *UnionSelectList) Accept(v Visitor) (Node, bool) {
	newNode, skipChildren := v.Enter(n)
	if skipChildren {
		return v.Leave(newNode)
	}
	n = newNode.(*UnionSelectList)
	for i, sel := range n.Selects {
		node, ok := sel.Accept(v)
		if !ok {
			return n, false
		}
		n.Selects[i] = node.(*SelectStmt)
	}
	return v.Leave(n)
}
598104
func (api OrganizationsAPI) AddOrganizationOwner(w http.ResponseWriter, r *http.Request) {
	api.inviteUser(w, r, invitations.RoleOwner)
}
913236
func Approve(id string, params *stripe.ReviewApproveParams) (*stripe.Review, error) {
	return getC().Approve(id, params)
}
834964
func (s *Service) OrganizationInvitationList(ctx context.Context, organizationName string, lr *ListRange) (OrganizationInvitationListResult, error) {
	var organizationInvitation OrganizationInvitationListResult
	return organizationInvitation, s.Get(ctx, &organizationInvitation, fmt.Sprintf("/organizations/%v/invitations", organizationName), nil, lr)
}
553778
func (r *RoomService) Invite(room string, user string, reason string) (*http.Response, error) {
	reasonReq := &InviteRequest{Reason: reason}

	req, err := r.client.NewRequest("POST", fmt.Sprintf("room/%s/invite/%s", room, user), nil, reasonReq)
	if err != nil {
		return nil, err
	}

	return r.client.Do(req, nil)
}
534194
func (n *Join) Accept(v Visitor) (Node, bool) {
	newNode, skipChildren := v.Enter(n)
	if skipChildren {
		return v.Leave(newNode)
	}
	n = newNode.(*Join)
	node, ok := n.Left.Accept(v)
	if !ok {
		return n, false
	}
	n.Left = node.(ResultSetNode)
	if n.Right != nil {
		node, ok = n.Right.Accept(v)
		if !ok {
			return n, false
		}
		n.Right = node.(ResultSetNode)
	}
	if n.On != nil {
		node, ok = n.On.Accept(v)
		if !ok {
			return n, false
		}
		n.On = node.(*OnCondition)
	}
	return v.Leave(n)
}
500955
func (service *IYOPhonenumberValidationService) SendOrganizationInviteSms(request *http.Request, invite *invitations.JoinOrganizationInvitation) (err error) {
	link := fmt.Sprintf(invitations.InviteURL, request.Host, url.QueryEscape(invite.Code))
	// todo: perhaps this should be shorter but that might be confusing for the end user
	message := fmt.Sprintf("You have been invited to the %s organization on It's You Online. Click the following link to accept it. %s", invite.Organization, link)
	go service.SMSService.Send(invite.PhoneNumber, message)
	return
}