// Invite generates a token which can be used to add another SSH node
// to a cluster
9152
func (c *NodeCommand) Invite(client auth.ClientI) error {
	// parse --roles flag
	roles, err := teleport.ParseRoles(c.roles)
	if err != nil {
		return trace.Wrap(err)
	}
	token, err := client.GenerateToken(auth.GenerateTokenRequest{Roles: roles, TTL: c.ttl, Token: c.token})
	if err != nil {
		return trace.Wrap(err)
	}

	// Calculate the CA pin for this cluster. The CA pin is used by the client
	// to verify the identity of the Auth Server.
	caPin, err := calculateCAPin(client)
	if err != nil {
		return trace.Wrap(err)
	}

	authServers, err := client.GetAuthServers()
	if err != nil {
		return trace.Wrap(err)
	}
	if len(authServers) == 0 {
		return trace.Errorf("This cluster does not have any auth servers running.")
	}

	// output format swtich:
	if c.format == "text" {
		if roles.Include(teleport.RoleTrustedCluster) || roles.Include(teleport.LegacyClusterTokenType) {
			fmt.Printf(trustedClusterMessage, token, int(c.ttl.Minutes()))
		} else {
			fmt.Printf(nodeMessage,
				token,
				int(c.ttl.Minutes()),
				strings.ToLower(roles.String()),
				token,
				caPin,
				authServers[0].GetAddr(),
				int(c.ttl.Minutes()),
				authServers[0].GetAddr(),
			)
		}
	} else {
		// Always return a list, otherwise we'll break users tooling. See #1846 for
		// more details.
		tokens := []string{token}
		out, err := json.Marshal(tokens)
		if err != nil {
			return trace.Wrap(err, "failed to marshal token")
		}
		fmt.Printf(string(out))
	}
	return nil
}
1091047
func (s *invitationServiceImpl) Accept(ctx context.Context, token uuid.UUID) (string, string, error) {

	// Locate the invitation
	inv, err := s.Repositories().InvitationRepository().FindByAcceptCode(ctx, token)

	if err != nil {
		return "", "", errs.Wrapf(err, "something went wrong while finding invitation with accept code")
	}

	// get redirect urls
	redirectOnSuccess := inv.SuccessRedirectURL
	redirectOnFailure := inv.FailureRedirectURL

	// get identity for invitation
	currentIdentityID := inv.IdentityID
	identity, err := s.Repositories().Identities().LoadWithUser(ctx, currentIdentityID)
	if err != nil {
		return "", redirectOnFailure, errs.Wrapf(err, "failed to load identity for invitee %d", currentIdentityID)
	}

	if identity.User.Banned {
		return "", redirectOnFailure, autherrors.NewUnauthorizedError("user banned")
	}

	var resourceID string

	err = s.ExecuteInTransaction(func() error {

		// If this invitation is for an identity
		if inv.InviteTo != nil {
			inviteToIdentity, err := s.Repositories().Identities().Load(ctx, *inv.InviteTo)
			if err != nil {
				return err
			}

			// If the invitation is for a membership, add a membership record
			if inv.Member {
				err = s.Repositories().Identities().AddMember(ctx, inviteToIdentity.ID, currentIdentityID)
				if err != nil {
					return err
				}
			}

			roles, err := s.Repositories().InvitationRepository().ListRoles(ctx, inv.InvitationID)
			if err != nil {
				return err
			}

			// If the invitation includes role assignments, assign them
			inviteToIdentityResourceID := inviteToIdentity.IdentityResourceID.String
			for _, role := range roles {
				ir := &repository.IdentityRole{
					IdentityID: currentIdentityID,
					RoleID:     role.RoleID,
					ResourceID: inviteToIdentityResourceID,
				}

				err = s.Repositories().IdentityRoleRepository().Create(ctx, ir)
				if err != nil {
					return err
				}
			}

			// Delete the invitation
			err = s.Repositories().InvitationRepository().Delete(ctx, inv.InvitationID)
			if err != nil {
				return errs.Wrap(err, "failed to create identity role")
			}

			// Return the identity ID
			resourceID = inviteToIdentity.IdentityResourceID.String

		} else if inv.ResourceID != nil {
			inviteToResource, err := s.Repositories().ResourceRepository().Load(ctx, *inv.ResourceID)
			if err != nil {
				return errs.Wrapf(err, "failed to load resource %s", resourceID)
			}

			roles, err := s.Repositories().InvitationRepository().ListRoles(ctx, inv.InvitationID)
			if err != nil {
				return errs.Wrapf(err, "failed to load roles for invitation %d", inv.InvitationID)
			}

			for _, role := range roles {
				ir := &repository.IdentityRole{
					IdentityID: currentIdentityID,
					RoleID:     role.RoleID,
					ResourceID: inviteToResource.ResourceID,
				}

				err = s.Repositories().IdentityRoleRepository().Create(ctx, ir)
				if err != nil {
					return err
				}
			}

			// Delete the invitation
			err = s.Repositories().InvitationRepository().Delete(ctx, inv.InvitationID)
			if err != nil {
				return errs.Wrapf(err, "failed to delete invitation %d", inv.InvitationID)
			}

			// Set the resource ID
			resourceID = inviteToResource.ResourceID
		}

		return nil
	})

	if err != nil {
		return "", redirectOnFailure, err
	}

	// Return the resource ID and redirect path
	return resourceID, redirectOnSuccess, nil
}
107446
func (c *InvitesClient) Create(ctx context.Context, createInvite *CreateInvite) (*Invite, error) {
	p := "/invites"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, createInvite)
	if err != nil {
		return nil, err
	}

	var resp Invite
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
30360
func (nr *NodeRegistrar) RegisterNode(n *node.Node, manager NodeManager) error {

	// Join the shared store holding node information of entire cluster
	store, err := store.JoinSharedStore(store.Configuration{
		Prefix:     NodeStorePrefix,
		KeyCreator: KeyCreator,
		Observer:   NewNodeObserver(manager),
	})

	if err != nil {
		return err
	}

	if err = store.UpdateLocalKeySync(n); err != nil {
		store.Close()
		return err
	}

	nr.SharedStore = store

	return nil
}
647210
func (api *Client) InviteGuestContext(ctx context.Context, teamName, channel, firstName, lastName, emailAddress string) error {
	values := url.Values{
		"email":            {emailAddress},
		"channels":         {channel},
		"first_name":       {firstName},
		"last_name":        {lastName},
		"ultra_restricted": {"1"},
		"token":            {api.token},
		"resend":           {"true"},
		"set_active":       {"true"},
		"_attempts":        {"1"},
	}

	err := api.adminRequest(ctx, "invite", teamName, values)
	if err != nil {
		return fmt.Errorf("Failed to invite single-channel guest: %s", err)
	}

	return nil
}
628384
func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {

	data := struct {
		MaxAge    int  `json:"max_age"`
		MaxUses   int  `json:"max_uses"`
		Temporary bool `json:"temporary"`
		Unique    bool `json:"unique"`
	}{i.MaxAge, i.MaxUses, i.Temporary, i.Unique}

	body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}
