protected override async Task <ClaimsIdentity> GenerateClaimsAsync(TUser identityuser)
        {
            var id = await base.GenerateClaimsAsync(identityuser);

            User user = Users.GetUser(identityuser.UserName);

            if (user != null)
            {
                id.AddClaim(new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()));
                if (user.IsHost) // host users are part of every site by default
                {
                    id.AddClaim(new Claim(options.ClaimsIdentity.RoleClaimType, Constants.HostRole));
                    id.AddClaim(new Claim(options.ClaimsIdentity.RoleClaimType, Constants.AdminRole));
                }
                else
                {
                    Alias alias = Tenants.GetAlias();
                    foreach (UserRole userrole in UserRoles.GetUserRoles(user.UserId, alias.SiteId))
                    {
                        id.AddClaim(new Claim(options.ClaimsIdentity.RoleClaimType, userrole.Role.Name));
                    }
                }
            }

            return(id);
        }
        protected override async Task <ClaimsIdentity> GenerateClaimsAsync(TUser identityuser)
        {
            var id = await base.GenerateClaimsAsync(identityuser);

            User user = _users.GetUser(identityuser.UserName);

            if (user != null)
            {
                id.AddClaim(new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()));
                Alias           alias     = _tenants.GetAlias();
                List <UserRole> userroles = _userRoles.GetUserRoles(user.UserId, alias.SiteId).ToList();
                foreach (UserRole userrole in userroles)
                {
                    id.AddClaim(new Claim(_options.ClaimsIdentity.RoleClaimType, userrole.Role.Name));
                    // host users are members of every site
                    if (userrole.Role.Name == Constants.HostRole)
                    {
                        if (userroles.Where(item => item.Role.Name == Constants.RegisteredRole).FirstOrDefault() == null)
                        {
                            id.AddClaim(new Claim(_options.ClaimsIdentity.RoleClaimType, Constants.RegisteredRole));
                        }
                        if (userroles.Where(item => item.Role.Name == Constants.AdminRole).FirstOrDefault() == null)
                        {
                            id.AddClaim(new Claim(_options.ClaimsIdentity.RoleClaimType, Constants.AdminRole));
                        }
                    }
                }
            }

            return(id);
        }
Exemplo n.º 3
0
        public IActionResult GetFile(string appName, string filePath)
        {
            try
            {
                var alias        = _tenantResolver.GetAlias();
                var fullFilePath = ContentFileHelper.GetFilePath(_hostingEnvironment.ContentRootPath, alias, Route, appName, filePath);
                if (string.IsNullOrEmpty(fullFilePath))
                {
                    return(NotFound());
                }

                var fileBytes = System.IO.File.ReadAllBytes(fullFilePath);
                var mimeType  = ContentFileHelper.GetMimeType(fullFilePath);

                return(mimeType.StartsWith("image") ? File(fileBytes, mimeType) :
                       new FileContentResult(fileBytes, mimeType)
                {
                    FileDownloadName = Path.GetFileName(fullFilePath)
                });
            }
            catch
            {
                return(NotFound());
            }
        }
Exemplo n.º 4
0
        public void Log(LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args)
        {
            Alias alias = TenantResolver.GetAlias();
            Log   log   = new Log();

            log.SiteId   = alias.SiteId;
            log.PageId   = null;
            log.ModuleId = null;
            log.UserId   = null;
            User user = UserPermissions.GetUser();

            if (user != null)
            {
                log.UserId = user.UserId;
            }
            HttpRequest request = Accessor.HttpContext.Request;

            if (request != null)
            {
                log.Url = request.Scheme.ToString() + "://" + request.Host.ToString() + request.Path.ToString() + request.QueryString.ToString();
            }

            Type type = Type.GetType(Class.ToString());

            if (type != null)
            {
                log.Category = type.AssemblyQualifiedName;
                log.Feature  = Utilities.GetTypeNameLastSegment(log.Category, 0);
            }
            else
            {
                log.Category = Class.ToString();
                log.Feature  = log.Category;
            }
            log.Function = Enum.GetName(typeof(LogFunction), Function);
            log.Level    = Enum.GetName(typeof(LogLevel), Level);
            if (Exception != null)
            {
                log.Exception = Exception.ToString();
            }
            log.Message         = Message;
            log.MessageTemplate = "";
            try
            {
                log.Properties = JsonSerializer.Serialize(Args);
            }
            catch // serialization error occurred
            {
                log.Properties = "";
            }
            Log(log);
        }
