public bool AddNode(IKey key, NodeRole nodeRole, IPAddress ipAddress) { AccountIdentity accountIdentity = GetAccountIdentity(key); if (accountIdentity == null) { GetOrAddIdentity(key); accountIdentity = GetAccountIdentity(key); } if (accountIdentity != null) { lock (_sync) { NodeRecord node = _dataContext.Nodes.FirstOrDefault(n => n.Identity == accountIdentity && n.NodeRole == (byte)nodeRole); if (node == null) { node = new NodeRecord { Identity = accountIdentity, IPAddress = ipAddress.GetAddressBytes(), NodeRole = (byte)nodeRole }; _dataContext.Nodes.Add(node); if (!_keyToNodeMap.ContainsKey(key)) { _keyToNodeMap.Add(key, node); } return(true); } } } return(false); }
public AccountIdentity GetAccountIdentity(int accountId) { MySqlCommand cmd = connection.CreateCommand(); cmd.CommandText = string.Format("select * from account_identity where account_id = {0}", accountId); MySqlDataReader reader = cmd.ExecuteReader(); AccountIdentity ident = null; while (reader.Read()) { ident = new AccountIdentity(); ident.UniqId = Convert.ToInt32(reader["uniqid"]); ident.AccountId = Convert.ToInt32(reader["account_id"]); ident.Nickname = reader["nickname"].ToString(); ident.Status = (EStatus)Enum.Parse(typeof(EStatus), reader["status"].ToString()); ident.PlayerType = reader["playerType"].ToString(); ident.Level = Convert.ToInt32(reader["level"]); ident.Experience = Convert.ToInt32(reader["experience"]); ident.Description = reader["description"].ToString(); ident.TutorialProgress = Convert.ToInt32(reader["tutorialProgress"]); ident.CanCraft = Convert.ToByte(reader["canCraft"]); ident.CanPlayRanked = Convert.ToByte(reader["canPlayRanked"]); ident.IdentId = reader["ident_id"].ToString(); } reader.Close(); return((ident != null) ? ident : null); }
protected override void BeginProcessing() { if (Identity == null) { Identity = new AccountIdentity(Context.User); } }
public static bool CanFindAccount(this Cmdlet command, AccountIdentity account, AccountType accountType) { if (account == null) { return(false); } var name = account.Name; var error = $"Cannot find an account with identity '{name}'."; if (accountType == AccountType.Role) { if (!Role.Exists(name) && !RolesInRolesManager.IsCreatorOwnerRole(name) && !RolesInRolesManager.IsSystemRole(name)) { command.WriteError(new ErrorRecord(new ObjectNotFoundException(error), ErrorIds.AccountNotFound.ToString(), ErrorCategory.ObjectNotFound, account)); return(false); } } if (accountType == AccountType.User && !User.Exists(name)) { command.WriteError(new ErrorRecord(new ObjectNotFoundException(error), ErrorIds.AccountNotFound.ToString(), ErrorCategory.ObjectNotFound, account)); return(false); } return(true); }
/// <summary> /// Constrtuctor /// </summary> public AccountViewModel(MainWindowViewModel mainWindowViewModel) { // Get a reference back to the main window view model _mainWindowViewModel = mainWindowViewModel; // Instatiate new Account Identity AccountIdentity = new AccountIdentity(); // Wire up commands for Account Identity CommandGetNewAccountID = new RelayCommand(GetNewAccountID); CommandUpdateAccountID = new RelayCommand(UpdateAccountID); CommandRemoveWorker = new RelayCommand(RemoveAccountWorkers); // Wire up commands for button clicks CommandSaveWorkerSettings = new RelayCommand(PersistWorkerSettings); CommandScanHardware = new RelayCommand(ScanHardware); CommandSaveAccountWorkerHardware = new RelayCommand(PersistWorkerHardware); CommandUpdateCoinType = new RelayCommand(UpdateCoinType); // Load previous GUID or get a new GUID InitAccountID(); // Load list of workers for account InitAccountWorkers(); // Load worker settings from config file or set the default worker settings and save to file InitWorkerSettings(); // Load hardware settings from API or scan for hardware InitWorkerHardware(); // Update worker list on main window _mainWindowViewModel.GetAccountWorkerList(); }
/// <summary> /// Call API and retrieve new GUID /// </summary> /// <param name="parameter"></param> public void GetNewAccountID(object parameter) { try { // Call API to get new GUID // Set GUID in account identity object AccountIdentityAPI accountIdentityAPI = new AccountIdentityAPI(); AccountIdentity = accountIdentityAPI.GetAccountID(); // Set global variable for Account ID Application.Current.Properties["AccountID"] = AccountIdentity.AccountGuid; // Write GUID to account identity config file AccountIdentityFile accountIdentityFile = new AccountIdentityFile(); accountIdentityFile.WriteJsonToFile(AccountIdentity); // Notify UI to update OnPropertyChanged("AccountGuid"); // Removed previous collection of account workers accountWorkersList = new ObservableCollection <AccountWorkers>(); // Insert new worker for account InsertAccountWorkers(); // Notify success ShowSuccess("New Account ID created"); } catch (Exception e) { throw new ApplicationException(string.Format("Error retrieving new account id"), e); } }
public async Task <IEnumerable <string> > TryRegisterAccount(RegisterDTO data) { if (await _accountRepository.GetByName(data.AccountName) != null) { throw new AccountInUseException(); } if (await _accountRepository.GetByEmail(data.Email) != null) { throw new EmailInUseException(); } var account = new Account { Creation = DateTime.Now, Email = data.Email, Name = data.AccountName, Password = GetHash(data.Password) }; await _accountRepository.Insert(account); var user = new AccountIdentity { News = data.AgreeReciveNews, UserName = data.AccountName, Account = account }; var result = await _userManager.CreateAsync(user, data.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, AccountType.Player.ToString()); // todo in future: email autentication // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); await _signInManager.SignInAsync(user, isPersistent : false); user.LockoutEnabled = true; return(null); } else { return(result.Errors.Select(x => x.Description)); } }
public TransactionalIdentity GetTransactionalIdentity(AccountIdentity accountIdentity) { if (accountIdentity == null) { throw new ArgumentNullException(nameof(accountIdentity)); } lock (_sync) { return(_dataContext.TransactionalIdentities.FirstOrDefault(g => g.Identity == accountIdentity)); } }
public void Initialize() { if (IsInitialized) { return; } _dataContext = new DataContext(_configurationService.Get <ISQLiteConfiguration>()); _dataContext.ChangeTracker.StateChanged += (s, e) => { AccountIdentity accountIdentity = e.Entry.Entity as AccountIdentity; }; _dataContext.Database.EnsureCreated(); _dataContext.EnsureConfigurationCompleted(); PeriodicTaskFactory.Start(() => { if (_isSaving) { return; } lock (_sync) { if (_isSaving) { return; } _isSaving = true; try { if (_dataContext.ChangeTracker.HasChanges()) { _dataContext.SaveChanges(); } } catch (Exception ex) { _logger.Error("Failure during saving data to database", ex); } finally { _isSaving = false; } } }, 1000, cancelToken: _cancellationTokenSource.Token, periodicTaskCreationOptions: System.Threading.Tasks.TaskCreationOptions.LongRunning); IsInitialized = true; }
private DataAccessService(IConfigurationService configurationService, IIdentityKeyProvidersRegistry identityKeyProvidersRegistry, IHashCalculationsRepository hashCalculationsRepository, ILoggerService loggerService) { _cancellationTokenSource = new CancellationTokenSource(); _configurationService = configurationService; _dataContext = new DataContext(_configurationService.Get <ISQLiteConfiguration>()); _dataContext.ChangeTracker.StateChanged += (s, e) => { AccountIdentity accountIdentity = e.Entry.Entity as AccountIdentity; }; _identityKeyProvider = identityKeyProvidersRegistry.GetInstance(); _defaultHashCalculation = hashCalculationsRepository.Create(Globals.DEFAULT_HASH); _logger = loggerService.GetLogger(nameof(DataAccessService)); }
/// <summary> /// Call API and GET new GUID for the account identity /// </summary> /// <returns></returns> public AccountIdentity GetAccountID() { try { string apiURL = APIConstants.APIURL + APIEndpoints.GetAccountGuid; AccountIdentity accountIdentity = DownloadSerializedJSONData <AccountIdentity>(apiURL); return(accountIdentity); } catch (Exception e) { logger.Error(e, "Could not download the account idenity information."); return(new AccountIdentity()); } }
public TransactionalIdentity AddTransactionalIdentity(AccountIdentity accountIdentity) { lock (_sync) { TransactionalIdentity transactionalIdentity = new TransactionalIdentity { Identity = accountIdentity }; _dataContext.TransactionalIdentities.Add(transactionalIdentity); return(transactionalIdentity); } }
public static Account GetAccountFromIdentity(this Cmdlet command, AccountIdentity identity) { Account account = identity; if (account == null) { if (RolesInRolesManager.IsCreatorOwnerRole(identity.Name) || RolesInRolesManager.IsSystemRole(identity.Name)) { return(Role.FromName(identity.Name)); } var error = $"Cannot find an account with identity '{identity.Name}'."; command.WriteError(new ErrorRecord(new ObjectNotFoundException(error), ErrorIds.AccountNotFound.ToString(), ErrorCategory.ObjectNotFound, identity)); } return(account); }
public TransactionalIdentity GetTransactionalIdentity(IKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } AccountIdentity accountIdentity = GetAccountIdentity(key); if (accountIdentity == null) { return(null); } return(GetTransactionalIdentity(accountIdentity)); }
/// <summary> /// Serialize object to JSON and write/overwrite file /// </summary> /// <param name="accountIdentity"></param> public void WriteJsonToFile(AccountIdentity accountIdentity) { string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.AccountIdentityFileName); try { // serialize JSON directly to a file using (StreamWriter file = File.CreateText(filePath)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, accountIdentity); } } catch (Exception e) { throw new ApplicationException(string.Format("Error reading reading file {0}", filePath), e); } }
public TransactionalBlock GetLastTransactionalBlock(AccountIdentity accountIdentity) { TransactionalBlock transactionalBlock = null; if (accountIdentity == null) { throw new ArgumentNullException(nameof(accountIdentity)); } TransactionalIdentity transactionalIdentity = GetTransactionalIdentity(accountIdentity); if (transactionalIdentity != null) { transactionalBlock = GetLastTransactionalBlock(transactionalIdentity); } return(transactionalBlock); }
private void DeserializeRole(string roleName) { var fileName = roleName; if (fileName.Contains("?") || fileName.Contains("*")) { string rootFolder = System.IO.Path.GetDirectoryName(fileName); var identity = new AccountIdentity(roleName, true); // if path is not absolute - add the Root folder if (!System.IO.Path.IsPathRooted(fileName)) { rootFolder = string.IsNullOrEmpty(Root) || Root.EndsWith("\\") ? Root : Root + "\\"; } foreach (var domain in WildcardFilter(identity.Domain, Directory.EnumerateDirectories(rootFolder), d => System.IO.Path.GetFileName(d))) { var files = WildcardFilter(identity.Account, Directory.EnumerateFiles(domain + @"\Roles"), f => System.IO.Path.GetFileName(f)).ToList(); foreach (var file in files) { DeserializeRoleFile(identity.ToString(), file); } } } else { // if path is not absolute - add the Root folder if (!System.IO.Path.IsPathRooted(fileName)) { var identity = new AccountIdentity(roleName); var target = string.IsNullOrEmpty(Root) || Root.EndsWith("\\") ? Root : Root + "\\"; fileName = target + identity.Domain + @"\Roles\" + identity.Account + PathUtils.RoleExtension; } // make sure the path has the proper extension if (!fileName.EndsWith(PathUtils.RoleExtension, StringComparison.OrdinalIgnoreCase)) { fileName += PathUtils.RoleExtension; } DeserializeRoleFile(roleName, fileName); } }
public static bool TryParse(XmlNode node, out AuthorizationEntry entry) { entry = new AuthorizationEntry(); if (node?.Attributes == null) { return(false); } var accessPermissionStr = node.Attributes?["Permission"].Value; var accountTypeStr = node?.Attributes["IdentityType"].Value; var identityStr = node?.Attributes["Identity"].Value; AccessPermission accessPermission; if (!Enum.TryParse(accessPermissionStr, true, out accessPermission) || accessPermission == AccessPermission.NotSet) { return(false); } AccountType accountType; if (!Enum.TryParse(accountTypeStr, true, out accountType) || accountType == AccountType.Unknown) { return(false); } AccountIdentity identity = null; try { identity = new AccountIdentity(identityStr, true); } catch { PowerShellLog.Error($"Invalid identity {identityStr} provided for service configuration."); } entry.AccessPermission = accessPermission; entry.IdentityType = accountType; entry.Identity = identity; entry.wildcardPattern = WildcardUtils.GetWildcardPattern(identity.Name); return(true); }
public AccountIdentity GetOrAddIdentity(IKey key) { AccountIdentity identity = GetAccountIdentity(key); if (identity == null) { identity = new AccountIdentity { PublicKey = key.Value.ToArray() }; lock (_sync) { _dataContext.AccountIdentities.Add(identity); _keyIdentityMap.Add(key, identity); } } return(identity); }
/// <summary> /// Load previous GUID from config file or get a new GUID from the API /// </summary> private void InitAccountID() { try { // Empty GUID used for validation Guid guidEmpty = new Guid(); // Attempt to read the GUID from the config file AccountIdentityFile accountIdentityFile = new AccountIdentityFile(); AccountIdentity = accountIdentityFile.ReadJsonFromFile(); // Validate if a GUID was actually read if (AccountIdentity.AccountGuid == guidEmpty) { try { // If no GUID found, then get a new GUID from the API AccountIdentityAPI accountIdentityAPI = new AccountIdentityAPI(); AccountIdentity = accountIdentityAPI.GetAccountID(); // Notify UI to update OnPropertyChanged("AccountGuid"); } catch (Exception) { MessageBox.Show("There was an error retrieving a new account id from the web. Please create a new one manually by selecting 'new account' before mining."); } // Write GUID to account identity config file accountIdentityFile.WriteJsonToFile(AccountIdentity); // Insert new worker for account InsertAccountWorkers(); } // Set global variable for Account ID Application.Current.Properties["AccountID"] = AccountIdentity.AccountGuid; } catch (Exception e) { throw new ApplicationException(string.Format("Error initializing account id"), e); } }
public void AddTransactionalBlock(IKey key, ulong syncBlockHeight, ushort blockType, ulong blockHeight, byte[] blockContent) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (blockContent == null) { throw new ArgumentNullException(nameof(blockContent)); } TransactionalIdentity transactionalIdentity = GetTransactionalIdentity(key); if (transactionalIdentity == null) { AccountIdentity accountIdentity = GetOrAddIdentity(key); transactionalIdentity = AddTransactionalIdentity(accountIdentity); } BlockHashKey blockHashKey = new BlockHashKey { SyncBlockHeight = syncBlockHeight, Hash = _defaultHashCalculation.CalculateHash(blockContent) }; TransactionalBlock transactionalBlock = new TransactionalBlock() { Identity = transactionalIdentity, HashKey = blockHashKey, SyncBlockHeight = syncBlockHeight, BlockContent = blockContent, BlockHeight = blockHeight, BlockType = blockType }; lock (_sync) { _dataContext.BlockHashKeys.Add(blockHashKey); _dataContext.TransactionalBlocks.Add(transactionalBlock); } }
public bool UpdateNode(IKey key, IPAddress ipAddress) { AccountIdentity accountIdentity = GetAccountIdentity(key); if (accountIdentity != null) { lock (_sync) { IEnumerable <NodeRecord> nodes = _dataContext.Nodes.Where(n => n.Identity == accountIdentity); foreach (var node in nodes) { node.IPAddress = ipAddress.GetAddressBytes(); _dataContext.Update(node); _keyToNodeMap[key].IPAddress = ipAddress.GetAddressBytes(); } } } return(false); }
internal bool AddSeed(IKey key, byte[] seed) { AccountIdentity identity = GetAccountIdentity(key); if (identity != null) { lock (_sync) { AccountSeed accountSeed = _dataContext.AccountSeeds.FirstOrDefault(s => s.Identity == identity); if (accountSeed == null) { accountSeed = new AccountSeed { Identity = identity, Seed = seed }; _dataContext.AccountSeeds.Add(accountSeed); } return(true); } } return(false); }
private void DeserializeUser(string userName) { var fileName = userName; // if path is not absolute - add the Root folder if (!System.IO.Path.IsPathRooted(fileName)) { var identity = new AccountIdentity(userName); var target = string.IsNullOrEmpty(Root) || Root.EndsWith("\\") ? Root : Root + "\\"; fileName = target + identity.Domain + @"\Users\" + identity.Account + PathUtils.UserExtension; } // make sure the path has the proper extension if (!fileName.EndsWith(PathUtils.UserExtension, StringComparison.OrdinalIgnoreCase)) { fileName += PathUtils.UserExtension; } if (fileName.Contains("?") || fileName.Contains("*")) { var users = System.IO.Path.GetDirectoryName(fileName); var domainName = System.IO.Path.GetDirectoryName(users); var root = System.IO.Path.GetDirectoryName(domainName); foreach (var domain in Directory.EnumerateDirectories(root)) { var files = WildcardFilter(fileName, Directory.EnumerateFiles(domain + @"\Users"), f => f).ToList(); foreach (var file in files) { DeserializeUserFile(userName, file); } } } else { DeserializeUserFile(userName, fileName); } }
/// <summary> /// Read object from file and deserialize JSON and map to object /// </summary> /// <returns></returns> public AccountIdentity ReadJsonFromFile() { string filePath = Path.Combine(FileConstants.ConfigFilePath(), FileNameConstants.AccountIdentityFileName); AccountIdentity accountIdentity = new AccountIdentity(); try { if (File.Exists(filePath)) { // deserialize JSON directly from a file using (StreamReader file = File.OpenText(filePath)) { JsonSerializer serializer = new JsonSerializer(); accountIdentity = (AccountIdentity)serializer.Deserialize(file, typeof(AccountIdentity)); } } return(accountIdentity); } catch (Exception e) { NLogProcessing.LogError(e, "Could not load Account Identity file."); return(accountIdentity); } }
private static bool CheckServiceAuthentication(HttpContext context, string serviceName, AccountIdentity identity, bool isAuthenticated) { if (identity.Name == Context.User.Name) { return(true); } if (isAuthenticated) { return(true); } const string disabledMessage = "The request could not be completed because the service requires authentication."; context.Response.StatusCode = 401; context.Response.StatusDescription = disabledMessage; context.Response.SuppressFormsAuthenticationRedirect = true; PowerShellLog.Error($"Attempt to call the {serviceName} service failed as - user not logged in, authentication failed, or no credentials provided."); return(false); }
public void ProcessRequest(HttpContext context) { var request = HttpContext.Current.Request; var userName = request.Params.Get("user"); var password = request.Params.Get("password"); var itemParam = request.Params.Get("script"); var pathParam = request.Params.Get("path"); var originParam = request.Params.Get("scriptDb"); var apiVersion = request.Params.Get("apiVersion"); var serviceMappingKey = request.HttpMethod + "/" + apiVersion; var isUpload = request.HttpMethod.Is("POST") && request.InputStream.Length > 0; var unpackZip = request.Params.Get("skipunpack").IsNot("true"); var skipExisting = request.Params.Get("skipexisting").Is("true"); var serviceName = apiVersionToServiceMapping.ContainsKey(serviceMappingKey) ? apiVersionToServiceMapping[serviceMappingKey] : string.Empty; // verify that the service is enabled if (!CheckServiceEnabled(apiVersion, request.HttpMethod)) { PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled."); return; } // verify that the user is authorized to access the end point var authUserName = string.IsNullOrEmpty(userName) ? Context.User.Name : userName; if (!ServiceAuthorizationManager.IsUserAuthorized(serviceName, authUserName, false)) { HttpContext.Current.Response.StatusCode = 401; PowerShellLog.Error($"Attempt to call the '{apiVersion}' service failed as user '{userName}' was not authorized."); return; } // login user if specified explicitly if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { var account = new AccountIdentity(userName); AuthenticationManager.Login(account.Name, password, false); } var isAuthenticated = Context.IsLoggedIn; var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated || string.IsNullOrEmpty(originParam) || originParam.Is("current"); var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam); var dbName = scriptDb.Name; if (!CheckServiceAuthentication(apiVersion, isAuthenticated)) { PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as - user not logged in, authentication failed or no credentials provided."); return; } if (isUpload) { switch (apiVersion) { case "media": if (ZipUtils.IsZipContent(request.InputStream) && unpackZip) { PowerShellLog.Debug("The uploaded asset will be extracted to Media Library."); using (var packageReader = new Sitecore.Zip.ZipReader(request.InputStream)) { foreach (var zipEntry in packageReader.Entries) { if (!zipEntry.IsDirectory) { ProcessMediaUpload(zipEntry.GetStream(), scriptDb, itemParam, zipEntry.Name, skipExisting); } } } } else { ProcessMediaUpload(request.InputStream, scriptDb, itemParam, null, skipExisting); } break; case "file": ProcessFileUpload(request.InputStream, originParam, pathParam); break; default: PowerShellLog.Error($"Requested API/Version ({apiVersion}) is not supported."); break; } return; } Item scriptItem; switch (apiVersion) { case "1": scriptItem = scriptDb.GetItem(itemParam) ?? scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam); break; case "media": ProcessMediaDownload(scriptDb, itemParam); return; case "file": ProcessFileDownload(originParam, pathParam); return; case "handle": ProcessHandle(originParam); return; default: UpdateCache(dbName); if (!apiScripts.ContainsKey(dbName)) { HttpContext.Current.Response.StatusCode = 404; return; } var dbScripts = apiScripts[scriptDb.Name]; if (!dbScripts.ContainsKey(itemParam)) { HttpContext.Current.Response.StatusCode = 404; return; } scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id); apiScripts = null; break; } ProcessScript(context, scriptItem); }
public void ProcessRequest(HttpContext context) { var request = HttpContext.Current.Request; var userName = request.Params.Get("user"); var password = request.Params.Get("password"); var itemParam = request.Params.Get("script"); var pathParam = request.Params.Get("path"); var originParam = request.Params.Get("scriptDb"); var apiVersion = request.Params.Get("apiVersion"); var isUpload = request.HttpMethod.Is("POST") && request.InputStream.Length > 0; var unpackZip = request.Params.Get("skipunpack").IsNot("true"); var skipExisting = request.Params.Get("skipexisting").Is("true"); if (!CheckServiceEnabled(apiVersion, request.HttpMethod)) { LogUtils.Debug($"The specified service {apiVersion} is not enabled.", this); return; } if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { var account = new AccountIdentity(userName); AuthenticationManager.Login(account.Name, password, false); } var isAuthenticated = Context.IsLoggedIn; var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated || string.IsNullOrEmpty(originParam) || originParam.Is("current"); var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam); var dbName = scriptDb.Name; if (!CheckServiceAuthentication(apiVersion, isAuthenticated)) { LogUtils.Debug($"The specified service {apiVersion} requires authentication.", this); return; } if (isUpload) { switch (apiVersion) { case "media": if (ZipUtils.IsZipContent(request.InputStream) && unpackZip) { LogUtils.Debug("The uploaded media item will be extracted to the media library.", this); using (var packageReader = new Sitecore.Zip.ZipReader(request.InputStream)) { foreach (var zipEntry in packageReader.Entries) { if (!zipEntry.IsDirectory) { ProcessMediaUpload(zipEntry.GetStream(), scriptDb, itemParam, zipEntry.Name, skipExisting); } } } } else { ProcessMediaUpload(request.InputStream, scriptDb, itemParam, null, skipExisting); } break; case "file": ProcessFileUpload(request.InputStream, originParam, pathParam); break; default: LogUtils.Debug($"The specified apiVersion {apiVersion} is not supported.", this); break; } return; } Item scriptItem; switch (apiVersion) { case "1": scriptItem = scriptDb.GetItem(itemParam) ?? scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam); break; case "media": ProcessMediaDownload(scriptDb, itemParam); return; case "file": ProcessFileDownload(originParam, pathParam); return; case "handle": ProcessHandle(originParam); return; default: UpdateCache(dbName); if (!apiScripts.ContainsKey(dbName)) { HttpContext.Current.Response.StatusCode = 404; return; } var dbScripts = apiScripts[scriptDb.Name]; if (!dbScripts.ContainsKey(itemParam)) { HttpContext.Current.Response.StatusCode = 404; return; } scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id); apiScripts = null; break; } ProcessScript(context, scriptItem); }
public void ProcessRequest(HttpContext context) { var request = HttpContext.Current.Request; var userName = request.Params.Get("user"); var password = request.Params.Get("password"); var itemParam = request.Params.Get("script"); var pathParam = request.Params.Get("path"); var originParam = request.Params.Get("scriptDb"); var apiVersion = request.Params.Get("apiVersion"); var serviceMappingKey = request.HttpMethod + "/" + apiVersion; var isUpload = request.HttpMethod.Is("POST") && request.InputStream.Length > 0; var unpackZip = request.Params.Get("skipunpack").IsNot("true"); var skipExisting = request.Params.Get("skipexisting").Is("true"); var scDB = request.Params.Get("sc_database"); var serviceName = apiVersionToServiceMapping.ContainsKey(serviceMappingKey) ? apiVersionToServiceMapping[serviceMappingKey] : string.Empty; // verify that the service is enabled if (!CheckServiceEnabled(apiVersion, request.HttpMethod)) { PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled."); return; } // verify that the user is authorized to access the end point var authUserName = string.IsNullOrEmpty(userName) ? Context.User.Name : userName; var identity = new AccountIdentity(authUserName); if (!ServiceAuthorizationManager.IsUserAuthorized(serviceName, identity.Name)) { HttpContext.Current.Response.StatusCode = 401; PowerShellLog.Error( $"Attempt to call the '{serviceMappingKey}' service failed as user '{userName}' was not authorized."); return; } lock (loginLock) { // login user if specified explicitly if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { AuthenticationManager.Login(identity.Name, password, false); } } var isAuthenticated = Context.IsLoggedIn; // in some cases we need to set the database as it's still set to web after authentication if (!scDB.IsNullOrEmpty()) { Context.Database = Database.GetDatabase(scDB); } var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated || string.IsNullOrEmpty(originParam) || originParam.Is("current"); var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam); var dbName = scriptDb?.Name; if (!CheckServiceAuthentication(apiVersion, isAuthenticated)) { PowerShellLog.Error( $"Attempt to call the {serviceMappingKey} service failed as - user not logged in, authentication failed or no credentials provided."); return; } if (scriptDb == null && !apiVersion.Is("file") && !apiVersion.Is("handle")) { PowerShellLog.Error( $"The '{serviceMappingKey}' service requires a database but none was found in parameters or Context."); return; } PowerShellLog.Info($"'{serviceMappingKey}' called by user: '******'"); PowerShellLog.Debug($"'{request.Url}'"); Item scriptItem; switch (apiVersion) { case "1": scriptItem = scriptDb.GetItem(itemParam) ?? scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam); break; case "media": if (isUpload) { if (ZipUtils.IsZipContent(request.InputStream) && unpackZip) { PowerShellLog.Debug("The uploaded asset will be extracted to Media Library."); using (var packageReader = new Sitecore.Zip.ZipReader(request.InputStream)) { itemParam = Path.GetDirectoryName(itemParam.TrimEnd('\\', '/')); foreach (var zipEntry in packageReader.Entries) { if (!zipEntry.IsDirectory && zipEntry.Size > 0) { ProcessMediaUpload(zipEntry.GetStream(), scriptDb, $"{itemParam}/{zipEntry.Name}", skipExisting); } } } } else if (request.Files?.AllKeys?.Length > 0) { foreach (string fileName in request.Files.Keys) { var file = request.Files[fileName]; ProcessMediaUpload(file.InputStream, scriptDb, $"{itemParam}/{file.FileName}", skipExisting); } } else { ProcessMediaUpload(request.InputStream, scriptDb, itemParam, skipExisting); } } else { ProcessMediaDownload(scriptDb, itemParam); } return; case "file": if (isUpload) { ProcessFileUpload(request.InputStream, originParam, pathParam); } else { ProcessFileDownload(originParam, pathParam); } return; case "handle": ProcessHandle(originParam); return; case "2": UpdateCache(dbName); if (!apiScripts.ContainsKey(dbName)) { HttpContext.Current.Response.StatusCode = 404; return; } var dbScripts = apiScripts[dbName]; if (!dbScripts.ContainsKey(itemParam)) { HttpContext.Current.Response.StatusCode = 404; return; } scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id); apiScripts = null; break; default: PowerShellLog.Error($"Requested API/Version ({serviceMappingKey}) is not supported."); return; } var streams = new Dictionary <string, Stream>(); if (request.Files?.AllKeys?.Length > 0) { foreach (string fileName in request.Files.AllKeys) { streams.Add(fileName, request.Files[fileName].InputStream); } } else if (request.InputStream != null) { streams.Add("stream", request.InputStream); } ProcessScript(context, scriptItem, streams); }
public void ProcessRequest(HttpContext context) { var request = context.Request; var requestParameters = request.Params; var username = requestParameters.Get("user"); var password = requestParameters.Get("password"); var authHeader = request.Headers["Authorization"]; if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(authHeader)) { if (authHeader.StartsWith("Basic")) { var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim(); var encoding = Encoding.GetEncoding("iso-8859-1"); var usernamePassword = encoding.GetString(System.Convert.FromBase64String(encodedUsernamePassword)); var separatorIndex = usernamePassword.IndexOf(':'); username = usernamePassword.Substring(0, separatorIndex); password = usernamePassword.Substring(separatorIndex + 1); } } var itemParam = requestParameters.Get("script"); var pathParam = requestParameters.Get("path"); var originParam = requestParameters.Get("scriptDb"); var sessionId = requestParameters.Get("sessionId"); var persistentSession = requestParameters.Get("persistentSession").Is("true"); var rawOutput = requestParameters.Get("rawOutput").Is("true"); var apiVersion = requestParameters.Get("apiVersion"); var serviceMappingKey = request.HttpMethod + "/" + apiVersion; var isUpload = request.HttpMethod.Is("POST") && request.InputStream.Length > 0; var unpackZip = requestParameters.Get("skipunpack").IsNot("true"); var skipExisting = requestParameters.Get("skipexisting").Is("true"); var scDb = requestParameters.Get("sc_database"); var serviceName = ApiVersionToServiceMapping.ContainsKey(serviceMappingKey) ? ApiVersionToServiceMapping[serviceMappingKey] : string.Empty; // verify that the service is enabled if (!CheckServiceEnabled(context, apiVersion, request.HttpMethod)) { return; } // verify that the user is authorized to access the end point var authUserName = string.IsNullOrEmpty(username) ? Context.User.Name : username; var identity = new AccountIdentity(authUserName); if (!CheckIsUserAuthorized(context, identity.Name, serviceName)) { return; } lock (LoginLock) { // login user if specified explicitly if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { AuthenticationManager.Login(identity.Name, password, false); } } var isAuthenticated = Context.IsLoggedIn; if (!CheckServiceAuthentication(context, apiVersion, serviceName, isAuthenticated)) { return; } // in some cases we need to set the database as it's still set to web after authentication if (!scDb.IsNullOrEmpty()) { Context.Database = Database.GetDatabase(scDb); } var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated || string.IsNullOrEmpty(originParam) || originParam.Is("current"); var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam); var dbName = scriptDb?.Name; if (scriptDb == null && !apiVersion.Is("file") && !apiVersion.Is("handle")) { PowerShellLog.Error($"The '{serviceMappingKey}' service requires a database but none was found in parameters or Context."); return; } PowerShellLog.Info($"'{serviceMappingKey}' called by user: '******'"); PowerShellLog.Debug($"'{request.Url}'"); Item scriptItem = null; switch (apiVersion) { case "1": scriptItem = scriptDb.GetItem(itemParam) ?? scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam); break; case "media": ProcessMedia(context, isUpload, scriptDb, itemParam, unpackZip, skipExisting); return; case "file": ProcessFile(context, isUpload, originParam, pathParam); return; case "handle": ProcessHandle(context, originParam); return; case "2": var apiScripts = GetApiScripts(dbName); if (apiScripts.ContainsKey(dbName)) { var dbScripts = apiScripts[dbName]; if (dbScripts.ContainsKey(itemParam)) { scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id); } } if (scriptItem == null) { context.Response.StatusCode = 404; context.Response.StatusDescription = "The specified script is invalid."; return; } break; case "script": ProcessScript(context, request, rawOutput, sessionId, persistentSession); return; default: PowerShellLog.Error($"Requested API/Version ({serviceMappingKey}) is not supported."); return; } ProcessScript(context, scriptItem); }