public async Task <string> GetPEMAsync(DeviceRepository deviceRepo, string partitionKey, string rowKey) { var pems = GetCloudTable(deviceRepo); var result = await pems.ExecuteAsync(TableOperation.Retrieve <PEMIndexDTO>(partitionKey, rowKey)); if (result.Result is PEMIndexDTO pemIndex) { var pemResult = pemIndex.ToPEM(); if (pemResult.Successful) { return(pemResult.Result); } else { _adminLogger.AddError("DevicePEMRepo_GetPEMAsync", pemResult.Errors.First().Message); return(null); } } else { _adminLogger.AddError("DevicePEMRepo_GetPEMAsync", "Null response from TableStorage", rowKey.ToKVP("rowKey"), partitionKey.ToKVP("partitionKey"), deviceRepo.OwnerOrganization.Text.ToKVP("org"), deviceRepo.Key.ToKVP("repo")); return(null); } }
protected async Task <ResourceResponse <Document> > UpsertDocumentAsync(TEntity item) { if (item is IValidateable) { var result = Validator.Validate(item as IValidateable); if (!result.Successful) { throw new ValidationException("Invalid Data.", result.Errors); } } item.DatabaseName = _dbName; item.EntityType = typeof(TEntity).Name; var upsertResult = await Client.UpsertDocumentAsync(await GetCollectionDocumentsLinkAsync(), item); switch (upsertResult.StatusCode) { case System.Net.HttpStatusCode.BadRequest: _logger.AddError("DocumentDBRepoBase_UpsertDocumentAsync", "BadRequest", typeof(TEntity).Name.ToKVP("entityType"), item.Id.ToKVP("id")); throw new Exception($"Bad Request on Upsert {typeof(TEntity).Name}"); case System.Net.HttpStatusCode.Forbidden: _logger.AddError("DocumentDBRepoBase_UpsertDocumentAsync", "Forbidden", typeof(TEntity).Name.ToKVP("entityType"), item.Id.ToKVP("id")); throw new Exception($"Forbidden on Upsert {typeof(TEntity).Name}"); case System.Net.HttpStatusCode.Conflict: _logger.AddError("DocumentDBRepoBase_UpsertDocumentAsync", "Conflict", typeof(TEntity).Name.ToKVP("entityType"), item.Id.ToKVP("id")); throw new ContentModifiedException() { EntityType = typeof(TEntity).Name, Id = item.Id }; case System.Net.HttpStatusCode.RequestEntityTooLarge: _logger.AddError("DocumentDBRepoBase_UpsertDocumentAsync", "RequestEntityTooLarge", typeof(TEntity).Name.ToKVP("entityType"), item.Id.ToKVP("id")); throw new Exception($"RequestEntityTooLarge Upsert on type {typeof(TEntity).Name}"); } if (_cacheProvider != null) { await _cacheProvider.AddAsync(GetCacheKey(item.Id), JsonConvert.SerializeObject(item)); } return(upsertResult); }
public async Task StartAsync() { lock (_msgSendTimers) { if (Status != null && Status.IsRunning) { return; } } await ConnectAsync(); var messages = new List <string>(); lock (_msgSendTimers) { var transmisssionPlans = _instance.TransmissionPlans.Where(st => st?.ForState.Id == CurrentState.Id); if (transmisssionPlans.Any()) { foreach (var plan in transmisssionPlans) { plan.Message.Value = _simulator.MessageTemplates.Where(msg => msg.Id == plan.Message.Id).FirstOrDefault(); if (plan.Message.Value == null) { _adminLogger.AddError("SimulatorRuntime_Start", $"Could not resolve message template {plan.Message.Text}", _simulator.Name.ToKVP("simulatorName")); messages.Add($"Could not resolve message template for {plan.Message.Text}"); } else { var tmr = new Timer(SendMessage, plan, plan.PeriodMS, plan.PeriodMS); messages.Add($"Started {plan.PeriodMS}ms timer for plan {plan.Message}"); _msgSendTimers.Add(tmr); } } } else { messages.Add($"No transmission plans identified for state {CurrentState.Name} on {_simulator.Name}."); } } Status = new SimulatorStatus() { IsRunning = true, Text = "Running" }; foreach (var message in messages) { await _notificationPublisher.PublishAsync(Targets.WebSocket, Channels.Simulator, InstanceId, message, CurrentState); } await _notificationPublisher.PublishAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Simulator Started", CurrentState); await _notificationPublisher.PublishAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Status Update", Status); }
public async Task <InvokeResult <AppInstance> > UpdateLastLoginAsync(string appUserId, AuthRequest existingAppInstance) { var appInstance = await _appInstanceRepo.GetAppInstanceAsync(appUserId, existingAppInstance.AppInstanceId); if (appInstance == null) { _adminLogger.AddError("AppInstanceManager_UpdateLastLoginAsync", "Could not load, possible user id change", new KeyValuePair <string, string>("appUserId", appUserId), new KeyValuePair <string, string>("appInstanceId", existingAppInstance.AppInstanceId)); return(await CreateForUserAsync(appUserId, existingAppInstance)); } else { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "AppInstanceManager_UpdateLastLoginAsync", "Update Last Login Information", new KeyValuePair <string, string>("appUserId", appUserId), new KeyValuePair <string, string>("appInstanceId", existingAppInstance.AppInstanceId)); appInstance.LastLogin = DateTime.UtcNow.ToJSONString(); await _appInstanceRepo.UpdateAppInstanceAsync(appInstance); return(InvokeResult <AppInstance> .Create(appInstance)); } }
public async Task <InvokeResult> SendResetPasswordLinkAsync(SendResetPasswordLink sendResetPasswordLink) { var validationResult = _authRequestValidators.ValidateSendPasswordLinkRequest(sendResetPasswordLink); if (!validationResult.Successful) { return(validationResult); } var appUser = await _userManager.FindByEmailAsync(sendResetPasswordLink.Email); if (appUser == null) { _adminLogger.AddError("PasswordManager_SendResetPasswordLinkAsync", "CouldNotFindUser", new System.Collections.Generic.KeyValuePair <string, string>("email", sendResetPasswordLink.Email)); return(InvokeResult.FromErrors(new ErrorMessage(UserAdminResources.Err_ResetPwd_CouldNotFindUser))); } var token = await _userManager.GeneratePasswordResetTokenAsync(appUser); var encodedToken = System.Net.WebUtility.UrlEncode(token); var callbackUrl = $"{_appConfig.WebAddress}{ACTION_RESET_PASSWORD}?code={encodedToken}"; var mobileCallbackUrl = $"nuviot://resetpassword?code={token}"; #if DIAG _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "PasswordManager_SendResetPasswordLinkAsync", "SentToken", token.ToKVP("token"), appUser.Id.ToKVP("appUserId"), encodedToken.ToKVP("encodedToken"), appUser.Email.ToKVP("toEmailAddress")); #endif var subject = UserAdminResources.Email_ResetPassword_Subject.Replace("[APP_NAME]", _appConfig.AppName); var body = UserAdminResources.Email_ResetPassword_Body.Replace("[CALLBACK_URL]", callbackUrl).Replace("[MOBILE_CALLBACK_URL]", mobileCallbackUrl); var result = await _emailSender.SendAsync(sendResetPasswordLink.Email, subject, body); if (result.Successful) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "PasswordManager_SendResetPasswordLinkAsync", "SentLink", appUser.Id.ToKVP("appUserId"), appUser.Email.ToKVP("toEmailAddress")); var org = appUser.CurrentOrganization == null?EntityHeader.Create(Guid.Empty.ToId(), "????") : appUser.CurrentOrganization; await LogEntityActionAsync(appUser.Id, typeof(AppUser).Name, "SentResetPasswordLink", org, appUser.ToEntityHeader()); } else { _adminLogger.AddError("PasswordManager_SendResetPasswordLinkAsync", "Could Not Send Password Link", result.ErrorsToKVPArray()); } return(result); }
public async Task <InvokeResult <Invitation> > InviteUserAsync(Models.DTOs.InviteUser inviteViewModel, EntityHeader org, EntityHeader user) { ValidateAuthParams(org, user); if (inviteViewModel == null) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "OrgManager_InviteUserAsync", UserAdminErrorCodes.InviteIsNull.Message); return(InvokeResult <Invitation> .FromErrors(UserAdminErrorCodes.InviteIsNull.ToErrorMessage())); } if (String.IsNullOrEmpty(inviteViewModel.Email)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "OrgManager_InviteUserAsync", UserAdminErrorCodes.InviteEmailIsEmpty.Message); return(InvokeResult <Invitation> .FromErrors(UserAdminErrorCodes.InviteEmailIsEmpty.ToErrorMessage())); } var emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); if (!emailRegEx.Match(inviteViewModel.Email).Success) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "OrgManager_InviteUserAsync", UserAdminErrorCodes.InviteEmailIsInvalid.Message); return(InvokeResult <Invitation> .FromErrors(UserAdminErrorCodes.InviteEmailIsInvalid.ToErrorMessage())); } if (String.IsNullOrEmpty(inviteViewModel.Name)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "OrgManager_InviteUserAsync", UserAdminErrorCodes.InviteNameIsEmpty.Message); return(InvokeResult <Invitation> .FromErrors(UserAdminErrorCodes.InviteNameIsEmpty.ToErrorMessage())); } if (await _orgUserRepo.QueryOrgHasUserByEmailAsync(org.Id, inviteViewModel.Email)) { var existingUser = await _appUserRepo.FindByEmailAsync(inviteViewModel.Email); if (existingUser != null) { var msg = UserAdminResources.InviteUser_AlreadyPartOfOrg.Replace(Tokens.USERS_FULL_NAME, existingUser.Name).Replace(Tokens.EMAIL_ADDR, inviteViewModel.Email); return(InvokeResult <Invitation> .FromErrors(new ErrorMessage(msg))); } else { _adminLogger.AddError("OrgManager_InviteUserAsync", "User Found in Org Unit XRef Table Storage, but not in User, bad data", new KeyValuePair <string, string>("OrgId", org.Id), new KeyValuePair <string, string>("Email", inviteViewModel.Email)); } } var existingInvite = await _inviteUserRepo.GetInviteByOrgIdAndEmailAsync(org.Id, inviteViewModel.Email); if (existingInvite != null) { existingInvite.Status = Invitation.StatusTypes.Replaced; await _inviteUserRepo.UpdateInvitationAsync(existingInvite); } Organization organization; organization = await _organizationRepo.GetOrganizationAsync(org.Id); if (organization == null) { /* Quick and Dirty Error Checking, should Never Happen */ return(InvokeResult <Invitation> .FromError("Could not Load Org")); } var inviteModel = new Invitation() { RowKey = Guid.NewGuid().ToId(), PartitionKey = org.Id, OrganizationId = org.Id, OrganizationName = org.Text, InvitedById = user.Id, InvitedByName = user.Text, Message = inviteViewModel.Message, Name = inviteViewModel.Name, Email = inviteViewModel.Email, DateSent = DateTime.Now.ToJSONString(), Status = Invitation.StatusTypes.New, }; await AuthorizeAsync(user, org, "InviteUser", inviteModel.RowKey); inviteModel.OrganizationName = organization.Name; await _inviteUserRepo.InsertInvitationAsync(inviteModel); inviteModel = await _inviteUserRepo.GetInvitationAsync(inviteModel.RowKey); await SendInvitationAsync(inviteModel, organization.Name, user); inviteModel.DateSent = DateTime.Now.ToJSONString(); inviteModel.Status = Invitation.StatusTypes.Sent; await _inviteUserRepo.UpdateInvitationAsync(inviteModel); return(InvokeResult <Invitation> .Create(inviteModel)); }
public async Task <String> GetRAWJSONAsync(String rowKey, string partitionKey) { await InitAsync(); if (String.IsNullOrEmpty(rowKey)) { _logger.AddError("TableStorageBase_GetAsync", "emptyRowKey", new KeyValuePair <string, string>("tableName", GetTableName())); throw new Exception("Row and Partition Keys must be present to insert or replace an entity."); } if (String.IsNullOrEmpty(partitionKey)) { _logger.AddError("TableStorageBase_GetAsync", "emptyPartitionKey", new KeyValuePair <string, string>("tableName", GetTableName())); throw new Exception("Row and Partition Keys must be present to insert or replace an entity."); } var fullResourcePath = $"(PartitionKey='{partitionKey}',RowKey='{rowKey}')"; var operationUri = new Uri($"{_srvrPath}{fullResourcePath}"); using (var request = CreateRequest(fullResourcePath)) { request.DefaultRequestHeaders.Authorization = GetAuthHeader(request, "GET", fullResourcePath: fullResourcePath); using (var response = await request.GetAsync(operationUri)) { if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsStringAsync()); } if (response.StatusCode == HttpStatusCode.NotFound) { throw new RecordNotFoundException(GetTableName(), rowKey); } _logger.AddError("TableStorageBase_GetRawJSONAsync", "failureResponseCode", new KeyValuePair <string, string>("tableName", GetTableName()), new KeyValuePair <string, string>("reasonPhrase", response.ReasonPhrase), new KeyValuePair <string, string>("rowKey", rowKey), new KeyValuePair <string, string>("partitionKey", partitionKey)); throw new Exception($"Non success response from server: {response.RequestMessage}"); } } }