public static void DeleteOAuthLink(int userId) { var clientUserId = GetOAuthClientUserId(userId); try { using (var conn = GetSqlConnection()) { using (var command = new SqlCommand($"[{databaseOwner}].[te_OAuth_RemoveLink]", conn) { CommandType = CommandType.StoredProcedure }) { command.Parameters.Add("@ClientType", SqlDbType.NVarChar).Value = "saml"; command.Parameters.Add("@ClientUserId", SqlDbType.NVarChar).Value = clientUserId; command.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; conn.Open(); command.ExecuteScalar(); } } } catch (Exception ex) { Apis.Get <IEventLog>() .Write($"Could not delete OAuth Link for user {userId}. {ex}", new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6022, EventType = "Error" }); } }
public static string GetTokenData(string tokenKey) { try { using (var conn = GetSqlConnection()) { var sql = $"SELECT EncryptedData FROM [{databaseOwner}].[db_SamlTempTokenData] WHERE TokenKey = @TokenKey"; var command = new SqlCommand(sql, conn) { CommandType = CommandType.Text }; command.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = Guid.Parse(tokenKey); conn.Open(); return((string)command.ExecuteScalar()); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error reading from db_SamlTempTokenData; I dont think its installed. " + ex, new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6022, EventType = "Error" }); return(string.Empty); } }
public static void DeleteTokenData(string tokenKey) { try { using (var conn = GetSqlConnection()) { var sql = $"DELETE FROM [{databaseOwner}].[db_SamlTempTokenData] WHERE TokenKey = @TokenKey"; var command = new SqlCommand(sql, conn) { CommandType = CommandType.Text }; command.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = Guid.Parse(tokenKey); conn.Open(); command.ExecuteNonQuery(); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error deleting from db_SamlTokenData; I dont think its installed. " + ex, new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6024, EventType = "Error" }); } }
public static void SaveEncryptedSamlToken(Guid tokenKey, string encryptedData) { try { using (var conn = GetSqlConnection()) { var sql = $"INSERT INTO [{databaseOwner}].[db_SamlTempTokenData]" + "(TokenKey" + ", EncryptedData)" + "VALUES" + "(@TokenKey" + ",@EncryptedData)"; var myCommand = new SqlCommand(sql, conn) { CommandType = CommandType.Text }; myCommand.Parameters.Add("@TokenKey", SqlDbType.UniqueIdentifier).Value = tokenKey; myCommand.Parameters.Add("@EncryptedData", SqlDbType.NVarChar).Value = encryptedData; conn.Open(); myCommand.ExecuteNonQuery(); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error inserting token into the db_SamlTempTokenData table. " + ex, new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6023, EventType = "Error" }); } }
public static Guid?GetCookieInvitationKey() { try { HttpCookie returnUrlCookie = HttpContext.Current.Request.Cookies[ReturnUrlCookieName]; if (returnUrlCookie != null && returnUrlCookie.Values[InvitationKeyParameterName] != null && !string.IsNullOrEmpty(returnUrlCookie.Values[InvitationKeyParameterName])) { var paresedGuid = Guid.Parse(returnUrlCookie.Values[InvitationKeyParameterName]); if (paresedGuid != Guid.Empty) { return(paresedGuid); } } } catch (Exception ex) { Apis.Get <IEventLog>().Write("ERROR trying to extract Invitation from cookie:" + ex.ToString(), new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6019, EventType = "Error" }); } return(null); }
private void ParseForumContext(PageContext context) { var appKey = context.GetTokenValue("ForumApp"); var forumsApi = Apis.Get <IForums>(); var groupsApi = Apis.Get <IGroups>(); if (appKey != null) { var groupItem = context.ContextItems.GetAllContextItems().FirstOrDefault(a => a.ContentTypeId == groupsApi.ContentTypeId); if (groupItem != null) { /**workaround until **/ var forums = forumsApi.List(new ForumsListOptions { GroupId = int.Parse(groupItem.Id), PageSize = 200 }); var forum = forums.FirstOrDefault(f => f.Url.Contains(appKey.ToString())); // forumsApi.Get(new ForumsGetOptions() { GroupId = int.Parse(groupItem.Id), Key = appKey.ToString() }); if (forum != null) { var contextItem = new ContextItem() { TypeName = "Forum", ApplicationId = forum.ApplicationId, ApplicationTypeId = forumsApi.ApplicationTypeId, ContainerId = forum.Group.ApplicationId, ContainerTypeId = groupsApi.ContentTypeId, ContentId = forum.ApplicationId, ContentTypeId = forumsApi.ApplicationTypeId, Id = forum.Id.ToString() }; context.ContextItems.Put(contextItem); } } } }
private bool IsValidReturnUrl(string returnUrl) { var apiCoreUrls = Apis.Get <ICoreUrls>(); if (!string.IsNullOrEmpty(returnUrl) && !( returnUrl.IndexOf("MessageID") != -1 || returnUrl.IndexOf(apiCoreUrls.Banned()) != -1 || returnUrl.IndexOf(apiCoreUrls.NotFound()) != -1 || returnUrl.IndexOf("changepassword") != -1 || returnUrl.IndexOf("emailforgottenpassword") != -1 || returnUrl.IndexOf("/samlauthn") != -1 || returnUrl.IndexOf("/samlresponse") != -1 || returnUrl.IndexOf("/oauth") != -1 || returnUrl.IndexOf("/login") != -1 || returnUrl.IndexOf("/logout") != -1 || returnUrl.IndexOf("/samllogout") != -1 ) ) { return(true); } return(false); }
public void Initialize() { _usersApi = Apis.Get <IUsers>(); _eventLogApi = Apis.Get <IEventLog>(); SamlEvents.Instance.AfterAuthenticate += Instance_AfterAuthenticate; SamlEvents.Instance.AfterCreate += Instance_AfterCreate; }
public void Initialize() { _userProfileFields = Apis.Get <IUserProfileFields>(); _usersApi = Apis.Get <IUsers>(); _eventLogApi = Apis.Get <IEventLog>(); SamlEvents.Instance.AfterAuthenticate += Instance_AfterAuthenticate; SamlEvents.Instance.AfterCreate += Instance_AfterCreate; _usersApi.Events.BeforeUpdate += Events_BeforeUpdate; }
private void ManageUserRoles(User user, SamlTokenData samlTokenData) { var usersSamlTokenRoles = GetSamlTokenRoles(samlTokenData); Apis.Get <IUsers>().RunAsUser("admin", () => { CreateMissingRoles(usersSamlTokenRoles); AddRemoveUserFromManagedRoles(user, usersSamlTokenRoles); }); }
//private static readonly IEventLog ApiEventLog = Apis.Get<IEventLog>(); #region Helper methods & properties protected static SqlConnection GetSqlConnection() { try { return(Apis.Get <IDatabaseConnections>().GetConnection("SiteSqlServer")); } catch { throw new ArgumentException("SQL Connection String 'SiteSqlServer' is unavailable or invalid."); } }
internal string GetReturnUrl() { string returnUrl = SamlHelpers.GetCookieReturnUrl(); SamlHelpers.ClearCookieReturnUrl(); if (string.IsNullOrEmpty(returnUrl)) { returnUrl = Apis.Get <IUrl>().Absolute(Apis.Get <ICoreUrls>().Home()); } return(returnUrl); }
internal Source(InternalApi.KhartaSource source) { var a = source.Id; ApplicationId = source.ApplicationId; ApplicationTypeId = source.ApplicationTypeId; AvatarUrl = source.AvatarUrl; Description = source.Description; Name = source.Name; OntologyId = source.OntologyId.HasValue ? source.OntologyId.Value : 0; SafeName = source.SafeName; Url = source.Url; IsEnabled = source.IsEnabled.HasValue ? source.IsEnabled.Value : true; GroupId = source.GroupId.HasValue ? source.GroupId.Value : Apis.Get <IGroups>().Root.Id.Value; }
public void Initialize() { _eventLogApi = Apis.Get <IEventLog>(); _usersApi = Apis.Get <IUsers>(); _urlApi = Apis.Get <IUrl>(); _coreUrlsApi = Apis.Get <ICoreUrls>(); //hook the user created event to save SAML token data (from secure cookie if persist flag is set) for new users _usersApi.Events.AfterCreate += new UserAfterCreateEventHandler(Events_AfterUserCreate); //hook to create custom user authenticated event _usersApi.Events.AfterIdentify += new UserAfterIdentifyEventHandler(Events_AfterIdentify); //cleanup persistent storage when a user is deleted _usersApi.Events.AfterDelete += new UserAfterDeleteEventHandler(Events_AfterUserDelete); }
public string Form(int formId) { // TODO: Replace hard coded entity var form = new Form { Title = "New Form", Body = "Test entity", Id = formId, GroupId = 1 }; return(Apis.Get <IUrl>().BuildUrl("forms.view", form.GroupId, new Dictionary <string, string> { { "id", form.Id.ToString() } })); }
public static void AddIdentityServer(this IServiceCollection services, IConfiguration config, IHostEnvironment env) => services .AddIdentityServer( options => { options.Events.RaiseErrorEvents = true; options.Events.RaiseInformationEvents = true; options.Events.RaiseFailureEvents = true; options.Events.RaiseSuccessEvents = true; }) .AddInMemoryIdentityResources(Resources.Get()) .AddInMemoryApiResources(Apis.Get()) .AddInMemoryClients(Clients.Get(config)) .AddAspNetIdentity <ApplicationUser>() .AddSigningCredentials(env);
internal static SamlTokenData GetFromSecureCookie(string tokenKey) { try { HttpCookie secureCookie = CookieHelper.GetCookie(tokenKey); var samlXml = SamlHelpers.Unprotect(secureCookie.Value, typeof(SamlTokenData).Name); var samlTokenData = SamlHelpers.Deserialize <SamlTokenData>(samlXml); return(samlTokenData); } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error Extracting SAML token from cookie:" + ex, new EventLogEntryWriteOptions { Category = "SAML", EventType = "Error", EventId = 1001 }); } return(null); }
public static bool IsValidInvitationKey(Guid invitationKey) { try { //check to see that the invitation is present and valid var invite = Apis.Get <IUserInvitations>().Get(invitationKey); if (invite != null) { return(!invite.HasErrors()); } } catch (Exception) { } return(false); }
private static void InsertSamlToken(int userId, string oAuthData, DateTime responseDate, string email, string nameId) { try { using (var myConnection = GetSqlConnection()) { var sql = $@"INSERT INTO [{databaseOwner}].[db_SamlTokenStore] ([UserId] ,[SamlOAuthData] ,[ResponseDate] ,[Email] ,[ClientId]) VALUES (@userId ,@samlOAuthData ,@responseDate ,@email ,@nameId)"; var myCommand = new SqlCommand(sql, myConnection) { CommandType = CommandType.Text }; myCommand.Parameters.Add("@userId", SqlDbType.Int).Value = userId; myCommand.Parameters.Add("@samlOAuthData", SqlDbType.Text).Value = oAuthData; myCommand.Parameters.Add("@responseDate", SqlDbType.DateTime).Value = responseDate; myCommand.Parameters.Add("@email", SqlDbType.NVarChar).Value = email; myCommand.Parameters.Add("@nameId", SqlDbType.NVarChar).Value = nameId; // Execute the command myConnection.Open(); myCommand.ExecuteNonQuery(); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error inserting token into the db_SamlTokenStore. " + ex, new EventLogEntryWriteOptions { Category = "SAML", EventId = 6009, EventType = "Error" }); } }
private ApiList <Evolution.Extensibility.Api.Entities.Version1.UserProfileField> GetSamlProfileFields() { var samlProfileFields = new ApiList <Evolution.Extensibility.Api.Entities.Version1.UserProfileField>(); var allProfileFields = Apis.Get <IUserProfileFields>().List(new UserProfileFieldsListOptions() { PageSize = int.MaxValue }); foreach (var profileField in allProfileFields) { if (profileField.Name.StartsWith(ProfileFieldPrefix, StringComparison.InvariantCultureIgnoreCase)) { samlProfileFields.Add(profileField); } } return(samlProfileFields); }
//1) can userId create application? anyone for now //2) what containerTypes are supported? just group containers for now //3) containerId is the group Guid, or any other application that has a nodeId //4) configurationDatabase is the properties set in the panel used to create the application public IApplication Create(int userId, Guid containerTypeId, Guid containerId, ConfigurationDataBase createConfigurationData) { try { foreach (Guid _containerTypeId in ContainerTypes) { //container types for groups is if (Apis.Get <IGroups>().ContainerTypeId == _containerTypeId) { int groupId = Apis.Get <IGroups>().Get(containerId).Id.Value; InternalApi.CoriaMapBook coriaMapBook = new InternalApi.CoriaMapBook(); coriaMapBook.ApplicationId = Guid.NewGuid(); coriaMapBook.ApplicationTypeId = CoriaMapBookType._applicationTypeId; coriaMapBook.AvatarUrl = createConfigurationData.GetStringValue("mapBookAvatarUrl", "/cfs-filesystemfile/__key/system/images/grid.svg"); coriaMapBook.Name = createConfigurationData.GetStringValue("mapBookName", "Map Book"); coriaMapBook.GroupId = groupId; coriaMapBook.IsEnabled = createConfigurationData.GetBoolValue("mapBookIsEnabled", true); coriaMapBook.Id = 0; coriaMapBook.OntologyId = 0; coriaMapBook.Description = createConfigurationData.GetStringValue("mapBookDesc", "a list of maps"); coriaMapBook.Url = createConfigurationData.GetStringValue("mapBookUrl", "mapbooks"); coriaMapBook.SafeName = createConfigurationData.GetStringValue("safeNameUrl", coriaMapBook.ApplicationId.ToString()); //coriaMapBook.SafeName = createConfigurationData.GetStringValue("mapBookUrl", "mapbook"); coriaMapBook = InternalApi.CoriaDataService.CreateUpdateMapBook(coriaMapBook); return(PublicApi.MapBooks.Get(coriaMapBook.Id)); } if (Apis.Get <IUsers>().ContainerTypeId == _containerTypeId) { //TODO: implement user's map applications return(null); } } } catch (Exception ex) { //IUserRenderableException. string exceptions = ex.Message; throw; } return(null); }
private static string GetOAuthClientUserId(int userId) { string clientUserId = null; try { using (var conn = GetSqlConnection()) { using (var command = new SqlCommand($"[{databaseOwner}].[te_OAuth_GetLinkByClientTypeAndUser]", conn) { CommandType = CommandType.StoredProcedure }) { command.Parameters.Add("@ClientType", SqlDbType.NVarChar).Value = "saml"; command.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; conn.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { clientUserId = reader.GetString(reader.GetOrdinal("ClientUserId")); reader.Close(); return(clientUserId); } } } } } catch (Exception ex) { Apis.Get <IEventLog>() .Write($"Could not get OAuth Link for user {userId}. {ex}", new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6022, EventType = "Error" }); clientUserId = null; } return(clientUserId); }
public static string GetKeyValueFromUrlFragment(string urlFragment, string key) { if (string.IsNullOrEmpty(urlFragment) || string.IsNullOrEmpty(key)) { return(null); } try { urlFragment = HttpUtility.UrlDecode(urlFragment); if (string.IsNullOrEmpty(urlFragment) || !urlFragment.Contains("?")) //empty or no querystring to parse { return(null); } //if the url is more than a querystring we need to just extract the querystring if (urlFragment.Contains("?") && !urlFragment.StartsWith("?")) { //trim it down (we probably could do this with new Uri(urlFragment); instead) urlFragment = urlFragment.Split('?')[1]; } NameValueCollection query = HttpUtility.ParseQueryString(urlFragment); if (!query[key].Equals(Guid.Empty.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return(query[key]); } } catch (Exception ex) { Apis.Get <IEventLog>().Write(string.Format("ERROR trying to extract key {0} from return url provided:{1} - {2}", key, urlFragment, ex.ToString()), new EventLogEntryWriteOptions() { Category = "SAML", EventId = 6018, EventType = "Error" }); } return(null); }
public static SamlTokenData GetSamlTokenStoreData(int userId) { try { using (var myConnection = GetSqlConnection()) { var sql = $@"SELECT top 1 SamlOAuthData FROM [{databaseOwner}].[db_SamlTokenStore] WHERE UserId = @userId ORDER BY ResponseDate Desc"; var myCommand = new SqlCommand(sql, myConnection) { CommandType = CommandType.Text }; myCommand.Parameters.Add("@userId", SqlDbType.Int).Value = userId; // Execute the command myConnection.Open(); var scalar = myCommand.ExecuteScalar(); if (scalar == null) { return(null); } var oAuthData = SamlHelpers.Deserialize <SamlTokenData>(scalar.ToString()); return(oAuthData); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error reading from db_SamlTokenStore; I dont think its installed. " + ex, new EventLogEntryWriteOptions { Category = "SAML", EventId = 6011, EventType = "Error" }); } return(null); }
public void Initialize(string fileStoreKey, XmlNode node) { FileStoreKey = fileStoreKey; _awsAuthPrivateKey = node.Attributes["awsSecretAccessKey"].Value; _awsAuthPublicKey = node.Attributes["awsAccessKeyId"].Value; _bucketName = node.Attributes["bucket"].Value; _isSecure = node.Attributes["secure"] == null || node.Attributes["secure"].Value == "true"; _s3domain = node.Attributes["domain"] != null ? node.Attributes["domain"].Value : (string)null; _region = node.Attributes["region"] != null ? node.Attributes["region"].Value : (string)null; _authorization = node.Attributes["authorization"] != null ? node.Attributes["authorization"].Value : (string)null; try { var connection = GetConnection(); if (connection.BucketExists(_bucketName)) return; connection.CreateBucket(_bucketName, new SortedList<string, string>()); } catch (Exception ex) { Apis.Get<IEventLog>().Write($"Error when creating an AmazonS3 Bucket - ex: {ex.ToString()}", new EventLogEntryWriteOptions() { EventType = "Error", Category = this.GetType().Name }); } }
public static List <SamlTokenData> GetSamlTokenData(string nameId) { try { using (var myConnection = GetSqlConnection()) { var sql = $@"SELECT SamlOAuthData FROM [{databaseOwner}].[db_SamlTokenStore] WHERE ClientId = @nameId"; var myCommand = new SqlCommand(sql, myConnection) { CommandType = CommandType.Text }; myCommand.Parameters.Add("@nameId", SqlDbType.NVarChar).Value = nameId; var oAuthDatas = new List <SamlTokenData>(); // Execute the command myConnection.Open(); using (var dr = myCommand.ExecuteReader()) { while (dr.Read()) { oAuthDatas.Add(SamlHelpers.Deserialize <SamlTokenData>(dr[0].ToString())); } } return(oAuthDatas); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error reading from db_SamlTokenStore. " + ex, new EventLogEntryWriteOptions { Category = "SAML", EventId = 6012, EventType = "Error" }); } return(null); }
public OAuthData ProcessLogin(HttpContextBase context) { var apiExceptions = Apis.Get <IExceptions>(); if (!Enabled) { return(null); } //should have a SamlOAuthClient.oauthTokeyQuerystringKey which corresponds to the current cookie to decrypt var tokenKey = HttpContext.Current.Request[oauthTokeyQuerystringKey]; if (!string.IsNullOrEmpty(tokenKey)) { var samlTokenData = SamlTokenData.GetTokenDataFromDatabase(tokenKey); if (samlTokenData == null) { apiExceptions.Log(new ArgumentException( "The SAML token was not found in the HttpContext.Current.Request, or could not be extracted. Please ensure cookies are enabled and try again.")); ProcessReturnUrl(); } //Store our token key so we can retrieve it later to raise the SamlUserCreated and SamlAuthenticated events and delete it var afterAuthenticatedCookie = new HttpCookie(clientType, tokenKey) { HttpOnly = true, Expires = DateTime.Now.AddHours(8) }; CookieHelper.AddCookie(afterAuthenticatedCookie); //this object is stored in temporary storage by the oauth handler, its guid is placed into the return url into the "TOKEN" placeholder. //the expectation of this processing is the return url at this time is to the login page, and that any login based return url should be double encoded return(samlTokenData.GetOAuthData()); } //if this is not a sign-in response, we should probably redirect to login.aspx apiExceptions.Log(new ArgumentException("The SAML token was not found in the HttpContext.Current.Request, please check the configuration and try again")); return(null); }
private static void UpdateSamlToken(int userId, string oAuthData, DateTime responseDate, string email, string nameId) { try { using (var myConnection = GetSqlConnection()) { var sql = $@"UPDATE [{databaseOwner}].[db_SamlTokenStore] SET [SamlOAuthData] = @samlOAuthData ,[ResponseDate] = @responseDate ,[Email] = @email ,[ClientId] = @nameId WHERE UserId = @userId"; var myCommand = new SqlCommand(sql, myConnection) { CommandType = CommandType.Text }; myCommand.Parameters.Add("@userId", SqlDbType.Int).Value = userId; myCommand.Parameters.Add("@samlOAuthData", SqlDbType.Text).Value = oAuthData; myCommand.Parameters.Add("@responseDate", SqlDbType.DateTime).Value = responseDate; myCommand.Parameters.Add("@email", SqlDbType.NVarChar).Value = email; myCommand.Parameters.Add("@nameId", SqlDbType.NVarChar).Value = nameId; // Execute the command myConnection.Open(); myCommand.ExecuteNonQuery(); } } catch (Exception ex) { Apis.Get <IEventLog>().Write("Error updating from db_SamlTokenStore. " + ex, new EventLogEntryWriteOptions { Category = "SAML", EventId = 6010, EventType = "Error" }); } }
/// <summary> /// Converts the users ProfileFields collection into something that can be saved, when you get a user profile field you get "lables" and "values" /// But when you save it you need to use "Names" and "Values", This class expects everyting to be the "Name" or Profile Field "Key" /// </summary> /// <param name="profileFields"></param> /// <returns></returns> private ApiList <ProfileField> ConvertTitlesToNames(ApiList <ProfileField> profileFields) { var cleanedProfileFields = new ApiList <ProfileField>(); var allProfileFields = Apis.Get <IUserProfileFields>().List(new UserProfileFieldsListOptions() { PageSize = int.MaxValue }); foreach (var profileField in profileFields) { var fieldDefinition = allProfileFields.Where(i => i.Name == profileField.Label).First(); if (fieldDefinition != null) { cleanedProfileFields.Add(new ProfileField() { Label = fieldDefinition.Name, Value = profileField.Value }); } } return(cleanedProfileFields); }
public void ProcessRequest(HttpContext context) { var urls = Apis.Get <IUrl>(); var forum = urls.CurrentContext.ContextItems.GetAllContextItems() .FirstOrDefault(f => f.ContentTypeId == Apis.Get <IForums>().ContentTypeId); if (forum != null) { var threads = Apis.Get <IForumThreads>().List(new ForumThreadsListOptions() { ForumId = int.Parse(forum.Id) }); foreach (var post in threads) { context.Response.Write(post.Excerpt + "<br />"); } } context.Response.End(); }