public async Task <User> RemoveAuthentication(User user, string provider) { var c = await Client <User>(); user.Auth.Remove(provider); await c.DeleteByQueryAsync <AuthenticationClaim>(s => s.Index(GetIndex <AuthenticationClaim>()).Query(q => q.Term(t => t.Field(record => record.Provider).Value(provider)))); await c.IndexAsync(user, s => s.Index(GetIndex <User>())); var ctx = new AuthenticationChangedCtx { Type = provider, User = user }; await _handlers().RunEventHandler(h => h.OnAuthenticationChanged(ctx), ex => _logger.Log(LogLevel.Error, "user.removeAuth", "An error occured while running OnAuthenticationChanged event handler", ex)); return(user); }
public async Task <User> AddAuthentication(User user, string provider, Action <dynamic> authDataModifier, Dictionary <string, string> cacheEntries) { var c = await Client <User>(); var auth = user.Auth[provider]; if (auth == null) { auth = new JObject(); user.Auth[provider] = auth; } authDataModifier?.Invoke(auth); foreach (var entry in cacheEntries) { var result = await c.IndexAsync(new AuthenticationClaim { Id = $"{provider}_{entry.Key}_{entry.Value}", UserId = user.Id, Provider = provider }, s => s.Index(GetIndex <AuthenticationClaim>()).OpType(Elasticsearch.Net.OpType.Create)); if (!result.IsValid) { var r = await c.GetAsync <AuthenticationClaim>($"{provider}_{entry.Key}_{entry.Value}", s => s.Index(GetIndex <AuthenticationClaim>())); if (r.IsValid && r.Source.UserId != user.Id) { if (result.ServerError?.Error?.Type == "document_already_exists_exception") { throw new ConflictException(); } else { throw new InvalidOperationException(result.ServerError?.Error?.Type ?? result.OriginalException.ToString()); } } } } try { await TaskHelper.Retry(async() => { var response = await c.IndexAsync(user, s => s.Index(GetIndex <User>())); if (!response.IsValid) { throw new InvalidOperationException(response.DebugInformation); } return(response); }, RetryPolicies.IncrementalDelay(5, TimeSpan.FromSeconds(1)), CancellationToken.None, ex => true); var ctx = new AuthenticationChangedCtx { Type = provider, User = user }; await _handlers().RunEventHandler(h => h.OnAuthenticationChanged(ctx), ex => _logger.Log(LogLevel.Error, "user.addAuth", "An error occured while running OnAuthenticationChanged event handler", ex)); return(user); } catch (InvalidOperationException) { foreach (var entry in cacheEntries) { await c.DeleteAsync <AuthenticationClaim>($"{provider}_{entry.Key}_{entry.Value}", s => s.Index(GetIndex <AuthenticationClaim>())); } throw; } }