public DnnUnitTest(int portalId) { var simulator = new HttpSimulator.HttpSimulator(); simulator.SimulateRequest(); InstallComponents(); LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder"); //fix Globals.ApplicationMapPath var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; if (!string.IsNullOrEmpty(appPath)) { var mappath = typeof(Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic); mappath.SetValue(null, appPath); } //fix membership var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic); providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]); var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo { PortalID = portalId }; var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo); System.Web.HttpContext.Current.Items.Add("PortalSettings", ps); SqlProvider = new SqlDataProvider(); PortalId = portalId; }
public DnnUnitTest(int portalId) { var simulator = new HttpSimulator.HttpSimulator(); simulator.SimulateRequest(); InstallComponents(); LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder"); //fix Globals.ApplicationMapPath var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; if(!string.IsNullOrEmpty(appPath)) { var mappath = typeof (Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic); mappath.SetValue(null, appPath); } //fix membership var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic); providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]); var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo { PortalID = portalId }; var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo); System.Web.HttpContext.Current.Items.Add("PortalSettings", ps); SqlProvider = new SqlDataProvider(); PortalId = portalId; }
static string GetEmailOfRequestor(int RequesterUserID, string RequesterEmail) { string strEmail = ""; if (RequesterUserID == -1) { try { strEmail = RequesterEmail; } catch (Exception) { // User no longer exists strEmail = ""; } } else { try { DotNetNuke.Entities.Portals.PortalSettings objPortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); strEmail = DotNetNuke.Entities.Users.UserController.GetUserById(objPortalSettings.PortalId, RequesterUserID).Email; } catch (Exception) { // User no longer exists strEmail = ""; } } return(strEmail); }
protected void Page_Load(object sender, EventArgs e) { #region ViewPermission // Truyen vao tabid va mid de he thong kiem tra // Neu User dang truy cap co quyen thi he thong tra ra du lieu // Neu user khong co quyen he thong se thong bao not define try { DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); if (((Request.QueryString["tabid"] == null && Request.Form["tabid"] == null) || (Request.QueryString["mid"] == null && Request.Form["mid"] == null)) || !(Request.IsAuthenticated)) { WriteDataError("NotAuthenticated"); return; } // get TabId int TabId = -1; if ((Request.QueryString["tabid"] != null)) { TabId = Int32.Parse(Request.QueryString["tabid"]); } else if ((Request.Form["tabid"] != null)) { TabId = Int32.Parse(Request.Form["tabid"]); } // get ModuleId int ModuleId = -1; if ((Request.QueryString["mid"] != null)) { ModuleId = Int32.Parse(Request.QueryString["mid"]); } else if ((Request.Form["mid"] != null)) { ModuleId = Int32.Parse(Request.Form["mid"]); } objUserInfo = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo(); DotNetNuke.Entities.Modules.ModuleController mc = new DotNetNuke.Entities.Modules.ModuleController(); System.Collections.Hashtable settings = mc.GetModuleSettings(ModuleId); objModuleInfo = new DotNetNuke.Entities.Modules.ModuleController().GetModule(ModuleId, TabId); if (DotNetNuke.Security.Permissions.ModulePermissionController.CanViewModule(objModuleInfo)) { try { WriteData(); } catch (Exception ex) { WriteDataError(ex.Message); } } } catch (Exception ex) { WriteDataError(ex.Message); } #endregion base.OnInit(e); }
public override void Init(string[] args, DotNetNuke.Entities.Portals.PortalSettings portalSettings, DotNetNuke.Entities.Users.UserInfo userInfo, int activeTabId) { base.Init(args, portalSettings, userInfo, activeTabId); LogType = GetFlagValue(FlagLogType, "LogType", ""); Enabled = GetFlagValue <bool?>(FlagEnabled, "Enabled", null); Notify = GetFlagValue <bool?>(FlagNotify, "Notify", null); }
//public string PageName { get; } public override void Init(string[] args, DotNetNuke.Entities.Portals.PortalSettings portalSettings, DotNetNuke.Entities.Users.UserInfo userInfo, int activeTabId) { PageId = GetFlagValue(FlagPageId, "Page Id", -1); ModuleName = GetFlagValue(FlagModuleName, "Module Name", string.Empty); ModuleTitle = GetFlagValue(FlagModuleTitle, "Module Title", string.Empty); Deleted = GetFlagValue <bool?>(FlagDeleted, "Deleted", null); Page = GetFlagValue(FlagPage, "Page No", 1); Max = GetFlagValue(FlagMax, "Page Size", 10); }
public AutomationBase() { if (Driver == null) { var simulator = new HttpSimulator.HttpSimulator(); simulator.SimulateRequest(); InstallComponents(); LoadDnnProviders("data;logging;caching;authentication;members;roles;profiles;permissions;folder"); //fix Globals.ApplicationMapPath var appPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; if (!string.IsNullOrEmpty(appPath)) { var mappath = typeof(Globals).GetField("_applicationMapPath", BindingFlags.Static | BindingFlags.NonPublic); mappath.SetValue(null, appPath); } //fix membership var providerProp = typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic); providerProp.SetValue(null, Membership.Providers["AspNetSqlMembershipProvider"]); var objPortalAliasInfo = new DotNetNuke.Entities.Portals.PortalAliasInfo { PortalID = _portalId }; var ps = new DotNetNuke.Entities.Portals.PortalSettings(59, objPortalAliasInfo); System.Web.HttpContext.Current.Items.Add("PortalSettings", ps); SqlProvider = new SqlDataProvider(); PortalId = _portalId; switch (_browser) { case Common.BrowserType.firefox: _ffp = new FirefoxProfile { AcceptUntrustedCertificates = true }; Driver = new FirefoxDriver(_ffp); Driver.Navigate().GoToUrl(SiteUrl); break; case Common.BrowserType.ie: Driver = new InternetExplorerDriver(); Driver.Navigate().GoToUrl(SiteUrl); break; case Common.BrowserType.chrome: Driver = new ChromeDriver(); Driver.Navigate().GoToUrl(SiteUrl); break; } } }
public void ProcessRequest(HttpContext context) { #region ViewPermission // Truyen vao tabid va mid de he thong kiem tra // Neu User dang truy cap co quyen thi he thong tra ra du lieu // Neu user khong co quyen he thong se thong bao not define try { DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); if (!context.Request.IsAuthenticated) { WriteDataError(context, "NotAuthenticated"); return; } // get TabId int TabId = Utils.tabCheckCommon; // get ModuleId int ModuleId = Utils.moduleCheckCommon; objUserInfo = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo(); DotNetNuke.Entities.Modules.ModuleController mc = new DotNetNuke.Entities.Modules.ModuleController(); System.Collections.Hashtable settings = mc.GetModuleSettings(ModuleId); objModuleInfo = new DotNetNuke.Entities.Modules.ModuleController().GetModule(ModuleId, TabId); if (DotNetNuke.Security.Permissions.ModulePermissionController.CanViewModule(objModuleInfo)) { try { WriteData(context); return; } catch (Exception ex) { WriteDataError(context, ex.Message); return; } } else { WriteDataError(context, "NotPermission"); return; } } catch (Exception ex) { WriteDataError(context, ex.Message); return; } #endregion }
public override List <SitemapUrl> GetUrls(int portalId, DotNetNuke.Entities.Portals.PortalSettings ps, string version) { var listOfUrls = new List <SitemapUrl>(); foreach (var a in Article.GetAllArticlesList(portalId)) { var pageUrl = new SitemapUrl { Url = Utility.GetItemLinkUrl(a.ItemId, portalId), Priority = (float)0.5, LastModified = Convert.ToDateTime(a.LastUpdated), ChangeFrequency = SitemapChangeFrequency.Daily }; listOfUrls.Add(pageUrl); } return(listOfUrls); }
protected override void RenderContents(HtmlTextWriter writer) { if (UserId == -1) { return; } try { string output = string.Empty; DotNetNuke.Entities.Portals.PortalSettings ps = (DotNetNuke.Entities.Portals.PortalSettings)(Context.Items["PortalSettings"]); DotNetNuke.Entities.Users.UserInfo cu = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo(); string imagePath = string.Empty; int portalId = ps.PortalId; string tmp = string.Empty; if (Template == null) { tmp = "<span class=\"aslabelsmbold\">[RESX:Posts]:</span> [AF:PROFILE:POSTCOUNT]<br />" + "<span class=\"aslabelsmbold\">[RESX:RankName]:</span> [AF:PROFILE:RANKNAME]<br />" + "<span class=\"aslabelsmbold\">[RESX:RankDisplay]:</span> [AF:PROFILE:RANKDISPLAY] <br />" + "<span class=\"aslabelsmbold\">[RESX:LastUpdate]:</span> [AF:PROFILE:DATELASTACTIVITY:d] <br />" + "<span class=\"aslabelsmbold\">[RESX:MemberSince]:</span> [AF:PROFILE:DATECREATED:d]"; } else { tmp = Template.Text; } if (ModuleId == -1) { DotNetNuke.Entities.Modules.ModuleController mc = new DotNetNuke.Entities.Modules.ModuleController(); DotNetNuke.Entities.Tabs.TabController tc = new DotNetNuke.Entities.Tabs.TabController(); DotNetNuke.Entities.Tabs.TabInfo ti = null; foreach (DotNetNuke.Entities.Modules.ModuleInfo mi in mc.GetModules(portalId)) { if (mi.DesktopModule.ModuleName.ToUpperInvariant() == "Active Forums".ToUpperInvariant()) { ModuleId = mi.ModuleID; break; } } } output = TemplateUtils.ParseProfileTemplate(tmp, UserId, portalId, ModuleId, cu.UserID, ps.TimeZoneOffset); output = Utilities.LocalizeControl(output); writer.Write(output); } catch (Exception ex) { writer.Write(ex.Message); } }
public List <MenuNode> ManipulateNodes(List <MenuNode> nodes, DotNetNuke.Entities.Portals.PortalSettings portalSettings) { MenuNode categoriesMenu = new MenuNode { Text = "Product Categories" }; nodes.Insert(0, categoriesMenu); //Find Categories to Display in Menu HotcakesApplication hccApp = HccAppHelper.InitHccApp(); List <CategorySnapshot> categories = hccApp.CatalogServices.Categories.FindForMainMenu(); foreach (CategorySnapshot category in categories) { string url = HccUrlBuilder.RouteHccUrl(HccRoute.Category, new { slug = category.RewriteUrl }); categoriesMenu.Children.Add(new MenuNode { Text = category.Name, Url = url, Enabled = true, Parent = categoriesMenu }); } return(nodes); }
static string GetGetAssignedRoleName(int AssignedRoleID) { string strAssignedRoleName = ""; if (AssignedRoleID > -1) { try { DotNetNuke.Security.Roles.RoleController objRoleController = new DotNetNuke.Security.Roles.RoleController(); DotNetNuke.Entities.Portals.PortalSettings objPortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); strAssignedRoleName = String.Format("{0}", objRoleController.GetRole(AssignedRoleID, objPortalSettings.PortalId).RoleName); } catch (Exception) { // User no longer exists strAssignedRoleName = ""; } } return(strAssignedRoleName); }
/// <summary> /// Determines when to do a redirect. This is separate to the rewriting process. The module developer can create any type of Url redirect here, because the entire Url of the original request is passed in. /// </summary> /// <param name="tabId">Identified TabId, if known. -1 if no valid tabid identified.</param> /// <param name="portalid">Identified portalId.</param> /// <param name="httpAlias">Identified httpAlias of the request.</param> /// <param name="requestUri">The original requested Url</param> /// <param name="queryStringCol">The querystring collection of the original request</param> /// <param name="options">The friendly url options that currently apply.</param> /// <param name="redirectLocation">Out parameter that shows where to redirect to.</param> /// <param name="messages">List of messages for debug purposes. Add to this list to help debug your module.</param> /// <returns>true if 301 redirect is required, false if not. If true, the redirectLocation value must be a valid fully qualified Url.</returns> public override bool CheckForRedirect(int tabId, int portalid, string httpAlias, Uri requestUri, System.Collections.Specialized.NameValueCollection queryStringCol, FriendlyUrlOptions options, out string redirectLocation, ref List <string> messages) { bool doRedirect = false; if (messages == null) { messages = new List <string>(); } redirectLocation = "";//set blank location //compare to known pattern of old Urls if (_redirectUrls) { Regex oldNewsRegex = new Regex(@"(&articleType=(?<type>[^&]+))?((&(?<idname>[a-z]*Id)=(?<id>\d+))|((&month=(?<mm>[\d]{1,2}))?&year=(?<yyyy>[\d]{4})))(&(?<pgname>PageId|CurrentPage)=(?<pg>[\d]+))?", RegexOptions.IgnoreCase); Match oldNewsMatch = oldNewsRegex.Match(queryStringCol.ToString()); if (oldNewsMatch.Success) { Group typeGroup = oldNewsMatch.Groups["type"]; Group idNameGroup = oldNewsMatch.Groups["idname"]; Group idGroup = oldNewsMatch.Groups["id"]; Group pageGroup = oldNewsMatch.Groups["pg"]; Group pgNameGrp = oldNewsMatch.Groups["pgname"]; string msg = ""; string id = null; string furlKey = null; string friendlyUrl = null; if (idGroup != null && idGroup.Success) { id = idGroup.Value; } string idType = null; if (typeGroup != null && typeGroup.Success) { idType = typeGroup.Value.ToLower(); } else { if (idNameGroup != null && idNameGroup.Success) { //check if it's the 'ID' value if (idNameGroup.Value.ToLower() == "id") { idType = "id"; } } } //now look at the idType string pagePath = null; if (pgNameGrp != null && pgNameGrp.Success == true && pageGroup != null && pageGroup.Success) { pagePath = pgNameGrp.Value + "/" + pageGroup.Value; } switch (idType) { case "articleview": case "id": msg = "Identified as old-style news article"; //article if (pageGroup != null && pageGroup.Success) { furlKey = "p" + pageGroup.Value; pagePath = null; //taking care of page separately } else { int articleId = -1; //only for items that are in the range of allowed article ids if (int.TryParse(id, out articleId)) { if (articleId >= this.StartingArticleId) { furlKey = "a" + id; } } } break; case "categoryview": msg = "Identified as old-style news category"; furlKey = "c" + id; break; case "archiveview": //get the mm and yyyy msg = "Identified as old-style news archive"; Group yyyyGrp = oldNewsMatch.Groups["yyyy"]; if (yyyyGrp != null && yyyyGrp.Success) { string yyyy = yyyyGrp.Value; string mm = null; Group mmGrp = oldNewsMatch.Groups["mm"]; if (mmGrp != null && mmGrp.Success) { mm = mmGrp.Value; } friendlyUrl = yyyy; if (mm != null) { friendlyUrl += "/" + mm; } } break; case "authorview": msg = "Identified as old-style news author"; furlKey = "u" + id; break; } if (furlKey != null) { //now lookup the friendly url index TabUrlOptions urlOptions = GetTabUrlOptions(tabId); Hashtable friendlyUrlIndex = UrlController.GetFriendlyUrlIndex(tabId, portalid, this, options, urlOptions); if (friendlyUrlIndex != null && friendlyUrlIndex.ContainsKey(furlKey)) { //look up the index for the item if we don't already have a friendly Url friendlyUrl = (string)friendlyUrlIndex[furlKey]; } } if (friendlyUrl != null) { //now merge with the friendly url for the selected page DotNetNuke.Entities.Portals.PortalAliasInfo alias = DotNetNuke.Entities.Portals.PortalAliasController.Instance.GetPortalAlias(httpAlias); DotNetNuke.Entities.Portals.PortalSettings ps = new DotNetNuke.Entities.Portals.PortalSettings(tabId, alias); if (pagePath != null) { friendlyUrl += this.EnsureLeadingChar("/", pagePath); } string baseUrl = ""; if (_noDnnPagePathTabId == tabId) { baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + httpAlias + this.EnsureLeadingChar("/", friendlyUrl) + options.PageExtension;//put onto http Alias with no page path } else { baseUrl = DotNetNuke.Common.Globals.NavigateURL(tabId, ps, "", friendlyUrl); //add on with page path } if (baseUrl != null) { redirectLocation = baseUrl; doRedirect = true; msg += ", found friendly url " + friendlyUrl + ", redirecting"; messages.Add(msg); } } } } return(doRedirect); }
public virtual void ProcessRequest(System.Web.HttpContext context) { try { if (HttpContext.Current.Items["PortalSettings"] != null) { _ps = (DotNetNuke.Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]); _pid = _ps.PortalId; } else { string DomainName = null; DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null; string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalAliasController.Instance.GetPortalAlias(HttpContext.Current.Request.Url.Host); _pid = objPortalAliasInfo.PortalID; _ps = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); } //Dim sc As New Social.SocialSettings //_mainSettings = sc.LoadSettings[_ps.PortalId] _mainSettings = DataCache.MainSettings(ModuleId); // If context.Request.IsAuthenticated Then _isValid = true; if (AdminRequired & !context.Request.IsAuthenticated) { _isValid = false; return; } if (AdminRequired && context.Request.IsAuthenticated) { //_isValid = DotNetNuke.Security.PortalSecurity.IsInRole(_ps.AdministratorRoleName) DotNetNuke.Entities.Modules.ModuleController objMC = new DotNetNuke.Entities.Modules.ModuleController(); DotNetNuke.Entities.Modules.ModuleInfo objM = objMC.GetModule(ModuleId, TabId); string roleIds = Permissions.GetRoleIds(objM.ModulePermissions.ToString("EDIT").Split(';'), PortalId); _isValid = Modules.ActiveForums.Permissions.HasAccess(roleIds, ForumUser.UserRoles); } else if (AdminRequired & !context.Request.IsAuthenticated) { _isValid = false; return; } string p = HttpContext.Current.Request.Params["p"]; if (!(string.IsNullOrEmpty(p))) { _params = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(p); } if (context.Request.Files.Count == 0) { string jsonPost = string.Empty; string prop = string.Empty; bool propComplete = true; string val = string.Empty; string tmp = string.Empty; bool bObj = false; //Arrays List <string> slist = null; //Dim pairs As NameValueCollection = Nothing Hashtable pairs = null; Hashtable subPairs = null; Hashtable ht = new Hashtable(); int idx = 0; string parentProp = string.Empty; string skip = "{}[]:," + ((char)(34)).ToString(); using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8)) { while (!(sr.EndOfStream)) { char c = (char)(sr.Read()); if (idx > 0 && c == '[') { c = (char)(sr.Read()); bObj = true; } if (idx > 0 && c == '{') { if (pairs == null) { parentProp = prop; prop = string.Empty; tmp = string.Empty; //pairs = New NameValueCollection pairs = new Hashtable(); } else if (subPairs == null) { string subString = c.ToString(); while (c != '}') { c = (char)(sr.Read()); subString += c; if (c == '}') { break; } } subPairs = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(subString); pairs.Add(prop, subPairs); prop = string.Empty; tmp = string.Empty; subPairs = null; c = (char)(sr.Read()); } } if (idx > 0 && bObj == true && !(c == '{')) { string subItem = string.Empty; while (c != ']') { if (slist == null) { slist = new List <string>(); } if (skip.IndexOf(c) == -1) { subItem += c; } c = (char)(sr.Read()); if (c == ',' || c == ']') { slist.Add(subItem); subItem = string.Empty; } if (c == ']') { c = (char)(sr.Read()); bObj = false; break; } } } if (c == ':') { prop = tmp; tmp = string.Empty; } if (skip.IndexOf(c) == -1) { tmp += c; } if (c == ',' || c == '}') { if (!(string.IsNullOrEmpty(tmp))) { tmp = HttpUtility.UrlDecode(tmp); } if (slist != null) { ht.Add(prop, slist); slist = null; } else if (pairs != null && c == ',' && !(string.IsNullOrEmpty(prop))) { pairs.Add(prop, tmp); } else if (pairs != null && c == '}') { if (!(string.IsNullOrEmpty(tmp))) { pairs.Add(prop, tmp); } ht.Add(parentProp, pairs); parentProp = string.Empty; pairs = null; } else if (!(string.IsNullOrEmpty(prop))) { ht.Add(prop, tmp); } prop = string.Empty; tmp = string.Empty; } idx += 1; } if (pairs != null & !(string.IsNullOrEmpty(parentProp))) { ht.Add(parentProp, pairs); } else if (!(string.IsNullOrEmpty(prop)) && !(string.IsNullOrEmpty(tmp))) { ht.Add(prop, HttpUtility.UrlDecode(tmp)); } else if (!(string.IsNullOrEmpty(prop)) && slist != null) { ht.Add(prop, slist); } //jsonPost = sr.ReadToEnd() sr.Close(); } _params = ht; //End If } else { Hashtable ht = new Hashtable(); foreach (string s in context.Request.Params.AllKeys) { if (!(ht.ContainsKey(s))) { ht.Add(s, context.Request.Params[s]); } } _params = ht; } if (HttpContext.Current.Request.IsAuthenticated) { UserId = UserController.GetUserIdByUserName(PortalId, HttpContext.Current.User.Identity.Name); } else { UserId = -1; } } catch (Exception ex) { _isValid = false; Exceptions.LogException(ex); } }
protected override void OnLoad(EventArgs e) { if (Request.QueryString["noSAML"] != null) { } else { base.OnLoad(e); staticPortalSettings = PortalSettings; string redirectTo = "~/"; try { config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId); if (Request.HttpMethod == "POST" && !Request.IsAuthenticated) { //specify the certificate that your SAML provider has given to you string samlCertificate = config.TheirCert; Saml.Response samlResponse = new Saml.Response(samlCertificate); LogToEventLog("Request:", Request.Form["SAMLResponse"].ToString()); samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]); //SAML providers usually POST the data into this var //String xmlExample = ""; //samlResponse.LoadXml(xmlExample); LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is: ", samlResponse.ToString())); if (samlResponse.IsValid()) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml valid"); LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is: {0}", samlResponse.Xml.ToString())); //WOOHOO!!! user is logged in //YAY! //Obtain optional items string username = "", email = "", firstname = "", lastname = "", displayname = ""; var rolesList = new List <string>(); var requiredRolesList = new List <string>(); try { username = samlResponse.GetNameID(); if (username == null) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS NULL"); } else { if (username == "") { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS EMPTY"); } } LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Username is: {0} ", username)); email = samlResponse.GetUserProperty(config.usrEmail); if (email == null) { email = samlResponse.GetUserProperty("email"); } firstname = samlResponse.GetUserProperty(config.usrFirstName); if (firstname == null) { firstname = samlResponse.GetUserProperty("firstName"); } lastname = samlResponse.GetUserProperty(config.usrLastName); if (lastname == null) { lastname = samlResponse.GetUserProperty("lastName"); } displayname = samlResponse.GetUserProperty(config.usrDisplayName); if (displayname == null) { displayname = samlResponse.GetUserProperty("displayName"); } var roles = samlResponse.GetUserProperty(config.RoleAttribute); if (!string.IsNullOrWhiteSpace(roles)) { rolesList = roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } var requiredRoles = samlResponse.GetUserProperty(config.RequiredRoles); if (!string.IsNullOrWhiteSpace(requiredRoles)) { requiredRolesList = requiredRoles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } } catch (Exception ex) { //insert error handling code //no, really, please do LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception:......{0}", ex.InnerException.Message)); } UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, username); if (userInfo == null) { //user does not exists, it needs to be created. userInfo = new UserInfo(); try { if (username != null && email != null && firstname != null && lastname != null) { if (displayname == null) { userInfo.DisplayName = firstname + " " + lastname; } else { userInfo.DisplayName = displayname; } userInfo.FirstName = firstname; userInfo.LastName = lastname; userInfo.Username = username; userInfo.Email = email; userInfo.PortalID = PortalSettings.PortalId; userInfo.IsSuperUser = false; userInfo.Membership.Password = UserController.GeneratePassword(); var usrCreateStatus = new UserCreateStatus(); usrCreateStatus = UserController.CreateUser(ref userInfo); if (usrCreateStatus == UserCreateStatus.Success) { UserInfo usrInfo = UserController.GetUserByName(PortalSettings.PortalId, username); SetProfileProperties(samlResponse, usrInfo); //Add roles if needed, since a new user no need to remove roles or process that condition if (rolesList.Any()) { AssignRolesFromList(usrInfo, rolesList); } } else { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user..." + usrCreateStatus.ToString()); } } } catch (Exception ex) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user...exception: " + ex.InnerException.Message); } } else { //User already exists //Wen unlock it if necessary if (userInfo.Membership.LockedOut) { UserController.UnLockUser(userInfo); } LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username)); try { //We update the user's info userInfo.DisplayName = displayname; userInfo.FirstName = firstname; userInfo.LastName = lastname; userInfo.Email = email; UserController.UpdateUser(PortalSettings.PortalId, userInfo); //We update the user's properties SetProfileProperties(samlResponse, userInfo); //Ensure roles if neeeded if (rolesList.Any()) { AssignRolesFromList(userInfo, rolesList); } //If we have a required role list, remove any of those items that were not in the SAML attribute if (requiredRolesList.Any()) { var toRemove = requiredRolesList.Where(req => !rolesList.Contains(req)) .ToList(); RemoveRolesFromList(userInfo, toRemove); } } catch (Exception ex) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error updating existing user...exception: " + ex.InnerException.Message); } } UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true); UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE; if (loginStatus == UserLoginStatus.LOGIN_SUCCESS) { SetLoginDate(username); //Raise UserAuthenticated Event var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one. How did it get named SAML???? { Authenticated = true, Message = "User authorized", RememberMe = false }; OnUserAuthenticated(eventArgs); } } else { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml not valid"); } } else if (Request.IsAuthenticated) { //Do Nothing if the request is authenticated } else { XmlDocument request = GenerateSAMLRequest(); //X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName); //request = StaticHelper.SignSAMLRequest(request, cert); LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml)); String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request); redirectTo = config.IdPURL + (config.IdPURL.Contains("?") ? "&" : "?") + "SAMLRequest=" + convertedRequestXML; if (Request.QueryString.Count > 0) { redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&")); } Response.Redirect(Page.ResolveUrl(redirectTo), false); } } catch (System.Threading.ThreadAbortException tae) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception is {0}", tae.Message)); //Response.Redirect(Page.ResolveUrl(redirectTo), false); } catch (Exception ex) { LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception {0}", ex.Message)); //redirectTo = "~/"; } //Response.Redirect(Page.ResolveUrl(redirectTo), false); } }
public virtual void ProcessRequest(System.Web.HttpContext context) { try { if (HttpContext.Current.Items["PortalSettings"] != null) { _ps = (DotNetNuke.Entities.Portals.PortalSettings)(HttpContext.Current.Items["PortalSettings"]); _pid = _ps.PortalId; } else { string DomainName = null; DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null; string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); objPortalAliasInfo = DotNetNuke.Entities.Portals.PortalSettings.GetPortalAliasInfo(HttpContext.Current.Request.Url.Host); _pid = objPortalAliasInfo.PortalID; _ps = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); } //Dim sc As New Social.SocialSettings //_mainSettings = sc.LoadSettings[_ps.PortalId] _mainSettings = DataCache.MainSettings(ModuleId); // If context.Request.IsAuthenticated Then _isValid = true; if (AdminRequired & ! context.Request.IsAuthenticated) { _isValid = false; return; } if (AdminRequired && context.Request.IsAuthenticated) { //_isValid = DotNetNuke.Security.PortalSecurity.IsInRole(_ps.AdministratorRoleName) DotNetNuke.Entities.Modules.ModuleController objMC = new DotNetNuke.Entities.Modules.ModuleController(); DotNetNuke.Entities.Modules.ModuleInfo objM = objMC.GetModule(ModuleId, TabId); string roleIds = Permissions.GetRoleIds(objM.AuthorizedEditRoles.Split(';'), PortalId); _isValid = Modules.ActiveForums.Permissions.HasAccess(roleIds, ForumUser.UserRoles); } else if (AdminRequired & ! context.Request.IsAuthenticated) { _isValid = false; return; } string p = HttpContext.Current.Request.Params["p"]; if (! (string.IsNullOrEmpty(p))) { _params = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(p); } if (context.Request.Files.Count == 0) { string jsonPost = string.Empty; string prop = string.Empty; bool propComplete = true; string val = string.Empty; string tmp = string.Empty; bool bObj = false; //Arrays List<string> slist = null; //Dim pairs As NameValueCollection = Nothing Hashtable pairs = null; Hashtable subPairs = null; Hashtable ht = new Hashtable(); int idx = 0; string parentProp = string.Empty; string skip = "{}[]:," + ((char)(34)).ToString(); using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8)) { while ( ! (sr.EndOfStream)) { char c = (char)(sr.Read()); if (idx > 0 && c == '[') { c = (char)(sr.Read()); bObj = true; } if (idx > 0 && c == '{') { if (pairs == null) { parentProp = prop; prop = string.Empty; tmp = string.Empty; //pairs = New NameValueCollection pairs = new Hashtable(); } else if (subPairs == null) { string subString = c.ToString(); while ( c != '}') { c = (char)(sr.Read()); subString += c; if (c == '}') { break; } } subPairs = Utilities.JSON.ConvertFromJSONAssoicativeArrayToHashTable(subString); pairs.Add(prop, subPairs); prop = string.Empty; tmp = string.Empty; subPairs = null; c = (char)(sr.Read()); } } if (idx > 0 && bObj == true && ! (c == '{')) { string subItem = string.Empty; while ( c != ']') { if (slist == null) { slist = new List<string>(); } if (skip.IndexOf(c) == -1) { subItem += c; } c = (char)(sr.Read()); if (c == ',' || c == ']') { slist.Add(subItem); subItem = string.Empty; } if (c == ']') { c = (char)(sr.Read()); bObj = false; break; } } } if (c == ':') { prop = tmp; tmp = string.Empty; } if (skip.IndexOf(c) == -1) { tmp += c; } if (c == ',' || c == '}') { if (! (string.IsNullOrEmpty(tmp))) { tmp = HttpUtility.UrlDecode(tmp); } if (slist != null) { ht.Add(prop, slist); slist = null; } else if (pairs != null && c == ',' && ! (string.IsNullOrEmpty(prop))) { pairs.Add(prop, tmp); } else if (pairs != null && c == '}') { if (! (string.IsNullOrEmpty(tmp))) { pairs.Add(prop, tmp); } ht.Add(parentProp, pairs); parentProp = string.Empty; pairs = null; } else if (! (string.IsNullOrEmpty(prop))) { ht.Add(prop, tmp); } prop = string.Empty; tmp = string.Empty; } idx += 1; } if (pairs != null & ! (string.IsNullOrEmpty(parentProp))) { ht.Add(parentProp, pairs); } else if (! (string.IsNullOrEmpty(prop)) && ! (string.IsNullOrEmpty(tmp))) { ht.Add(prop, HttpUtility.UrlDecode(tmp)); } else if (! (string.IsNullOrEmpty(prop)) && slist != null) { ht.Add(prop, slist); } //jsonPost = sr.ReadToEnd() sr.Close(); } _params = ht; //End If } else { Hashtable ht = new Hashtable(); foreach (string s in context.Request.Params.AllKeys) { if (! (ht.ContainsKey(s))) { ht.Add(s, context.Request.Params[s]); } } _params = ht; } if (HttpContext.Current.Request.IsAuthenticated) { UserId = UserController.GetUserIdByUserName(PortalId, HttpContext.Current.User.Identity.Name); } else { UserId = -1; } } catch (Exception ex) { _isValid = false; Exceptions.LogException(ex); } }
// Customization - token replacement #region ReplaceTicketToken public static string ReplaceTicketToken(string strBody, string strPasswordLinkUrl, ITILServiceDesk_Task objITILServiceDesk_Tasks) { DotNetNuke.Entities.Portals.PortalSettings objPortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); //TaskID if (strBody.Contains("[TaskID]")) { strBody = strBody.Replace("[TaskID]", objITILServiceDesk_Tasks.TaskID.ToString()); } //PasswordLinkUrl if (strBody.Contains("[PasswordLinkUrl]")) { strBody = strBody.Replace("[PasswordLinkUrl]", strPasswordLinkUrl); } //Description if (strBody.Contains("[Description]")) { strBody = strBody.Replace("[Description]", objITILServiceDesk_Tasks.Description); } //Details if (strBody.Contains("[Details]")) { strBody = strBody.Replace("[Details]", GetDetailsOfTicket(objITILServiceDesk_Tasks.TaskID)); } //Comments if (strBody.Contains("[Comments]")) { strBody = strBody.Replace("[Comments]", GetCommentsOfTicket(objITILServiceDesk_Tasks.TaskID)); } //Requestor if (strBody.Contains("[Requestor]")) { strBody = strBody.Replace("[Requestor]", objITILServiceDesk_Tasks.RequesterName); } //Priority Name if (strBody.Contains("[PriorityName]")) { strBody = strBody.Replace("[PriorityName]", objITILServiceDesk_Tasks.Priority); } //Email if (strBody.Contains("[Email]")) { strBody = strBody.Replace("[Email]", GetEmailOfRequestor(objITILServiceDesk_Tasks.RequesterUserID, objITILServiceDesk_Tasks.RequesterEmail)); } //CreatedDate if (strBody.Contains("[CreatedDate]")) { strBody = strBody.Replace("[CreatedDate]", objITILServiceDesk_Tasks.CreatedDate.ToShortDateString()); } //DueDate if (strBody.Contains("[DueDate]")) { if (objITILServiceDesk_Tasks.DueDate.HasValue) { strBody = strBody.Replace("[DueDate]", objITILServiceDesk_Tasks.DueDate.Value.ToShortDateString()); } else { strBody = strBody.Replace("[DueDate]", string.Empty); } } //Phone if (strBody.Contains("[Phone]")) { strBody = strBody.Replace("[Phone]", objITILServiceDesk_Tasks.RequesterPhone); } //Assigned if (strBody.Contains("[Assigned]")) { strBody = strBody.Replace("[Assigned]", GetGetAssignedRoleName(objITILServiceDesk_Tasks.AssignedRoleID)); } //StatusName if (strBody.Contains("[StatusName]")) { strBody = strBody.Replace("[StatusName]", objITILServiceDesk_Tasks.Status); } //StartDate if (strBody.Contains("[StartDate]")) { if (objITILServiceDesk_Tasks.EstimatedStart.HasValue) { strBody = strBody.Replace("[StartDate]", objITILServiceDesk_Tasks.EstimatedStart.Value.ToShortDateString()); } else //blank out token { strBody = strBody.Replace("[StartDate]", string.Empty); } } //EstimatedHours if (strBody.Contains("[EstimatedHours]")) { if (objITILServiceDesk_Tasks.EstimatedHours.HasValue) { strBody = strBody.Replace("[EstimatedHours]", objITILServiceDesk_Tasks.EstimatedHours.Value.ToString()); } else //blank out token { strBody = strBody.Replace("[EstimatedHours]", string.Empty); } } //CompleteDate if (strBody.Contains("[CompleteDate]")) { if (objITILServiceDesk_Tasks.EstimatedCompletion.HasValue) { strBody = strBody.Replace("[CompleteDate]", objITILServiceDesk_Tasks.EstimatedCompletion.Value.ToShortDateString()); } else //blank out token { strBody = strBody.Replace("[CompleteDate]", string.Empty); } } return(strBody); }
public override void Init(string[] args, DotNetNuke.Entities.Portals.PortalSettings portalSettings, DotNetNuke.Entities.Users.UserInfo userInfo, int activeTabId) { base.Init(args, portalSettings, userInfo, activeTabId); PersonName = GetFlagValue(FlagPersonName, "FlagPersonName", "", true, true); }
private void DisplayItem(Item item) { //check if item.URL is populated, if so figure out where to redirect. if (Utility.HasValue(item.Url)) { //do our redirect now Response.Status = "301 Moved Permanently"; Response.RedirectLocation = item.GetItemExternalUrl; } else { int defaultTabId = -1; object o = HostController.Instance.GetString(Utility.PublishDefaultDisplayPage + item.PortalId); if (o != null && Utility.HasValue(o.ToString())) { defaultTabId = Convert.ToInt32(o, CultureInfo.InvariantCulture); } //build language parameter string friendlyLanguageValue = string.Empty; string languageValue = string.Empty; if (!string.IsNullOrEmpty(_language)) { languageValue = "&language=" + _language; friendlyLanguageValue = "/language/" + _language + "/"; } if (item != null) { if (item.IsLinkable()) { if (HostController.Instance.GetString("UseFriendlyUrls") == "Y" && ModuleBase.EnablePublishFriendlyUrlsForPortal(item.PortalId)) { string pageName = item.Name.Trim(); if (pageName.Length > 50) { pageName = item.Name.Substring(0, 50); } pageName = Utility.OnlyAlphanumericCharacters(pageName); //Global.asax Application_BeginRequest checks for these values and will try to redirect to the non-existent page if (pageName.EndsWith("install", StringComparison.CurrentCultureIgnoreCase) || pageName.EndsWith("installwizard", StringComparison.CurrentCultureIgnoreCase)) { pageName = pageName.Substring(0, pageName.Length - 1); } pageName = pageName + ".aspx"; DotNetNuke.Entities.Portals.PortalSettings ps = Utility.GetPortalSettings(item.PortalId); var tc = new TabController(); TabInfo ti; //if the setting to "force display on this page" is set, be sure to send them there. if (item.ForceDisplayOnPage()) { ti = tc.GetTab(item.DisplayTabId, item.PortalId, false); if (ti.IsDeleted) { if (defaultTabId > 0) { ti = tc.GetTab(defaultTabId, item.PortalId, false); } } Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.FriendlyUrl(ti, "/tabid/" + ti.TabID.ToString(CultureInfo.InvariantCulture) + "/itemid/" + item.ItemId.ToString(CultureInfo.InvariantCulture) + UsePageId(true), pageName, ps); } else if (_tabid > 0 && item.DisplayOnCurrentPage()) { ti = tc.GetTab(_tabid, item.PortalId, false); if (ti.IsDeleted) { ti = tc.GetTab(defaultTabId, item.PortalId, false); } //check if there is a ModuleID passed in the querystring, if so then send it in the querystring as well if (_modid > 0) { Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.FriendlyUrl(ti, "/tabid/" + ti.TabID.ToString(CultureInfo.InvariantCulture) + "/itemid/" + item.ItemId.ToString(CultureInfo.InvariantCulture) + "/modid/" + _modid.ToString(CultureInfo.InvariantCulture) + UsePageId(true) + friendlyLanguageValue, pageName, ps); } else { Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.FriendlyUrl(ti, "/tabid/" + ti.TabID.ToString(CultureInfo.InvariantCulture) + "/itemid/" + item.ItemId.ToString(CultureInfo.InvariantCulture) + UsePageId(true) + friendlyLanguageValue, pageName, ps); } } else { ti = tc.GetTab(item.DisplayTabId, item.PortalId, false); if (ti.IsDeleted) { ti = tc.GetTab(defaultTabId, item.PortalId, false); } Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.FriendlyUrl(ti, "/tabid/" + ti.TabID.ToString(CultureInfo.InvariantCulture) + "/itemid/" + item.ItemId.ToString(CultureInfo.InvariantCulture) + UsePageId(true) + friendlyLanguageValue, pageName, ps); } } else { //we need to check for ForceOnCurrentPage var tc = new TabController(); TabInfo ti; DotNetNuke.Entities.Portals.PortalSettings ps = Utility.GetPortalSettings(item.PortalId); //if we are passing in a TabId use it if (item.ForceDisplayOnPage()) { ti = tc.GetTab(item.DisplayTabId, item.PortalId, false); Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(ti.TabID, ps, "", "itemid=" + item.ItemId.ToString(CultureInfo.InvariantCulture) + UsePageId(false) + languageValue); } if (_tabid > 0) { if (_modid > 0) { Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(_tabid, ps, "", "itemid=" + item.ItemId.ToString(CultureInfo.InvariantCulture) + "&modid=" + _modid.ToString(CultureInfo.InvariantCulture) + UsePageId(false) + languageValue); } else { Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(_tabid, ps, "", "itemid=" + item.ItemId + UsePageId(false) + languageValue); } } Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(item.DisplayTabId, ps, "", "itemid=" + item.ItemId + UsePageId(false) + languageValue); } } else { //display on the current page or send them elsewhere. //display broken link information //DisplayBrokenLinkMessage(item); if (defaultTabId > -1) { //send them to the Default Display Page Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(defaultTabId, PortalSettings, "", "itemid=" + item.ItemId.ToString(CultureInfo.InvariantCulture) + UsePageId(false) + languageValue); } else { DisplayBrokenLinkMessage(item); } } } else { Response.Status = "301 Moved Permanently"; Response.RedirectLocation = DotNetNuke.Common.Globals.NavigateURL(); } } }
public void Configuration(IAppBuilder app) { try { #region "SSL settings" // Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1) ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11; // Add TLS 1.2 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; #endregion Auth0ConfigBase config = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, Helpers.FirstPortalID); System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.Security.Claims.ClaimTypes.NameIdentifier; // Configure Auth0 parameters string auth0Domain = config.Domain; string auth0ClientId = config.ClientID; // Enable the Cookie saver middleware to work around a bug in the OWIN implementation app.UseKentorOwinCookieSaver(); // Set Cookies as default authentication type app.SetDefaultSignInAsAuthenticationType(Constants.AUTH_TYPE); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = Constants.AUTH_TYPE, CookieName = Constants.AUTH_COOKIE_NAME, }); // Configure Auth0 authentication app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { AuthenticationType = Constants.AUTH_TYPE, Authority = $"https://{auth0Domain}", ClientId = auth0ClientId, Scope = "openid profile email", ResponseType = OpenIdConnectResponseType.CodeIdToken, TokenValidationParameters = new TokenValidationParameters { NameClaimType = System.Security.Claims.ClaimTypes.NameIdentifier }, Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = notification => { DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (notification.OwinContext.Environment["System.Web.HttpContextBase"] != null && notification.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper context = notification.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (context.Items["PortalSettings"] != null && context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { logger.Debug("Can't obtain DNN settings, login process terminated!!"); } #endregion #region "Set Auth0 coordinates according to the current DNN portal" if (_portalSettings != null && notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.Logout) { notification.Options.Authority = $"https://{_providerConfig.Domain}"; notification.Options.ClientId = _providerConfig.ClientID; notification.Options.ClientSecret = _providerConfig.ClientSecret; notification.Options.RedirectUri = _providerConfig.RedirectUri; notification.Options.CallbackPath = Microsoft.Owin.PathString.FromUriComponent("/Default.aspx"); notification.ProtocolMessage.ClientId = _providerConfig.ClientID; notification.ProtocolMessage.ClientSecret = _providerConfig.ClientSecret; notification.ProtocolMessage.RedirectUri = _providerConfig.RedirectUri; } #endregion #region "Log-off code snippet" else if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) { var logoutUri = $"https://{_providerConfig.Domain}/v2/logout?client_id={_providerConfig.ClientID}"; var postLogoutUri = _providerConfig.PostLogoutRedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = notification.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } notification.Response.Redirect(logoutUri); notification.HandleResponse(); } #endregion #region "Output some diagnistic info" if (_providerConfig != null && _providerConfig.IsDiagnosticModeEnabled) { logger.Debug(string.Format("Redirecting to '{0}' using following coordinates:", notification.Options.Authority)); logger.Debug("Client id: " + notification.Options.ClientId); logger.Debug("Redirect uri: " + notification.Options.RedirectUri); logger.Debug("Callback path: " + notification.Options.CallbackPath); } #endregion return(Task.FromResult(0)); }, AuthorizationCodeReceived = async context => { DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (context.OwinContext.Environment["System.Web.HttpContextBase"] != null && context.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper _context = context.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (_context.Items["PortalSettings"] != null && _context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = _context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { throw new ArgumentNullException("Can't obtain DNN settings, login process terminated!!"); } #endregion GS.Auth0.Components.UserController userController = new GS.Auth0.Components.UserController(); //get or create DNN user DotNetNuke.Entities.Users.UserInfo _userInfo = userController.User_Create(context.AuthenticationTicket.Identity.Name, _portalSettings, _providerConfig.IsDiagnosticModeEnabled); if (_userInfo != null) { //update DNN user profile userController.User_Update( _userInfo, context.AuthenticationTicket.Identity?.FindFirst(c => c.Type == "nickname")?.Value, context.AuthenticationTicket.Identity?.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value, _portalSettings.PortalId, _providerConfig.IsDiagnosticModeEnabled); DotNetNuke.Security.Membership.UserLoginStatus loginStatus = DotNetNuke.Security.Membership.UserLoginStatus.LOGIN_FAILURE; UserInfo objUserInfo = DotNetNuke.Entities.Users.UserController.ValidateUser(_portalSettings.PortalId, context.AuthenticationTicket.Identity.Name, "", Constants.PROVIDER_NAME, "", _portalSettings.PortalName, "", ref loginStatus); //set type of current authentication provider DotNetNuke.Services.Authentication.AuthenticationController.SetAuthenticationType(Constants.AUTH_TYPE); DotNetNuke.Entities.Users.UserController.UserLogin(_portalSettings.PortalId, _userInfo, _portalSettings.PortalName, context.OwinContext.Request.RemoteIpAddress, false); } else { throw new ArgumentNullException(string.Format("Can't create or get user '{0}' from DNN.", context.AuthenticationTicket.Identity.Name)); } await Task.FromResult(0); }, AuthenticationFailed = (context) => { //get the error message and send it to the DNN login page DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (context.OwinContext.Environment["System.Web.HttpContextBase"] != null && context.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper _context = context.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (_context.Items["PortalSettings"] != null && _context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = _context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { logger.Error("Can't obtain DNN settings from 'AuthenticationFailed' event, login process terminated!!"); } #endregion if (_providerConfig.IsDiagnosticModeEnabled) { logger.Error(string.Format("OIDC authentication failed, details: {0}", context.Exception)); } string redirectUrl = DotNetNuke.Common.Globals.NavigateURL(_portalSettings.LoginTabId, "Login", new string[] { Constants.ALERT_QUERY_STRING + "=" + context.Exception.Message }); context.Response.Redirect(redirectUrl); context.HandleResponse(); return(Task.FromResult(0)); }, #region "Rest of 'Notification' methods, not in use for now." //SecurityTokenValidated = notification => //{ // return Task.FromResult(0); //}, //MessageReceived = (context) => //{ // return Task.FromResult(0); //}, #endregion }, }); } catch (Exception ex) { logger.Error(ex); } }
protected void Save_OnClick(object sender, EventArgs e) { try { if (FolderList.Items.Count == 0) { return; } DotNetNuke.Entities.Portals.PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalSettings.Current; string fileContents = htmlText2.Text.Trim(); string newFileName = FileName.Text; if (!(newFileName.EndsWith(".html"))) { newFileName = newFileName + ".html"; } string rootFolder = portalSettings.HomeDirectoryMapPath; string dbFolderPath = FolderList.SelectedValue; string virtualFolder = (string)(string)FileSystemValidation.ToVirtualPath(dbFolderPath); rootFolder = rootFolder + FolderList.SelectedValue; rootFolder = rootFolder.Replace("/", "\\"); string errorMessage = string.Empty; FolderController folderCtrl = new FolderController(); FolderInfo folder = folderCtrl.GetFolder(portalSettings.PortalId, dbFolderPath, false); if ((folder == null)) { ShowSaveTemplateMessage(GetString("msgFolderDoesNotExist.Text")); return; } // Check file name is valid FileSystemValidation dnnValidator = new FileSystemValidation(); errorMessage = dnnValidator.OnCreateFile(virtualFolder + newFileName, fileContents.Length); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } FileController fileCtrl = new FileController(); DotNetNuke.Services.FileSystem.FileInfo existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); // error if file exists if (!Overwrite.Checked && existingFile != null) { ShowSaveTemplateMessage(GetString("msgFileExists.Text")); return; } FileInfo newFile = existingFile; if ((newFile == null)) { newFile = new FileInfo(); } newFile.FileName = newFileName; newFile.ContentType = "text/plain"; newFile.Extension = "html"; newFile.Size = fileContents.Length; newFile.FolderId = folder.FolderID; errorMessage = FileSystemUtils.CreateFileFromString(rootFolder, newFile.FileName, fileContents, newFile.ContentType, string.Empty, false); if (!(string.IsNullOrEmpty(errorMessage))) { ShowSaveTemplateMessage(errorMessage); return; } existingFile = fileCtrl.GetFile(newFileName, portalSettings.PortalId, folder.FolderID); if (newFile.FileId != existingFile.FileId) { newFile.FileId = existingFile.FileId; } if (newFile.FileId != Null.NullInteger) { fileCtrl.UpdateFile(newFile.FileId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID); } else { fileCtrl.AddFile(portalSettings.PortalId, newFile.FileName, newFile.Extension, newFile.Size, newFile.Width, newFile.Height, newFile.ContentType, folder.FolderPath, folder.FolderID, true); } ShowSaveTemplateMessage(string.Empty); } catch (Exception ex) { DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); throw ex; } }
public static string SendSystemEmail(UserInfo user, DotNetNuke.Services.Mail.MessageType msgType, DotNetNuke.Entities.Portals.PortalSettings ps) { string msg = string.Empty; try { msg = DotNetNuke.Services.Mail.Mail.SendMail(user, msgType, ps); } catch (Exception ex) { // On some systems, if DNN has sent an email and the SMTP connection is still open, // no other email can be sent until that connection times out. When that happens a transport error is thrown // but it seems to close the connection at that point. So, retrying after the exception always (in my tests) // results in the email being sent on the 2nd go-round. // try again. try { msg = DotNetNuke.Services.Mail.Mail.SendMail(user, msgType, ps); } catch (Exception ex2) { Exceptions.LogException(ex2); } } return(msg); }
private string BuildRSS(int PortalId, int TabId, int ModuleId, int intPosts, int ForumID, bool IngnoreSecurity, bool IncludeBody) { DotNetNuke.Entities.Portals.PortalController pc = new DotNetNuke.Entities.Portals.PortalController(); DotNetNuke.Entities.Portals.PortalSettings ps = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings(); DotNetNuke.Entities.Users.UserInfo ou = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo(); UserController uc = new UserController(); User u = uc.GetUser(PortalId, ModuleId); DataSet ds = DataProvider.Instance().UI_TopicsView(PortalId, ModuleId, ForumID, ou.UserID, 0, 20, ou.IsSuperUser, SortColumns.ReplyCreated); if (ds.Tables.Count > 0) { offSet = Convert.ToInt32(ps.TimeZone.BaseUtcOffset.TotalMinutes); if (ds.Tables[0].Rows.Count == 0) { return(string.Empty); } drForum = ds.Tables[0].Rows[0]; drSecurity = ds.Tables[1].Rows[0]; dtTopics = ds.Tables[3]; if (dtTopics.Rows.Count == 0) { return(string.Empty); } bView = Permissions.HasPerm(drSecurity["CanView"].ToString(), u.UserRoles); bRead = Permissions.HasPerm(drSecurity["CanRead"].ToString(), u.UserRoles); StringBuilder sb = new StringBuilder(1024); if (bRead) { ForumName = drForum["ForumName"].ToString(); GroupName = drForum["GroupName"].ToString(); ForumDescription = drForum["ForumDesc"].ToString(); //TopicsTemplateId = CInt(drForum("TopicsTemplateId")) bAllowRSS = Convert.ToBoolean(drForum["AllowRSS"]); if (bAllowRSS) { sb.Append("<?xml version=\"1.0\" ?>" + System.Environment.NewLine); sb.Append("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:cf=\"http://www.microsoft.com/schemas/rss/core/2005\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\">" + System.Environment.NewLine); string[] Params = { ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics }; string URL = string.Empty; if (Request.QueryString["asg"] == null) { URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params); } else if (SimulateIsNumeric.IsNumeric(Request.QueryString["asg"])) { Params = new string[] { "asg=" + Request.QueryString["asg"], ParamKeys.ForumId + "=" + ForumID, ParamKeys.ViewType + "=" + Views.Topics }; URL = DotNetNuke.Common.Globals.NavigateURL(TabId, "", Params); } if (URL.IndexOf(Request.Url.Host) == -1) { URL = DotNetNuke.Common.Globals.AddHTTP(Request.Url.Host) + URL; } // build channel sb.Append(WriteElement("channel", 1)); sb.Append(WriteElement("title", HttpUtility.HtmlEncode(ps.PortalName) + " " + ForumName, 2)); sb.Append(WriteElement("link", URL, 2)); sb.Append(WriteElement("description", ForumDescription, 2)); sb.Append(WriteElement("language", PortalSettings.DefaultLanguage, 2)); sb.Append(WriteElement("generator", "ActiveForums 5.0", 2)); sb.Append(WriteElement("copyright", PortalSettings.FooterText, 2)); sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2)); if (!(ps.LogoFile == string.Empty)) { string sLogo = "<image><url>http://" + Request.Url.Host + ps.HomeDirectory + ps.LogoFile + "</url>"; sLogo += "<title>" + ps.PortalName + " " + ForumName + "</title>"; sLogo += "<link>" + URL + "</link></image>"; sb.Append(sLogo); } foreach (DataRow dr in dtTopics.Rows) { if (DotNetNuke.Security.PortalSecurity.IsInRoles(PortalSettings.ActiveTab.TabPermissions.ToString("VIEW"))) { //objModule = objModules.GetModule(ModuleId, TabId) //If DotNetNuke.Security.PortalSecurity.IsInRoles(objModule.AuthorizedViewRoles) = True Then // sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId)) //End If sb.Append(BuildItem(dr, TabId, 2, IncludeBody, PortalId)); } } sb.Append("<atom:link href=\"http://" + Request.Url.Host + HttpUtility.HtmlEncode(Request.RawUrl) + "\" rel=\"self\" type=\"application/rss+xml\" />"); sb.Append(WriteElement("/channel", 1)); sb.Replace("[LASTBUILDDATE]", LastBuildDate.ToString("r")); sb.Append("</rss>"); //Cache.Insert("RSS" & ModuleId & ForumID, sb.ToString, Nothing, DateTime.Now.AddMinutes(dblCacheTimeOut), TimeSpan.Zero) return(sb.ToString()); } } } return(string.Empty); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); staticPortalSettings = PortalSettings; string redirectTo = "~/"; try { config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId); if (Request.HttpMethod == "POST" && !Request.IsAuthenticated) { if (Request.Form["RelayState"] != null) { string relayState = HttpUtility.UrlDecode(Request.Form["RelayState"]); LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", string.Format("relayState : {0}", relayState)); var relayStateSplit = relayState.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in relayStateSplit) { if (s.ToLower().StartsWith("returnurl")) { redirectTo = "~" + s.Replace("returnurl=", ""); break; } } } X509Certificate2 myCert = StaticHelper.GetCert(config.OurCertFriendlyName); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); string responseXML = enc.GetString(Convert.FromBase64String(Request.Form["SAMLResponse"])); ResponseHandler responseHandler = new ResponseHandler(responseXML, myCert, config.TheirCert ); LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", "responseXML : " + responseHandler.ResponseString()); string emailFromSAMLResponse = responseHandler.GetNameID(); UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, emailFromSAMLResponse); if (userInfo == null) { userInfo = new UserInfo(); userInfo.Username = emailFromSAMLResponse; userInfo.PortalID = base.PortalId; userInfo.DisplayName = emailFromSAMLResponse; userInfo.Email = emailFromSAMLResponse; userInfo.FirstName = emailFromSAMLResponse; userInfo.LastName = emailFromSAMLResponse; userInfo.Membership.Password = UserController.GeneratePassword(12).ToString(); UserCreateStatus rc = UserController.CreateUser(ref userInfo); if (rc == UserCreateStatus.Success) { addRoleToUser(userInfo, "Subscribers", DateTime.MaxValue); } } else { LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username)); } string sessionIndexFromSAMLResponse = responseHandler.GetSessionIndex(); Session["sessionIndexFromSAMLResponse"] = sessionIndexFromSAMLResponse; UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true); UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE; if (loginStatus == UserLoginStatus.LOGIN_SUCCESS) { //Raise UserAuthenticated Event var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one. How did it get named SAML???? { Authenticated = true, Message = "User authorized", RememberMe = false }; OnUserAuthenticated(eventArgs); } } else if (Request.IsAuthenticated) { //if (!Response.IsRequestBeingRedirected) // Response.Redirect(Page.ResolveUrl("~/"), false); } else { XmlDocument request = GenerateSAMLRequest(); X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName); request = StaticHelper.SignSAMLRequest(request, cert); LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml)); String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request); redirectTo = config.IdPURL + (config.IdPURL.Contains("?") ? "&" : "?") + "SAMLRequest=" + convertedRequestXML; if (Request.QueryString.Count > 0) { redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&")); } } } catch (System.Threading.ThreadAbortException tae) { LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Redirecting to {0}", redirectTo)); Response.Redirect(Page.ResolveUrl(redirectTo), false); } catch (Exception ex) { LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception {0}", ex.Message)); redirectTo = "~/"; } Response.Redirect(Page.ResolveUrl(redirectTo), false); }