Exemplo n.º 5
0
        public void Log(LogLevel Level, object Class, LogFunction Function, Exception Exception, string Message, params object[] Args)
        {
            Alias alias = TenantResolver.GetAlias();
            Log   log   = new Log();

            log.SiteId   = alias.SiteId;
            log.PageId   = null;
            log.ModuleId = null;
            if (Accessor.HttpContext.User.FindFirst(ClaimTypes.PrimarySid) != null)
            {
                log.UserId = int.Parse(Accessor.HttpContext.User.FindFirst(ClaimTypes.PrimarySid).Value);
            }
            HttpRequest request = Accessor.HttpContext.Request;

            if (request != null)
            {
                log.Url = request.Scheme.ToString() + "://" + request.Host.ToString() + request.Path.ToString() + request.QueryString.ToString();
            }

            Type type = Type.GetType(Class.ToString());

            if (type != null)
            {
                log.Category = type.AssemblyQualifiedName;
                log.Feature  = Utilities.GetTypeNameLastSegment(log.Category, 0);
            }
            else
            {
                log.Category = Class.ToString();
                log.Feature  = log.Category;
            }
            log.Function = Enum.GetName(typeof(LogFunction), Function);
            log.Level    = Enum.GetName(typeof(LogLevel), Level);
            if (Exception != null)
            {
                log.Exception = JsonSerializer.Serialize(Exception.ToString());
            }
            log.Message         = Message;
            log.MessageTemplate = "";
            log.Properties      = JsonSerializer.Serialize(Args);
            Log(log);
        }
        protected override async Task <ClaimsIdentity> GenerateClaimsAsync(TUser identityuser)
        {
            var id = await base.GenerateClaimsAsync(identityuser);

            User user = Users.GetUser(identityuser.UserName);

            if (user != null)
            {
                if (user.IsSuperUser)
                {
                    id.AddClaim(new Claim(options.ClaimsIdentity.RoleClaimType, "Administrators"));
                }
                else
                {
                    Alias alias = Tenants.GetAlias();
                    foreach (UserRole userrole in UserRoles.GetUserRoles(user.UserId, alias.SiteId))
                    {
                        id.AddClaim(new Claim(options.ClaimsIdentity.RoleClaimType, userrole.Role.Name));
                    }
                }
            }

            return(id);
        }
