// GenerateTransientUserAccessTokenForIdentity generates a transient user access token, an extremely short-lived token
497740
func (m *tokenManager) GenerateTransientUserAccessTokenForIdentity(ctx context.Context, identity repository.Identity) (*string, error) {
	token, err := m.GenerateUnsignedUserAccessTokenForIdentity(ctx, identity)
	if err != nil {
		return nil, err
	}

	claims := token.Claims.(jwt.MapClaims)
	iat := time.Now().Unix()
	claims["exp"] = iat + m.config.GetTransientTokenExpiresIn()
	claims["transient"] = "true"

	accessToken, err := token.SignedString(m.userAccountPrivateKey.Key)
	if err != nil {
		return nil, errors.WithStack(err)
	}

	return &accessToken, nil
}
624584
func (ga *gossipAdapterImpl) GetIdentityByPKIID(pkiID common.PKIidType) api.PeerIdentityType {
	identity, err := ga.idMapper.Get(pkiID)
	if err != nil {
		return nil
	}
	return identity
}
674049
func (f *identityProviderFactoryImpl) NewIdentityProvider(ctx context.Context, config provider.IdentityProviderConfiguration) provider.IdentityProvider {
	return provider.NewIdentityProvider(config)
}
48836
func (w *defaultDialect) WriteIdentity(i string) {
	if len(i) == 1 && i == "*" {
		w.WriteByte('*')
		return
	}
	IdentityMaybeEscapeBuf(&w.Buffer, w.IdentityQuote, i)
}
1276561
func GenerateUserCreds(process *service.TeleportProcess, username string) (*UserCreds, error) {
	priv, pub, err := testauthority.New().GenerateKeyPair("")
	if err != nil {
		return nil, trace.Wrap(err)
	}
	a := process.GetAuthServer()
	sshCert, x509Cert, err := a.GenerateUserCerts(pub, username, time.Hour, teleport.CertificateFormatStandard)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	clusterName, err := a.GetClusterName()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	ca, err := a.GetCertAuthority(services.CertAuthID{
		Type:       services.HostCA,
		DomainName: clusterName.GetClusterName(),
	}, false)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return &UserCreds{
		HostCA: ca,
		Key: client.Key{
			Priv:    priv,
			Pub:     pub,
			Cert:    sshCert,
			TLSCert: x509Cert,
		},
	}, nil
}
676317
func (k *Keygen) GenerateUserCert(c services.UserCertParams) ([]byte, error) {
	if c.TTL < defaults.MinCertDuration {
		return nil, trace.BadParameter("wrong certificate TTL")
	}
	if len(c.AllowedLogins) == 0 {
		return nil, trace.BadParameter("allowedLogins: need allowed OS logins")
	}
	pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicUserKey)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	validBefore := uint64(ssh.CertTimeInfinity)
	if c.TTL != 0 {
		b := k.clock.Now().UTC().Add(c.TTL)
		validBefore = uint64(b.Unix())
		log.Debugf("generated user key for %v with expiry on (%v) %v", c.AllowedLogins, validBefore, b)
	}
	cert := &ssh.Certificate{
		// we have to use key id to identify teleport user
		KeyId:           c.Username,
		ValidPrincipals: c.AllowedLogins,
		Key:             pubKey,
		ValidAfter:      uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()),
		ValidBefore:     validBefore,
		CertType:        ssh.UserCert,
	}
	cert.Permissions.Extensions = map[string]string{
		teleport.CertExtensionPermitPTY:            "",
		teleport.CertExtensionPermitPortForwarding: "",
	}
	if c.PermitAgentForwarding {
		cert.Permissions.Extensions[teleport.CertExtensionPermitAgentForwarding] = ""
	}
	if !c.PermitPortForwarding {
		delete(cert.Permissions.Extensions, teleport.CertExtensionPermitPortForwarding)
	}
	if len(c.Roles) != 0 {
		// only add roles to the certificate extensions if the standard format was
		// requested. we allow the option to omit this to support older versions of
		// OpenSSH due to a bug in <= OpenSSH 7.1
		// https://bugzilla.mindrot.org/show_bug.cgi?id=2387
		if c.CertificateFormat == teleport.CertificateFormatStandard {
			roles, err := services.MarshalCertRoles(c.Roles)
			if err != nil {
				return nil, trace.Wrap(err)
			}
			cert.Permissions.Extensions[teleport.CertExtensionTeleportRoles] = roles
		}
	}
	signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if err := cert.SignCert(rand.Reader, signer); err != nil {
		return nil, trace.Wrap(err)
	}
	return ssh.MarshalAuthorizedKey(cert), nil
}
322472
func GenerateCertificate(authServer *AuthServer, identity TestIdentity) ([]byte, []byte, error) {
	switch id := identity.I.(type) {
	case LocalUser:
		user, err := authServer.GetUser(id.Username)
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		roles, err := services.FetchRoles(user.GetRoles(), authServer, user.GetTraits())
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		if identity.TTL == 0 {
			identity.TTL = time.Hour
		}
		priv, pub, err := authServer.GenerateKeyPair("")
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		certs, err := authServer.generateUserCert(certRequest{
			publicKey: pub,
			user:      user,
			roles:     roles,
			ttl:       identity.TTL,
			usage:     identity.AcceptedUsage,
		})
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		return certs.tls, priv, nil
	case BuiltinRole:
		keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{
			HostID:   id.Username,
			NodeName: id.Username,
			Roles:    teleport.Roles{id.Role},
		})
		if err != nil {
			return nil, nil, trace.Wrap(err)
		}
		return keys.TLSCert, keys.Key, nil
	default:
		return nil, nil, trace.BadParameter("identity of unknown type %T is unsupported", identity)
	}
}
1142306
func (c *ACLCaches) GetIdentity(id string) *IdentityCacheEntry {
	if c == nil || c.identities == nil {
		return nil
	}

	if raw, ok := c.identities.Get(id); ok {
		return raw.(*IdentityCacheEntry)
	}

	return nil
}
627020
func (msp *bccspmsp) GetDefaultSigningIdentity() (SigningIdentity, error) {
	mspLogger.Debugf("Obtaining default signing identity")

	if msp.signer == nil {
		return nil, errors.New("this MSP does not possess a valid default signing identity")
	}

	return msp.signer, nil
}
516265
func (s *authenticationProviderServiceImpl) CreateOrUpdateIdentityAndUser(ctx context.Context, referrerURL *url.URL,
	providerToken *oauth2.Token) (*string, *oauth2.Token, error) {

	tokenManager, err := manager.ReadTokenManagerFromContext(ctx)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err": err,
		}, "failed to retrieve token manager from context")
		return nil, nil, autherrors.NewInternalError(ctx, err)
	}

	apiClient := referrerURL.Query().Get(apiClientParam)
	identity, err := s.UpdateIdentityUsingUserInfoEndPoint(ctx, providerToken.AccessToken)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err,
		}, "failed to create a user and keycloak identity")
		switch err.(type) {
		case autherrors.UnauthorizedError:
			if apiClient != "" {
				// Return the api token
				userToken, err := tokenManager.GenerateUserTokenForAPIClient(ctx, *providerToken)
				if err != nil {
					log.Error(ctx, map[string]interface{}{"err": err}, "failed to generate token for API client")
					return nil, nil, err
				}
				err = encodeToken(ctx, referrerURL, userToken, apiClient)
				if err != nil {
					log.Error(ctx, map[string]interface{}{"err": err}, "failed to encode token")
					return nil, nil, err
				}
				log.Info(ctx, map[string]interface{}{
					"referrerURL": referrerURL.String(),
					"api_client":  apiClient,
				}, "return api token for unapproved user")
				redirectTo := referrerURL.String()
				return &redirectTo, userToken, nil
			}

			userNotApprovedRedirectURL := s.config.GetNotApprovedRedirect()
			if userNotApprovedRedirectURL != "" {
				status, err := s.Services().OSOSubscriptionService().LoadOSOSubscriptionStatus(ctx, *providerToken)
				if err != nil {
					// Not critical. Just log the error and proceed
					log.Error(ctx, map[string]interface{}{"err": err}, "failed to load OSO subscription status")
				}
				userNotApprovedRedirectURL, err := rest.AddParam(userNotApprovedRedirectURL, "status", status)
				if err != nil {
					log.Error(ctx, map[string]interface{}{"err": err}, "failed to add a status param to the redirect URL")
					return nil, nil, err
				}
				log.Debug(ctx, map[string]interface{}{
					"user_not_approved_redirect_url": userNotApprovedRedirectURL,
				}, "user not approved; redirecting to registration app")
				return &userNotApprovedRedirectURL, nil, nil
			}
			return nil, nil, autherrors.NewUnauthorizedError(err.Error())
		}
		return nil, nil, err
	}

	if identity.User.Banned {
		log.Warn(ctx, map[string]interface{}{
			"identity_id": identity.ID,
			"user_name":   identity.Username,
		}, "banned user tried to login")
		return nil, nil, autherrors.NewUnauthorizedError("unauthorized access")
	}

	log.Debug(ctx, map[string]interface{}{
		"referrerURL": referrerURL.String(),
		"user_name":   identity.Username,
	}, "local user created/updated")

	// Update the identity's last active timestamp
	err = s.Repositories().Identities().TouchLastActive(ctx, identity.ID)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"err": err, "identity_id": identity.ID.String()}, "failed to update last_active timestamp for identity")
		return nil, nil, err
	}

	// Generate a new user token instead of using the original oauth provider token
	userToken, err := tokenManager.GenerateUserTokenForIdentity(ctx, *identity, false)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"err": err, "identity_id": identity.ID.String()}, "failed to generate token for user")
		return nil, nil, err
	}

	// Register the access token
	_, err = s.Services().TokenService().RegisterToken(ctx, identity.ID, userToken.AccessToken, token2.TOKEN_TYPE_ACCESS, nil)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "could not register access token")
		return nil, nil, autherrors.NewInternalError(ctx, err)
	}

	// Register the refresh token
	_, err = s.Services().TokenService().RegisterToken(ctx, identity.ID, userToken.RefreshToken, token2.TOKEN_TYPE_REFRESH, nil)
	if err != nil {
		log.Error(ctx, map[string]interface{}{"error": err}, "could not register refresh token")
		return nil, nil, autherrors.NewInternalError(ctx, err)
	}

	err = encodeToken(ctx, referrerURL, userToken, apiClient)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err,
		}, "failed to encode token")
		redirectTo := referrerURL.String() + err.Error()
		return &redirectTo, nil, autherrors.NewInternalError(ctx, err)
	}
	log.Debug(ctx, map[string]interface{}{
		"referrerURL": referrerURL.String(),
		"user_name":   identity.Username,
	}, "token encoded")

	redirectTo := referrerURL.String()
	return &redirectTo, userToken, nil
}
100227
func (ctxt *httpContext) stateForRequestAuthenticatedUser(r *http.Request) (*state.PooledState, error) {
	st, _, err := ctxt.stateAndEntityForRequestAuthenticatedUser(r)
	return st, err
}
929560
func (s *UsersService) Identity() *UsersIdentityCall {
	var call UsersIdentityCall
	call.service = s
	return &call
}
665938
func GeneratePrivateAccount() (*PrivateAccount, error) {
	privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519)
	if err != nil {
		return nil, err
	}
	publicKey := privateKey.GetPublicKey()
	return ConcretePrivateAccount{
		Address:    publicKey.GetAddress(),
		PublicKey:  publicKey,
		PrivateKey: privateKey,
	}.PrivateAccount(), nil
}
326822
func GenerateIdentityKeyPair() *IdentityKeyPair {
	kp := NewECKeyPair()
	ikp := &IdentityKeyPair{
		PublicKey:  IdentityKey{kp.PublicKey},
		PrivateKey: kp.PrivateKey,
	}
	return ikp
}
698313
func CreateAccessToken(c *context.APIContext, form api.CreateAccessTokenOption) {
	t := &models.AccessToken{
		UID:  c.User.ID,
		Name: form.Name,
	}
	if err := models.NewAccessToken(t); err != nil {
		c.Error(500, "NewAccessToken", err)
		return
	}
	c.JSON(201, &api.AccessToken{t.Name, t.Sha1})
}
1312513
func CurrentIdentity(c context.Context) identity.Identity {
	if s := GetState(c); s != nil {
		return s.User().Identity
	}
	return identity.AnonymousIdentity
}
1071111
func (p *provider) GetUserIdentity(data *osincli.AccessData) (authapi.UserIdentityInfo, bool, error) {
	req, _ := http.NewRequest("GET", p.userAPIURL, nil)
	req.Header.Set("Authorization", fmt.Sprintf("bearer %s", data.AccessToken))

	client := http.DefaultClient
	if p.transport != nil {
		client = &http.Client{Transport: p.transport}
	}
	res, err := client.Do(req)
	if err != nil {
		return nil, false, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, false, err
	}

	userdata := gitlabUser{}
	err = json.Unmarshal(body, &userdata)
	if err != nil {
		return nil, false, err
	}

	if userdata.ID == 0 {
		return nil, false, errors.New("Could not retrieve GitLab id")
	}

	identity := authapi.NewDefaultUserIdentityInfo(p.providerName, fmt.Sprintf("%d", userdata.ID))
	if len(userdata.Name) > 0 {
		identity.Extra[authapi.IdentityDisplayNameKey] = userdata.Name
	}
	if len(userdata.Username) > 0 {
		identity.Extra[authapi.IdentityPreferredUsernameKey] = userdata.Username
	}
	if len(userdata.Email) > 0 {
		identity.Extra[authapi.IdentityEmailKey] = userdata.Email
	}
	klog.V(4).Infof("Got identity=%#v", identity)

	return identity, true, nil
}