// CreateOrUpdateIdentityAndUser creates or updates the user and identity associated with the oauth-provided user token,
// checks whether the user is approved, generates a new user token and returns a final URL to which the client should redirect
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
}
1207902
func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {

	// NOTE: Avatar must be either the hash/id of existing Avatar or
	// data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
	// to set a new avatar.
	// If left blank, avatar will be set to null/blank

	data := struct {
		Email       string `json:"email,omitempty"`
		Password    string `json:"password,omitempty"`
		Username    string `json:"username,omitempty"`
		Avatar      string `json:"avatar,omitempty"`
		NewPassword string `json:"new_password,omitempty"`
	}{email, password, username, avatar, newPassword}

	body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}
1223059
func (a *API) UpdateUser(user *User) (*User, error) {
	dst := new(User)
	url := a.BuildURL("/v2/user/%d", user.Id)
	err := a.Put(url, Params{}, user, dst)
	return dst, err
}
818668
func (d *DataSource) InsertOrUpdate(user Model) (Model, error) {
	// no matter what we will update the password hash
	// for both update and insert actions.
	hashedPassword, err := GeneratePassword(user.password)
	if err != nil {
		return user, err
	}
	user.HashedPassword = hashedPassword

	// update
	if id := user.ID; id > 0 {
		_, found := d.GetByID(id)
		if !found {
			return user, errors.New("ID should be zero or a valid one that maps to an existing User")
		}
		d.mu.Lock()
		d.Users[id] = user
		d.mu.Unlock()
		return user, nil
	}

	// insert
	id := d.getLastID() + 1
	user.ID = id
	d.mu.Lock()
	user.CreatedAt = time.Now()
	d.Users[id] = user
	d.mu.Unlock()

	return user, nil
}
1276762
func (c *Client) OAuthClientUpdate(oauthClientIdentity string, options *OAuthClientUpdateOpts) (*OAuthClient, error) {
	var oauthClientRes OAuthClient
	return &oauthClientRes, c.Patch(&oauthClientRes, "/oauth/clients/"+oauthClientIdentity, options)
}
896635
func setIdentityUser(identity *userapi.Identity, user *userapi.User) bool {
	if identityReferencesUser(identity, user) {
		return false
	}
	identity.User = corev1.ObjectReference{
		Name: user.Name,
		UID:  user.UID,
	}
	return true
}
293695
func (c *ChatRPC) ChatIdentifyUpdate(
	_ context.Context, _ keybase1.CanonicalTLFNameAndIDWithBreaks) error {
	return nil
}
1346789
func (api UsersAPI) UpdateDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	oldlabel := mux.Vars(r)["label"]

	newcurrency := user.DigitalAssetAddress{}
	if err := json.NewDecoder(r.Body).Decode(&newcurrency); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !newcurrency.Validate() {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	userMgr := user.NewManager(r)

	u, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	_, err = u.GetDigitalAssetAddressByLabel(oldlabel)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	if oldlabel != newcurrency.Label {
		_, err = u.GetDigitalAssetAddressByLabel(newcurrency.Label)
		if err == nil {
			http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
			return
		}
	}

	if err = userMgr.SaveVirtualCurrency(username, newcurrency); err != nil {
		log.Error("ERROR while saving address - ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	if oldlabel != newcurrency.Label {
		if err := userMgr.RemoveVirtualCurrency(username, oldlabel); err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	w.Header().Set("Content-Type", "application/json")

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(newcurrency)
}
816069
func createUser(request *restful.Request, response *restful.Response) {
	u := new(User)
	err := request.ReadEntity(u)
	log.Print("createUser", err, u)
	response.WriteEntity(u)
}
915486
func (s *UserService) CreateUser(ctx context.Context, u *platform.User) error {
	url, err := newURL(s.Addr, usersPath)
	if err != nil {
		return err
	}

	octets, err := json.Marshal(u)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", url.String(), bytes.NewReader(octets))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}

	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp, true); err != nil {
		return err
	}

	if err := json.NewDecoder(resp.Body).Decode(u); err != nil {
		return err
	}

	return nil
}
916977
func (c *FakeIdentities) Update(identity *user.Identity) (result *user.Identity, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewRootUpdateAction(identitiesResource, identity), &user.Identity{})
	if obj == nil {
		return nil, err
	}
	return obj.(*user.Identity), err
}
1255830
func (s *IdentityService) UpsertPasswordHash(username string, hash []byte) error {
	userPrototype, err := services.NewUser(username)
	if err != nil {
		return trace.Wrap(err)
	}
	user, err := services.GetUserMarshaler().GenerateUser(userPrototype)
	if err != nil {
		return trace.Wrap(err)
	}
	err = s.CreateUser(user)
	if err != nil {
		if !trace.IsAlreadyExists(err) {
			return trace.Wrap(err)
		}
	}
	item := backend.Item{
		Key:   backend.Key(webPrefix, usersPrefix, username, pwdPrefix),
		Value: hash,
	}
	_, err = s.Put(context.TODO(), item)
	if err != nil {
		return trace.Wrap(err)
	}
	return nil
}
1107585
func (c *Client) OAuthAuthorizationCreate(scope []string, options *OAuthAuthorizationCreateOpts) (*OAuthAuthorization, error) {
	params := struct {
		Scope       []string `json:"scope"`
		Client      *string  `json:"client,omitempty"`
		Description *string  `json:"description,omitempty"`
		ExpiresIn   *int     `json:"expires_in,omitempty"`
	}{
		Scope: scope,
	}
	if options != nil {
		params.Client = options.Client
		params.Description = options.Description
		params.ExpiresIn = options.ExpiresIn
	}
	var oauthAuthorizationRes OAuthAuthorization
	return &oauthAuthorizationRes, c.Post(&oauthAuthorizationRes, "/oauth/authorizations", params)
}
94719
func (doc *Document) createOrUpdate(data []byte) (*DocCreateResoponse, error) {

	headMap := make(map[string]string)
	headMap["Content-Type"] = "application/json"
	body, err := doc.Db.Req.Post("", data, headMap)
	if err != nil {
		return nil, err
	}

	result := &DocCreateResoponse{}
	err = json.Unmarshal(body, result)
	if err != nil {
		return nil, err
	}
	if result.Error != "" {
		return nil, errors.New("Failure while creating " + result.Error)
	}
	if !result.Ok {
		return nil, errors.New("Couch returned failure when creating [" + doc.Db.Name + "]")
	}
	return result, nil
}
322307
func (p *provisioningIdentityMapper) createIdentityAndMapping(ctx context.Context, info authapi.UserIdentityInfo) (kuser.Info, error) {
	// Build the part of the identity we know about
	identity := &userapi.Identity{
		ObjectMeta: metav1.ObjectMeta{
			Name: info.GetIdentityName(),
		},
		ProviderName:     info.GetProviderName(),
		ProviderUserName: info.GetProviderUserName(),
		Extra:            info.GetExtra(),
	}

	// GetIdentities or create a persisted user pointing to the identity
	persistedUser, err := p.provisioningStrategy.UserForNewIdentity(ctx, getPreferredUserName(identity), identity)
	if err != nil {
		return nil, err
	}

	// CreateIdentity the identity pointing to the persistedUser
	identity.User = corev1.ObjectReference{
		Name: persistedUser.Name,
		UID:  persistedUser.UID,
	}
	if _, err := p.identity.Create(identity); err != nil {
		return nil, err
	}

	return userToInfo(persistedUser), nil
}
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
}
926216
func (e *Etcd) CreateOrUpdate(snapshot *api.RangeAllocation) error {
	e.lock.Lock()
	defer e.lock.Unlock()

	last := ""
	err := e.storage.GuaranteedUpdate(context.TODO(), e.baseKey, &api.RangeAllocation{}, true, nil,
		storage.SimpleUpdate(func(input runtime.Object) (output runtime.Object, err error) {
			existing := input.(*api.RangeAllocation)
			switch {
			case len(snapshot.ResourceVersion) != 0 && len(existing.ResourceVersion) != 0:
				if snapshot.ResourceVersion != existing.ResourceVersion {
					return nil, k8serr.NewConflict(e.resource, "", fmt.Errorf("the provided resource version does not match"))
				}
			case len(existing.ResourceVersion) != 0:
				return nil, k8serr.NewConflict(e.resource, "", fmt.Errorf("another caller has already initialized the resource"))
			}
			last = snapshot.ResourceVersion
			return snapshot, nil
		}),
	)
	if err != nil {
		return storeerr.InterpretUpdateError(err, e.resource, "")
	}
	err = e.alloc.Restore(snapshot.Range, snapshot.Data)
	if err == nil {
		e.last = last
	}
	return err
}