300371
func (api *API) Propose(address common.Address, auth bool) {
	api.clique.lock.Lock()
	defer api.clique.lock.Unlock()

	api.clique.proposals[address] = auth
}
710819
func (n *Node) registerNode(node *api.RaftMember) error {
	if n.cluster.IsIDRemoved(node.RaftID) {
		return nil
	}

	member := &membership.Member{}

	existingMember := n.cluster.GetMember(node.RaftID)
	if existingMember != nil {
		// Member already exists

		// If the address is different from what we thought it was,
		// update it. This can happen if we just joined a cluster
		// and are adding ourself now with the remotely-reachable
		// address.
		if existingMember.Addr != node.Addr {
			if node.RaftID != n.Config.ID {
				if err := n.transport.UpdatePeer(node.RaftID, node.Addr); err != nil {
					return err
				}
			}
			member.RaftMember = node
			n.cluster.AddMember(member)
		}

		return nil
	}

	// Avoid opening a connection to the local node
	if node.RaftID != n.Config.ID {
		if err := n.transport.AddPeer(node.RaftID, node.Addr); err != nil {
			return err
		}
	}

	member.RaftMember = node
	err := n.cluster.AddMember(member)
	if err != nil {
		if rerr := n.transport.RemovePeer(node.RaftID); rerr != nil {
			return errors.Wrapf(rerr, "failed to remove peer after error %v", err)
		}
		return err
	}

	return nil
}
1024425
func (_m *ClientInterface) AddHost(h host.Host) ([]byte, error) {
	ret := _m.Called(h)

	var r0 []byte
	if rf, ok := ret.Get(0).(func(host.Host) []byte); ok {
		r0 = rf(h)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]byte)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(host.Host) error); ok {
		r1 = rf(h)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
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)
}
366188
func (s *Store) Join(id, addr string, metadata map[string]string) error {
	s.logger.Printf("received request to join node at %s", addr)
	if s.raft.State() != raft.Leader {
		return ErrNotLeader
	}

	configFuture := s.raft.GetConfiguration()
	if err := configFuture.Error(); err != nil {
		s.logger.Printf("failed to get raft configuration: %v", err)
		return err
	}

	for _, srv := range configFuture.Configuration().Servers {
		// If a node already exists with either the joining node's ID or address,
		// that node may need to be removed from the config first.
		if srv.ID == raft.ServerID(id) || srv.Address == raft.ServerAddress(addr) {
			// However if *both* the ID and the address are the same, the no
			// join is actually needed.
			if srv.Address == raft.ServerAddress(addr) && srv.ID == raft.ServerID(id) {
				s.logger.Printf("node %s at %s already member of cluster, ignoring join request",
					id, addr)
				return nil
			}
			if err := s.remove(id); err != nil {
				s.logger.Printf("failed to remove node: %v", err)
				return err
			}
		}
	}

	f := s.raft.AddVoter(raft.ServerID(id), raft.ServerAddress(addr), 0, 0)
	if e := f.(raft.Future); e.Error() != nil {
		if e.Error() == raft.ErrNotLeader {
			return ErrNotLeader
		}
		return e.Error()
	}

	if err := s.setMetadata(id, metadata); err != nil {
		return err
	}

	s.logger.Printf("node at %s joined successfully", addr)
	return nil
}
395209
func (f *tokenFuture) Wait() <-chan struct{} {
	f.m.Lock()
	defer f.m.Unlock()

	c := make(chan struct{})
	if f.set {
		close(c)
		return c
	}

	f.waiting = append(f.waiting, c)
	return c
}
1021605
func (api *Client) InviteGuest(teamName, channel, firstName, lastName, emailAddress string) error {
	return api.InviteGuestContext(context.Background(), teamName, channel, firstName, lastName, emailAddress)
}
677705
func (cli *Client) InviteUser(roomID string, req *ReqInviteUser) (resp *RespInviteUser, err error) {
	u := cli.BuildURL("rooms", roomID, "invite")
	_, err = cli.MakeRequest("POST", u, req, &resp)
	return
}
1145114
func (api *Client) InviteUsersToConversationContext(ctx context.Context, channelID string, users ...string) (*Channel, error) {
	values := url.Values{
		"token":   {api.token},
		"channel": {channelID},
		"users":   {strings.Join(users, ",")},
	}
	response := struct {
		SlackResponse
		Channel *Channel `json:"channel"`
	}{}
	err := api.postMethod(ctx, "conversations.invite", values, &response)
	if err != nil {
		return nil, err
	}

	return response.Channel, response.Err()
}
1301209
func (c *Client) AddNode(host string, command AddNodeCommand) error {
	return c.AddNodeAsync(host, command).Receive()
}
1066690
func (tx *AddMemberTx) createInvite(typ string, name keybase1.TeamInviteName, role keybase1.TeamRole, uid keybase1.UID) {
	var payload *SCTeamInvites
	if typ == "keybase" {
		payload = tx.inviteKeybasePayload(uid)
	} else {
		payload = tx.inviteSocialPayload(uid)
	}

	invite := SCTeamInvite{
		Type: typ,
		Name: name,
		ID:   NewInviteID(),
	}

	switch role {
	case keybase1.TeamRole_READER:
		payload.Readers = appendToInviteList(invite, payload.Readers)
	case keybase1.TeamRole_WRITER:
		payload.Writers = appendToInviteList(invite, payload.Writers)
	case keybase1.TeamRole_ADMIN:
		payload.Admins = appendToInviteList(invite, payload.Admins)
	case keybase1.TeamRole_OWNER:
		payload.Owners = appendToInviteList(invite, payload.Owners)
	}
}