Exemplo n.º 7
0
        //TODO shoud be moved to another layer
        private async Task <User> CreateUser(User user)
        {
            User newUser = null;

            bool verified;
            bool allowregistration;

            if (user.Username == UserNames.Host || User.IsInRole(RoleNames.Admin))
            {
                verified          = true;
                allowregistration = true;
            }
            else
            {
                verified          = false;
                allowregistration = _sites.GetSite(user.SiteId).AllowRegistration;
            }

            if (allowregistration)
            {
                IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);

                if (identityuser == null)
                {
                    identityuser                = new IdentityUser();
                    identityuser.UserName       = user.Username;
                    identityuser.Email          = user.Email;
                    identityuser.EmailConfirmed = verified;
                    var result = await _identityUserManager.CreateAsync(identityuser, user.Password);

                    if (result.Succeeded)
                    {
                        user.LastLoginOn   = null;
                        user.LastIPAddress = "";
                        newUser            = _users.AddUser(user);
                        if (!verified)
                        {
                            string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);

                            string url          = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                            string body         = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
                            var    notification = new Notification(user.SiteId, null, newUser, "User Account Verification", body, null);
                            _notifications.AddNotification(notification);
                        }

                        // assign to host role if this is the host user ( initial installation )
                        if (user.Username == UserNames.Host)
                        {
                            int      hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == RoleNames.Host).FirstOrDefault().RoleId;
                            UserRole userrole   = new UserRole();
                            userrole.UserId        = newUser.UserId;
                            userrole.RoleId        = hostroleid;
                            userrole.EffectiveDate = null;
                            userrole.ExpiryDate    = null;
                            _userRoles.AddUserRole(userrole);
                        }

                        // add folder for user
                        Folder folder = _folders.GetFolder(user.SiteId, Utilities.PathCombine("Users", Path.DirectorySeparatorChar.ToString()));
                        if (folder != null)
                        {
                            _folders.AddFolder(new Folder
                            {
                                SiteId      = folder.SiteId,
                                ParentId    = folder.FolderId,
                                Name        = "My Folder",
                                Path        = Utilities.PathCombine(folder.Path, newUser.UserId.ToString(), Path.DirectorySeparatorChar.ToString()),
                                Order       = 1,
                                IsSystem    = true,
                                Permissions = new List <Permission>
                                {
                                    new Permission(PermissionNames.Browse, newUser.UserId, true),
                                    new Permission(PermissionNames.View, RoleNames.Everyone, true),
                                    new Permission(PermissionNames.Edit, newUser.UserId, true)
                                }.EncodePermissions()
                            });
                        }
                    }
                }
                else
                {
                    var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);

                    if (result.Succeeded)
                    {
                        newUser = _users.GetUser(user.Username);
                    }
                }

                if (newUser != null && user.Username != UserNames.Host)
                {
                    // add auto assigned roles to user for site
                    List <Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
                    foreach (Role role in roles)
                    {
                        UserRole userrole = new UserRole();
                        userrole.UserId        = newUser.UserId;
                        userrole.RoleId        = role.RoleId;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate    = null;
                        _userRoles.AddUserRole(userrole);
                    }
                }

                if (newUser != null)
                {
                    newUser.Password = ""; // remove sensitive information
                    _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
                }
            }
            else
            {
                _logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Create, "User Registration Is Not Enabled For Site. User Was Not Added {User}", user);
            }

            return(newUser);
        }
 public Module Post([FromBody] Module module)
 {
     if (ModelState.IsValid && _userPermissions.IsAuthorized(User, EntityNames.Page, module.PageId, PermissionNames.Edit))
     {
         module = _modules.AddModule(module);
         _syncManager.AddSyncEvent(_tenants.GetTenant().TenantId, EntityNames.Site, _tenants.GetAlias().SiteId);
         _logger.Log(LogLevel.Information, this, LogFunction.Create, "Module Added {Module}", module);
     }
     else
     {
         _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Module {Module}", module);
         HttpContext.Response.StatusCode = 401;
         module = null;
     }
     return(module);
 }
        //TODO shoud be moved to another layer
        private async Task <User> CreateUser(User user)
        {
            User newUser = null;

            bool verified;
            bool allowregistration;

            if (user.Username == Constants.HostUser || User.IsInRole(Constants.AdminRole))
            {
                verified          = true;
                allowregistration = true;
            }
            else
            {
                verified          = false;
                allowregistration = _sites.GetSite(user.SiteId).AllowRegistration;
            }

            if (allowregistration)
            {
                IdentityUser identityuser = await _identityUserManager.FindByNameAsync(user.Username);

                if (identityuser == null)
                {
                    identityuser                = new IdentityUser();
                    identityuser.UserName       = user.Username;
                    identityuser.Email          = user.Email;
                    identityuser.EmailConfirmed = verified;
                    var result = await _identityUserManager.CreateAsync(identityuser, user.Password);

                    if (result.Succeeded)
                    {
                        user.LastLoginOn   = null;
                        user.LastIPAddress = "";
                        newUser            = _users.AddUser(user);
                        if (!verified)
                        {
                            Notification notification = new Notification();
                            notification.SiteId     = user.SiteId;
                            notification.FromUserId = null;
                            notification.ToUserId   = newUser.UserId;
                            notification.ToEmail    = "";
                            notification.Subject    = "User Account Verification";
                            string token = await _identityUserManager.GenerateEmailConfirmationTokenAsync(identityuser);

                            string url = HttpContext.Request.Scheme + "://" + _tenants.GetAlias().Name + "/login?name=" + user.Username + "&token=" + WebUtility.UrlEncode(token);
                            notification.Body        = "Dear " + user.DisplayName + ",\n\nIn Order To Complete The Registration Of Your User Account Please Click The Link Displayed Below:\n\n" + url + "\n\nThank You!";
                            notification.ParentId    = null;
                            notification.CreatedOn   = DateTime.UtcNow;
                            notification.IsDelivered = false;
                            notification.DeliveredOn = null;
                            _notifications.AddNotification(notification);
                        }

                        // assign to host role if this is the host user ( initial installation )
                        if (user.Username == Constants.HostUser)
                        {
                            int      hostroleid = _roles.GetRoles(user.SiteId, true).Where(item => item.Name == Constants.HostRole).FirstOrDefault().RoleId;
                            UserRole userrole   = new UserRole();
                            userrole.UserId        = newUser.UserId;
                            userrole.RoleId        = hostroleid;
                            userrole.EffectiveDate = null;
                            userrole.ExpiryDate    = null;
                            _userRoles.AddUserRole(userrole);
                        }

                        // add folder for user
                        Folder folder = _folders.GetFolder(user.SiteId, "Users\\");
                        if (folder != null)
                        {
                            _folders.AddFolder(new Folder
                            {
                                SiteId      = folder.SiteId,
                                ParentId    = folder.FolderId,
                                Name        = "My Folder",
                                Path        = folder.Path + newUser.UserId.ToString() + "\\",
                                Order       = 1,
                                IsSystem    = true,
                                Permissions = "[{\"PermissionName\":\"Browse\",\"Permissions\":\"[" + newUser.UserId.ToString() + "]\"},{\"PermissionName\":\"View\",\"Permissions\":\"All Users\"},{\"PermissionName\":\"Edit\",\"Permissions\":\"[" +
                                              newUser.UserId.ToString() + "]\"}]"
                            });
                        }
                    }
                }
                else
                {
                    var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, user.Password, false);

                    if (result.Succeeded)
                    {
                        newUser = _users.GetUser(user.Username);
                    }
                }

                if (newUser != null && user.Username != Constants.HostUser)
                {
                    // add auto assigned roles to user for site
                    List <Role> roles = _roles.GetRoles(user.SiteId).Where(item => item.IsAutoAssigned).ToList();
                    foreach (Role role in roles)
                    {
                        UserRole userrole = new UserRole();
                        userrole.UserId        = newUser.UserId;
                        userrole.RoleId        = role.RoleId;
                        userrole.EffectiveDate = null;
                        userrole.ExpiryDate    = null;
                        _userRoles.AddUserRole(userrole);
                    }
                }

                if (newUser != null)
                {
                    newUser.Password = ""; // remove sensitive information
                    _logger.Log(user.SiteId, LogLevel.Information, this, LogFunction.Create, "User Added {User}", newUser);
                }
            }
            else
            {
                _logger.Log(user.SiteId, LogLevel.Error, this, LogFunction.Create, "User Registration Is Not Enabled For Site. User Was Not Added {User}", user);
            }

            return(newUser);
        }
