public async Task <InvokeResult <AuthResponse> > CreateUserAsync(RegisterUser newUser, bool sendAuthEmail = true, bool autoLogin = true) { if (String.IsNullOrEmpty(newUser.Email)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingEmail.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingEmail.ToErrorMessage())); } var user = await _appUserRepo.FindByEmailAsync(newUser.Email); if (user != null) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegErrorUserExists.Message); if (sendAuthEmail) { return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegErrorUserExists.ToErrorMessage())); } else { return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegisterUserExists_3rdParty.ToErrorMessage())); } } /* Need to check all these, if any fail, we want to aboart, we need to refactor this into the UserAdmin module :( */ if (String.IsNullOrEmpty(newUser.AppId)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingAppId.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingAppId.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.ClientType)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingClientType.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingClientType.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.DeviceId)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.AuthMissingDeviceId.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.AuthMissingDeviceId.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.FirstName)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingFirstLastName.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingFirstLastName.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.LastName)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingLastName.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingLastName.ToErrorMessage())); } if (String.IsNullOrEmpty(newUser.Password)) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegMissingPassword.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegMissingPassword.ToErrorMessage())); } var emailRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); if (!emailRegEx.Match(newUser.Email).Success) { _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Error, "UserServicesController_CreateUserAsync", UserAdminErrorCodes.RegInvalidEmailAddress.Message); return(InvokeResult <AuthResponse> .FromErrors(UserAdminErrorCodes.RegInvalidEmailAddress.ToErrorMessage())); } var appUser = new AppUser(newUser.Email, $"{newUser.FirstName} {newUser.LastName}") { FirstName = newUser.FirstName, LastName = newUser.LastName, }; var identityResult = await _userManager.CreateAsync(appUser, newUser.Password); if (identityResult.Successful) { await LogEntityActionAsync(appUser.Id, typeof(AppUser).Name, "New User Registered", null, appUser.ToEntityHeader()); if (autoLogin) { await _signInManager.SignInAsync(appUser); } if (newUser.ClientType != "WEBAPP") { var authRequest = new AuthRequest() { AppId = newUser.AppId, DeviceId = newUser.DeviceId, AppInstanceId = newUser.AppInstanceId, ClientType = newUser.ClientType, GrantType = "password", Email = newUser.Email, UserName = newUser.Email, Password = newUser.Password, }; var tokenResponse = await _authTokenManager.AccessTokenGrantAsync(authRequest); if (tokenResponse.Successful) { await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader()); return(InvokeResult <AuthResponse> .Create(tokenResponse.Result)); } else { var failedValidationResult = new InvokeResult <AuthResponse>(); failedValidationResult.Concat(tokenResponse); return(failedValidationResult); } } else { if (sendAuthEmail) { await _userVerificationmanager.SendConfirmationEmailAsync(null, appUser.ToEntityHeader()); } /* If we are logging in as web app, none of this applies */ return(InvokeResult <AuthResponse> .Create(new AuthResponse() { AccessToken = "N/A", AccessTokenExpiresUTC = "N/A", RefreshToken = "N/A", AppInstanceId = "N/A", RefreshTokenExpiresUTC = "N/A", IsLockedOut = false, User = appUser.ToEntityHeader(), Roles = new List <EntityHeader>() })); } } else { return(InvokeResult <AuthResponse> .FromInvokeResult(identityResult)); } }
public async Task <InvokeResult <Device> > CreateDeviceAsync(DeviceRepository deviceRepo, string deviceTypeId, EntityHeader org, EntityHeader user) { if (!deviceRepo.AutoGenerateDeviceIds) { return(InvokeResult <Device> .FromError("Can only create a device without a device id and name with a repository that is configure to auto generate device ids.")); } var timeStamp = DateTime.UtcNow.ToJSONString(); var device = new Device(); /* Note we just create it here for now then the record gets inserted we go ahead assign the name */ device.DeviceId = $"{deviceRepo.Key}{deviceRepo.IncrementingDeviceNumber:0000000}"; deviceRepo.IncrementingDeviceNumber++; deviceRepo.LastUpdatedBy = user; deviceRepo.LastUpdatedDate = timeStamp; await _deviceRepoRepo.UpdateDeviceRepositoryAsync(deviceRepo); device.Name = device.DeviceId; device.OwnerOrganization = org; device.CreatedBy = user; device.LastUpdatedBy = user; device.CreationDate = timeStamp; device.LastUpdatedDate = timeStamp; if (String.IsNullOrEmpty(device.PrimaryAccessKey)) { var guidBytes = new List <byte>(Guid.NewGuid().ToByteArray()); var timeStampBytes = new List <byte>(BitConverter.GetBytes(DateTime.Now.Ticks)); guidBytes.AddRange(timeStampBytes); device.PrimaryAccessKey = System.Convert.ToBase64String(guidBytes.ToArray()); } if (String.IsNullOrEmpty(device.SecondaryAccessKey)) { var guidBytes = new List <byte>(Guid.NewGuid().ToByteArray()); var timeStampBytes = new List <byte>(BitConverter.GetBytes(DateTime.Now.Ticks)); guidBytes.AddRange(timeStampBytes); device.SecondaryAccessKey = System.Convert.ToBase64String(guidBytes.ToArray()); } var deviceType = await _deviceTypeRepo.GetDeviceTypeAsync(deviceTypeId); if (!EntityHeader.IsNullOrEmpty(deviceType.Firmware)) { device.DesiredFirmware = deviceType.Firmware; } if (!EntityHeader.IsNullOrEmpty(deviceType.FirmwareRevision)) { device.DesiredFirmwareRevision = deviceType.FirmwareRevision; } device.DeviceType = new EntityHeader <DeviceAdmin.Models.DeviceType>() { Id = deviceType.Id, Text = deviceType.Name, Key = deviceType.Key }; device.DeviceConfiguration = deviceType.DefaultDeviceConfiguration; if (deviceRepo.UserOwnedDevicesOnly) { device.AssignedUser = user; device.OwnerUser = user; } var result = await AddDeviceAsync(deviceRepo, device, org, user); if (!result.Successful) { return(InvokeResult <Device> .FromInvokeResult(result)); } return(InvokeResult <Device> .Create(device)); }
public async Task <InvokeResult <AppUser> > AddDeviceUser([FromBody] DeviceUserRegistrationRequest newuser) { String userId = Guid.NewGuid().ToId(); newuser.Device.OwnerUser = EntityHeader.Create(userId, newuser.Email); var repo = await GetDeviceRepositoryWithSecretsAsync(); var addDeviceResult = await _deviceManager.AddDeviceAsync(repo, newuser.Device, OrgEntityHeader, UserEntityHeader); if (!addDeviceResult.Successful) { return(InvokeResult <AppUser> .FromInvokeResult(addDeviceResult)); } var appUser = new AppUser() { Id = userId, FirstName = newuser.FirstName, LastName = newuser.LastName, CurrentOrganization = OrgEntityHeader, Email = $"{repo.Id}-{newuser.Email}", PhoneNumber = newuser.PhoneNumber, UserName = $"{repo.Id}-{newuser.Email}", EmailConfirmed = true, PhoneNumberConfirmed = true, IsAppBuilder = false, IsOrgAdmin = false, IsUserDevice = true, PrimaryDevice = EntityHeader.Create(newuser.Device.Id, newuser.Device.DeviceId), DeviceConfiguration = EntityHeader.Create(newuser.Device.DeviceConfiguration.Id, newuser.Device.DeviceConfiguration.Text), DeviceRepo = EntityHeader.Create(newuser.Device.DeviceRepository.Id, newuser.Device.DeviceRepository.Text), ProfileImageUrl = new ImageDetails() { Width = 128, Height = 128, ImageUrl = "https://bytemaster.blob.core.windows.net/userprofileimages/watermark.png", Id = "b78ca749a1e64ce59df4aa100050dcc7" } }; SetAuditProperties(appUser); SetOwnedProperties(appUser); Console.WriteLine("Device Created - " + newuser.Device.DeviceId); try { var result = await _userManager.CreateAsync(appUser, newuser.Password); if (result.Succeeded) { var addToOrgResult = await _orgManager.AddUserToOrgAsync(OrgEntityHeader.Id, appUser.Id, OrgEntityHeader, UserEntityHeader); if (addToOrgResult.Successful) { return(InvokeResult <AppUser> .Create(appUser)); } else { await _userManager.DeleteAsync(appUser); return(InvokeResult <AppUser> .FromInvokeResult(addToOrgResult)); } } else { Console.WriteLine("Error creating user - removing device - " + newuser.Device.DeviceId); var device = await _deviceManager.GetDeviceByDeviceIdAsync(repo, newuser.Device.DeviceId, OrgEntityHeader, UserEntityHeader); await _deviceManager.DeleteDeviceAsync(repo, device.Id, OrgEntityHeader, UserEntityHeader); return(InvokeResult <AppUser> .FromError(result.Errors.First().Description)); } } catch (Exception) { Console.WriteLine("Exception - removing device - " + newuser.Device.DeviceId); var device = await _deviceManager.GetDeviceByDeviceIdAsync(repo, newuser.Device.DeviceId, OrgEntityHeader, UserEntityHeader); await _deviceManager.DeleteDeviceAsync(repo, device.Id, OrgEntityHeader, UserEntityHeader); throw; } }
public async Task <InvokeResult <Uri> > AddFileAsync(string fileName, byte[] data, string contentType = "application/octet-stream") { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(nameof(fileName)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } var result = await GetStorageContainerAsync(_containerName); if (!result.Successful) { return(InvokeResult <Uri> .FromInvokeResult(result.ToInvokeResult())); } var container = result.Result; if (fileName.StartsWith("/")) { fileName = fileName.TrimStart('/'); } var blob = container.GetBlockBlobReference(fileName); blob.Properties.ContentType = contentType; //TODO: Should really encapsulate the idea of retry of an action w/ error reporting var numberRetries = 5; var retryCount = 0; var completed = false; var stream = new MemoryStream(data); while (retryCount++ < numberRetries && !completed) { try { stream.Seek(0, SeekOrigin.Begin); await blob.UploadFromStreamAsync(stream); } catch (Exception ex) { if (retryCount == numberRetries) { _logger.AddException("CloudFileStorage_AddFileAsync", ex, _containerName.ToKVP("containerName")); var exceptionResult = InvokeResult.FromException("CloudFileStorage_AddFileAsync", ex); return(InvokeResult <Uri> .FromInvokeResult(exceptionResult)); } else { _logger.AddCustomEvent(LagoVista.Core.PlatformSupport.LogLevel.Warning, "CloudFileStorage_AddFileAsync", "", ex.Message.ToKVP("exceptionMessage"), ex.GetType().Name.ToKVP("exceptionType"), retryCount.ToString().ToKVP("retryCount")); } await Task.Delay(retryCount * 250); } } return(InvokeResult <Uri> .Create(blob.Uri)); }
private async Task <InvokeResult <DataStream> > PopulateCredentialsAsync(DataStream stream, EntityHeader org, EntityHeader user) { if (stream.StreamType.Value == DataStreamTypes.AzureBlob || stream.StreamType.Value == DataStreamTypes.AzureEventHub || stream.StreamType.Value == DataStreamTypes.AzureTableStorage || stream.StreamType.Value == DataStreamTypes.AzureTableStorage_Managed) { if (String.IsNullOrEmpty(stream.AzureAccessKeySecureId)) { return(InvokeResult <DataStream> .FromError("Attempt to load an azure type data stream, but secret key id is not present.")); } var azureSecretKeyResult = await _secureStorage.GetSecretAsync(org, stream.AzureAccessKeySecureId, user); if (!azureSecretKeyResult.Successful) { return(InvokeResult <DataStream> .FromInvokeResult(azureSecretKeyResult.ToInvokeResult())); } stream.AzureAccessKey = azureSecretKeyResult.Result; } else if (stream.StreamType.Value == DataStreamTypes.AWSS3 || stream.StreamType.Value == DataStreamTypes.AWSElasticSearch) { if (String.IsNullOrEmpty(stream.AWSSecretKeySecureId)) { return(InvokeResult <DataStream> .FromError("Attempt to load an azure type data stream, but secret key id is not present.")); } var awsSecretKeyResult = await _secureStorage.GetSecretAsync(org, stream.AWSSecretKeySecureId, user); if (!awsSecretKeyResult.Successful) { return(InvokeResult <DataStream> .FromInvokeResult(awsSecretKeyResult.ToInvokeResult())); } stream.AwsSecretKey = awsSecretKeyResult.Result; } else if (stream.StreamType.Value == DataStreamTypes.SQLServer || stream.StreamType.Value == DataStreamTypes.Postgresql || stream.StreamType.Value == DataStreamTypes.PointArrayStorage) { if (String.IsNullOrEmpty(stream.DBPasswordSecureId)) { return(InvokeResult <DataStream> .FromError("Attempt to load an azure type data stream, but secret key id is not present.")); } var dbSecretKeyResult = await _secureStorage.GetSecretAsync(org, stream.DBPasswordSecureId, user); if (!dbSecretKeyResult.Successful) { return(InvokeResult <DataStream> .FromInvokeResult(dbSecretKeyResult.ToInvokeResult())); } stream.DbPassword = dbSecretKeyResult.Result; } else if (stream.StreamType.Value == DataStreamTypes.Redis) { if (!String.IsNullOrEmpty(stream.RedisPasswordSecureId)) { var getSecretResult = await _secureStorage.GetSecretAsync(org, stream.RedisPasswordSecureId, user); if (!getSecretResult.Successful) { return(InvokeResult <DataStream> .FromInvokeResult(getSecretResult.ToInvokeResult())); } stream.RedisPassword = getSecretResult.Result; } } return(InvokeResult <DataStream> .Create(stream)); }