Exemplo n.º 10
0
        public void Log(int siteId, LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args)
        {
            Log log = new Log();

            if (siteId == -1)
            {
                log.SiteId = null;
                Alias alias = _tenantResolver.GetAlias();
                if (alias != null)
                {
                    log.SiteId = alias.SiteId;
                }
            }
            else
            {
                log.SiteId = siteId;
            }
            log.PageId   = null;
            log.ModuleId = null;
            log.UserId   = null;
            User user = _userPermissions.GetUser();

            if (user != null)
            {
                log.UserId = user.UserId;
            }
            HttpRequest request = _accessor.HttpContext.Request;

            if (request != null)
            {
                log.Url = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
            }

            Type type = @class.GetType();

            if (type != null)
            {
                log.Category = type.AssemblyQualifiedName;
                log.Feature  = Utilities.GetTypeNameLastSegment(log.Category, 0);
            }
            else
            {
                log.Category = @class.ToString();
                log.Feature  = log.Category;
            }
            log.Function = Enum.GetName(typeof(LogFunction), function);
            log.Level    = Enum.GetName(typeof(LogLevel), level);
            if (exception != null)
            {
                log.Exception = exception.ToString();
            }
            log.Message         = message;
            log.MessageTemplate = "";
            try
            {
                log.Properties = JsonSerializer.Serialize(args);
            }
            catch // serialization error occurred
            {
                log.Properties = "";
            }
            Log(log);
        }
Exemplo n.º 11
0
        public IActionResult GetFile(string appName, string filePath)
        {
            try
            {
                // Oqtane path and file name validation.
                // Partly commented because Path validation is not working as expected.
                if (!appName.IsPathOrFileValid() /*|| !filePath.Backslash().IsPathOrFileValid()*/)
                {
                    return(NotFound());
                }

                // Blacklist extensions should be denied.
                if (IsKnownRiskyExtension(filePath))
                {
                    return(NotFound());
                }
                if (Eav.Security.Files.FileNames.IsKnownCodeExtension(filePath))
                {
                    return(NotFound());
                }

                // Whitelist extensions like, js, css, json, map, xml, csv should all be fine or
                // any mime-type image/...  should be fine.
                var mimeType = GetMimeType(filePath);
                //if (!_whiteListExtensions.Contains(Path.GetExtension(filePath)) && (!mimeType.StartsWith("image"))) return NotFound();

                // Nothing in a ".xyz" folder or a subfolder of this should be allowed (like .data must be protected).
                if (appName.StartsWith(".") || filePath.StartsWith(".") || filePath.Backslash().Contains(@"\."))
                {
                    return(NotFound());
                }

                // Validate for alias.
                var alias = _tenantResolver.GetAlias();
                if (alias == null)
                {
                    return(NotFound());
                }

                var folder = Route switch
                {
                    "adam" => "adam",
                    "sxc" => "2sxc",
                    _ => "2sxc"
                };

                // todo: put into constants somewhere
                var aliasPart   = $@"Content\Tenants\{alias.TenantId}\Sites\{alias.SiteId}\{folder}";
                var appPath     = Path.Combine(_hostingEnvironment.ContentRootPath, aliasPart);
                var fullAppPath = Path.Combine(appPath, appName).Backslash();

                // Check that the app-folder folder with provided appName exists.
                //if (!Directory.GetDirectories(appPath).Any(f => string.Equals(f, fullAppPath, StringComparison.OrdinalIgnoreCase))) return NotFound();

                // Check that file exist in file system.
                var fullFilePath = Path.Combine(_hostingEnvironment.ContentRootPath, aliasPart, appName, filePath).Backslash();
                if (!System.IO.File.Exists(fullFilePath))
                {
                    return(NotFound());
                }

                // Check that file with filePath exists in appPath.
                //if (!GetAllFiles(appPath).Any(f => string.Equals(f, fullFilePath, StringComparison.OrdinalIgnoreCase))) return NotFound();

                var fileBytes = System.IO.File.ReadAllBytes(fullFilePath);

                return(mimeType.StartsWith("image") ? File(fileBytes, mimeType) :
                       new FileContentResult(fileBytes, mimeType)
                {
                    FileDownloadName = Path.GetFileName(fullFilePath)
                });
            }
            catch
            {
                //Console.WriteLine(e);
                return(NotFound());
            }
        }
        public override async ValueTask <RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            var wrapLog = Log.Call <RouteValueDictionary>();

            // Check required route values: alias, appFolder, controller, action.
            if (!values.ContainsKey("alias"))
            {
                return(wrapLog("Error: missing required 'alias' route value", values));
            }
            var aliasId = int.Parse((string)values["alias"]);

            if (!values.ContainsKey("appFolder"))
            {
                return(wrapLog("Error: missing required 'appFolder' route value", values));
            }
            var appFolder = (string)values["appFolder"];

            if (!values.ContainsKey("controller"))
            {
                return(wrapLog("Error: missing required 'controller' route value", values));
            }
            var controller = (string)values["controller"];

            if (!values.ContainsKey("action"))
            {
                return(wrapLog("Error: missing required 'action' route value", values));
            }
            var action = (string)values["action"];

            Log.Add($"TransformAsync route required values are present, alias:{aliasId}, app:{appFolder}, ctrl:{controller}, act:{action}.");

            try
            {
                var controllerTypeName = $"{controller}Controller";
                Log.Add($"Controller TypeName: {controllerTypeName}");
                values.Add("controllerTypeName", controllerTypeName);

                var edition = GetEdition(values);
                Log.Add($"Edition: {edition}");

                var alias     = _tenantResolver.GetAlias();
                var aliasPart = $@"Content\Tenants\{alias.TenantId}\Sites\{alias.SiteId}\2sxc";

                var controllerFolder = Path.Combine(aliasPart, appFolder, edition.Backslash(), "api");
                Log.Add($"Controller Folder: {controllerFolder}");

                var area = $"{alias.SiteId}/{OqtConstants.ApiAppLinkPart}/{appFolder}/{edition}api";
                Log.Add($"Area: {area}");
                values.Add("area", area);

                var controllerPath = Path.Combine(controllerFolder, controllerTypeName + ".cs");
                Log.Add($"Controller Path: {controllerPath}");

                var apiFile = Path.Combine(_hostingEnvironment.ContentRootPath, controllerPath);
                Log.Add($"Absolute Path: {apiFile}");
                values.Add("apiFile", apiFile);

                var dllName = $"DynCode_{controllerFolder.Replace(@"\", "_")}_{System.IO.Path.GetFileNameWithoutExtension(apiFile)}";
                Log.Add($"Dll Name: {dllName}");
                values.Add("dllName", dllName);

                // help with path resolution for compilers running inside the created controller
                httpContext.Request?.HttpContext.Items.Add(CodeCompiler.SharedCodeRootPathKeyInCache, controllerFolder);

                return(wrapLog($"ok, TransformAsync route required values are prepared", values));
            }
            catch (Exception e)
            {
                return(wrapLog($"Error, unexpected error {e.Message} while preparing controller.", values));
            }
        }
Exemplo n.º 13
0
 public Setting Post([FromBody] Setting setting)
 {
     if (ModelState.IsValid && IsAuthorized(setting.EntityName, setting.EntityId, PermissionNames.Edit))
     {
         setting = _settings.AddSetting(setting);
         if (setting.EntityName == EntityNames.Module)
         {
             _syncManager.AddSyncEvent(_tenants.GetTenant().TenantId, EntityNames.Site, _tenants.GetAlias().SiteId);
         }
         _logger.Log(LogLevel.Information, this, LogFunction.Create, "Setting Added {Setting}", setting);
     }
     else
     {
         _logger.Log(LogLevel.Error, this, LogFunction.Create, "User Not Authorized To Add Setting {Setting}", setting);
         HttpContext.Response.StatusCode = 401;
         setting = null;
     }
     return(setting);
 }