diff options
Diffstat (limited to 'projecttemplates')
34 files changed, 493 insertions, 283 deletions
diff --git a/projecttemplates/WebFormsRelyingParty/Admin/CreateDatabase.sql b/projecttemplates/RelyingPartyLogic/CreateDatabase.sql index 52ca669..52ca669 100644 --- a/projecttemplates/WebFormsRelyingParty/Admin/CreateDatabase.sql +++ b/projecttemplates/RelyingPartyLogic/CreateDatabase.sql diff --git a/projecttemplates/WebFormsRelyingParty/Code/DataRoleProvider.cs b/projecttemplates/RelyingPartyLogic/DataRoleProvider.cs index 8117e4b..1171646 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/DataRoleProvider.cs +++ b/projecttemplates/RelyingPartyLogic/DataRoleProvider.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -18,10 +18,10 @@ namespace WebFormsRelyingParty.Code { } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { - var users = from token in Global.DataContext.AuthenticationToken + var users = from token in Database.DataContext.AuthenticationToken where usernames.Contains(token.ClaimedIdentifier) select token.User; - var roles = from role in Global.DataContext.Role + var roles = from role in Database.DataContext.Role where roleNames.Contains(role.Name, StringComparer.OrdinalIgnoreCase) select role; foreach (User user in users) { @@ -32,10 +32,10 @@ namespace WebFormsRelyingParty.Code { } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { - var users = from token in Global.DataContext.AuthenticationToken + var users = from token in Database.DataContext.AuthenticationToken where usernames.Contains(token.ClaimedIdentifier) select token.User; - var roles = from role in Global.DataContext.Role + var roles = from role in Database.DataContext.Role where roleNames.Contains(role.Name, StringComparer.OrdinalIgnoreCase) select role; foreach (User user in users) { @@ -46,7 +46,7 @@ namespace WebFormsRelyingParty.Code { } public override void CreateRole(string roleName) { - Global.DataContext.AddToRole(new Role { Name = roleName }); + Database.DataContext.AddToRole(new Role { Name = roleName }); } /// <summary> @@ -58,7 +58,7 @@ namespace WebFormsRelyingParty.Code { /// true if the role was successfully deleted; otherwise, false. /// </returns> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { - Role role = Global.DataContext.Role.SingleOrDefault(r => r.Name == roleName); + Role role = Database.DataContext.Role.SingleOrDefault(r => r.Name == roleName); if (role == null) { return false; } @@ -67,7 +67,7 @@ namespace WebFormsRelyingParty.Code { throw new InvalidOperationException(); } - Global.DataContext.DeleteObject(roleName); + Database.DataContext.DeleteObject(roleName); return true; } @@ -80,7 +80,7 @@ namespace WebFormsRelyingParty.Code { /// A string array containing the names of all the users where the user name matches <paramref name="usernameToMatch"/> and the user is a member of the specified role. /// </returns> public override string[] FindUsersInRole(string roleName, string usernameToMatch) { - return (from role in Global.DataContext.Role + return (from role in Database.DataContext.Role where role.Name == roleName from user in role.Users from authTokens in user.AuthenticationTokens @@ -89,18 +89,18 @@ namespace WebFormsRelyingParty.Code { } public override string[] GetAllRoles() { - return Global.DataContext.Role.Select(role => role.Name).ToArray(); + return Database.DataContext.Role.Select(role => role.Name).ToArray(); } public override string[] GetRolesForUser(string username) { - return (from authToken in Global.DataContext.AuthenticationToken + return (from authToken in Database.DataContext.AuthenticationToken where authToken.ClaimedIdentifier == username from role in authToken.User.Roles select role.Name).ToArray(); } public override string[] GetUsersInRole(string roleName) { - return (from role in Global.DataContext.Role + return (from role in Database.DataContext.Role where string.Equals(role.Name, roleName, StringComparison.OrdinalIgnoreCase) from user in role.Users from token in user.AuthenticationTokens @@ -108,7 +108,7 @@ namespace WebFormsRelyingParty.Code { } public override bool IsUserInRole(string username, string roleName) { - Role role = Global.DataContext.Role.SingleOrDefault(r => string.Equals(r.Name, roleName, StringComparison.OrdinalIgnoreCase)); + Role role = Database.DataContext.Role.SingleOrDefault(r => string.Equals(r.Name, roleName, StringComparison.OrdinalIgnoreCase)); if (role != null) { return role.Users.Any(user => user.AuthenticationTokens.Any(token => token.ClaimedIdentifier == username)); } @@ -117,7 +117,7 @@ namespace WebFormsRelyingParty.Code { } public override bool RoleExists(string roleName) { - return Global.DataContext.Role.Any(role => string.Equals(role.Name, roleName, StringComparison.OrdinalIgnoreCase)); + return Database.DataContext.Role.Any(role => string.Equals(role.Name, roleName, StringComparison.OrdinalIgnoreCase)); } } } diff --git a/projecttemplates/RelyingPartyLogic/Database.cs b/projecttemplates/RelyingPartyLogic/Database.cs new file mode 100644 index 0000000..a1e17a6 --- /dev/null +++ b/projecttemplates/RelyingPartyLogic/Database.cs @@ -0,0 +1,150 @@ +//----------------------------------------------------------------------- +// <copyright file="Database.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace RelyingPartyLogic { + using System; + using System.Collections.Generic; + using System.Data; + using System.Data.SqlClient; + using System.Linq; + using System.ServiceModel; + using System.Text; + using System.Web; + + public class Database : IHttpModule, IDisposable { + private const string DataContextKey = "DataContext"; + + private const string DataContextTransactionKey = "DataContextTransaction"; + + /// <summary> + /// Initializes a new instance of the <see cref="Database"/> class. + /// </summary> + public Database() { + } + + public static User LoggedInUser { + get { return DataContext.AuthenticationToken.Where(token => token.ClaimedIdentifier == HttpContext.Current.User.Identity.Name).Select(token => token.User).FirstOrDefault(); } + } + + /// <summary> + /// Gets the transaction-protected database connection for the current request. + /// </summary> + public static DatabaseEntities DataContext { + get { + DatabaseEntities dataContext = DataContextSimple; + if (dataContext == null) { + dataContext = new DatabaseEntities(); + try { + dataContext.Connection.Open(); + } catch (EntityException entityEx) { + var sqlEx = entityEx.InnerException as SqlException; + if (sqlEx != null) { + if (sqlEx.Class == 14 && sqlEx.Number == 15350) { + // Most likely the database schema hasn't been created yet. + HttpContext.Current.Response.Redirect("~/Setup.aspx"); + } + } + + throw; + } + + DataContextTransactionSimple = dataContext.Connection.BeginTransaction(); + DataContextSimple = dataContext; + } + + return dataContext; + } + } + + private static DatabaseEntities DataContextSimple { + get { + if (HttpContext.Current != null) { + return HttpContext.Current.Items[DataContextKey] as DatabaseEntities; + } else if (OperationContext.Current != null) { + object data; + if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextKey, out data)) { + return data as DatabaseEntities; + } else { + return null; + } + } else { + throw new InvalidOperationException(); + } + } + + set { + if (HttpContext.Current != null) { + HttpContext.Current.Items[DataContextKey] = value; + } else if (OperationContext.Current != null) { + OperationContext.Current.IncomingMessageProperties[DataContextKey] = value; + } else { + throw new InvalidOperationException(); + } + } + } + + private static IDbTransaction DataContextTransactionSimple { + get { + if (HttpContext.Current != null) { + return HttpContext.Current.Items[DataContextTransactionKey] as IDbTransaction; + } else if (OperationContext.Current != null) { + object data; + if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextTransactionKey, out data)) { + return data as IDbTransaction; + } else { + return null; + } + } else { + throw new InvalidOperationException(); + } + } + + set { + if (HttpContext.Current != null) { + HttpContext.Current.Items[DataContextTransactionKey] = value; + } else if (OperationContext.Current != null) { + OperationContext.Current.IncomingMessageProperties[DataContextTransactionKey] = value; + } else { + throw new InvalidOperationException(); + } + } + } + + public void Dispose() { + } + + void IHttpModule.Init(HttpApplication context) { + context.EndRequest += this.Application_EndRequest; + context.Error += this.Application_Error; + } + + protected void Application_EndRequest(object sender, EventArgs e) { + CommitAndCloseDatabaseIfNecessary(); + } + + protected void Application_Error(object sender, EventArgs e) { + if (DataContextTransactionSimple != null) { + DataContextTransactionSimple.Rollback(); + DataContextTransactionSimple.Dispose(); + DataContextTransactionSimple = null; + } + } + + private static void CommitAndCloseDatabaseIfNecessary() { + var dataContext = DataContextSimple; + if (dataContext != null) { + dataContext.SaveChanges(); + if (DataContextTransactionSimple != null) { + DataContextTransactionSimple.Commit(); + DataContextTransactionSimple.Dispose(); + } + + dataContext.Dispose(); + DataContextSimple = null; + } + } + } +} diff --git a/projecttemplates/WebFormsRelyingParty/Model.AuthenticationToken.cs b/projecttemplates/RelyingPartyLogic/Model.AuthenticationToken.cs index 53ca10f..e44fd83 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.AuthenticationToken.cs +++ b/projecttemplates/RelyingPartyLogic/Model.AuthenticationToken.cs @@ -1,4 +1,4 @@ -namespace WebFormsRelyingParty { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -10,7 +10,7 @@ } private static string UriPrefixForInfoCard { - get { return new Uri(HttpContext.Current.Request.Url, Global.ApplicationPath + "infocard/").AbsoluteUri; } + get { return new Uri(Utilities.ApplicationRoot, "infocard/").AbsoluteUri; } } public static string SynthesizeClaimedIdentifierFromInfoCard(string uniqueId) { diff --git a/projecttemplates/WebFormsRelyingParty/Model.Consumer.cs b/projecttemplates/RelyingPartyLogic/Model.Consumer.cs index 5076d6d..a09029a 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.Consumer.cs +++ b/projecttemplates/RelyingPartyLogic/Model.Consumer.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/WebFormsRelyingParty/Model.Designer.cs b/projecttemplates/RelyingPartyLogic/Model.Designer.cs index d265efa..d19d305 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.Designer.cs +++ b/projecttemplates/RelyingPartyLogic/Model.Designer.cs @@ -9,14 +9,14 @@ //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] -[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "UserRole", "Role", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(WebFormsRelyingParty.Role), "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(WebFormsRelyingParty.User))] -[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "UserAuthenticationToken", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(WebFormsRelyingParty.User), "AuthenticationToken", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(WebFormsRelyingParty.AuthenticationToken))] -[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_Consumer", "Consumer", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(WebFormsRelyingParty.Consumer), "IssuedTokens", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(WebFormsRelyingParty.IssuedToken))] -[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_User", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(WebFormsRelyingParty.User), "IssuedTokens", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(WebFormsRelyingParty.IssuedToken))] +[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "UserRole", "Role", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.Role), "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.User))] +[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "UserAuthenticationToken", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.User), "AuthenticationToken", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.AuthenticationToken))] +[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_Consumer", "Consumer", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(RelyingPartyLogic.Consumer), "IssuedTokens", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.IssuedToken))] +[assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("DatabaseModel", "FK_IssuedToken_User", "User", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(RelyingPartyLogic.User), "IssuedTokens", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(RelyingPartyLogic.IssuedToken))] // Original file name: -// Generation date: 11/11/2009 10:26:25 PM -namespace WebFormsRelyingParty +// Generation date: 11/13/2009 4:45:45 PM +namespace RelyingPartyLogic { /// <summary> @@ -823,8 +823,8 @@ namespace WebFormsRelyingParty [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="DatabaseModel", Name="IssuedToken")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] - [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::WebFormsRelyingParty.IssuedRequestToken))] - [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::WebFormsRelyingParty.IssuedAccessToken))] + [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::RelyingPartyLogic.IssuedRequestToken))] + [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::RelyingPartyLogic.IssuedAccessToken))] public abstract partial class IssuedToken : global::System.Data.Objects.DataClasses.EntityObject { /// <summary> diff --git a/projecttemplates/WebFormsRelyingParty/Model.IssuedAccessToken.cs b/projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs index ab064c3..fff27af 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.IssuedAccessToken.cs +++ b/projecttemplates/RelyingPartyLogic/Model.IssuedAccessToken.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/WebFormsRelyingParty/Model.IssuedRequestToken.cs b/projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs index 1352e54..c62f5c4 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.IssuedRequestToken.cs +++ b/projecttemplates/RelyingPartyLogic/Model.IssuedRequestToken.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -49,8 +49,8 @@ namespace WebFormsRelyingParty { /// Call this method when the user has completed web-based authorization. /// </remarks> public void Authorize() { - this.User = Global.LoggedInUser; - Global.DataContext.SaveChanges(); + this.User = Database.LoggedInUser; + Database.DataContext.SaveChanges(); } } } diff --git a/projecttemplates/WebFormsRelyingParty/Model.User.cs b/projecttemplates/RelyingPartyLogic/Model.User.cs index 1493603..16980e2 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.User.cs +++ b/projecttemplates/RelyingPartyLogic/Model.User.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/WebFormsRelyingParty/Model.edmx b/projecttemplates/RelyingPartyLogic/Model.edmx index f37aa6c..f37aa6c 100644 --- a/projecttemplates/WebFormsRelyingParty/Model.edmx +++ b/projecttemplates/RelyingPartyLogic/Model.edmx diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthAuthenticationModule.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs index 426dce5..e47e4ee 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthAuthenticationModule.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthAuthorizationManager.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs index 480e1b9..752e2eb 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthAuthorizationManager.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.IdentityModel.Policy; @@ -33,7 +33,7 @@ namespace WebFormsRelyingParty.Code { ServiceProvider sp = OAuthServiceProvider.ServiceProvider; var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri); if (auth != null) { - var accessToken = Global.DataContext.IssuedToken.OfType<IssuedAccessToken>().First(token => token.Token == auth.AccessToken); + var accessToken = Database.DataContext.IssuedToken.OfType<IssuedAccessToken>().First(token => token.Token == auth.AccessToken); var principal = sp.CreatePrincipal(auth); var policy = new OAuthPrincipalAuthorizationPolicy(principal); diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthConsumerTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs index 107934b..64e6be8 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthConsumerTokenManager.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthConsumerTokenManager.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthPrincipalAuthorizationPolicy.cs b/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs index b2c9a2d..ddd0b3f 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthPrincipalAuthorizationPolicy.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthPrincipalAuthorizationPolicy.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.IdentityModel.Claims; diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthServiceProvider.cs b/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs index b914315..8d582ab 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthServiceProvider.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthServiceProvider.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -61,14 +61,14 @@ namespace WebFormsRelyingParty.Code { set { HttpContext.Current.Session[PendingAuthorizationRequestSessionKey] = value; } } - public static WebFormsRelyingParty.Consumer PendingAuthorizationConsumer { + public static Consumer PendingAuthorizationConsumer { get { ITokenContainingMessage message = PendingAuthorizationRequest; if (message == null) { throw new InvalidOperationException(); } - return Global.DataContext.IssuedToken.OfType<IssuedRequestToken>().Include("Consumer").First(t => t.Token == message.Token).Consumer; + return Database.DataContext.IssuedToken.OfType<IssuedRequestToken>().Include("Consumer").First(t => t.Token == message.Token).Consumer; } } @@ -79,7 +79,7 @@ namespace WebFormsRelyingParty.Code { } ITokenContainingMessage msg = pendingRequest; - var token = Global.DataContext.IssuedToken.OfType<IssuedRequestToken>().First(t => t.Token == msg.Token); + var token = Database.DataContext.IssuedToken.OfType<IssuedRequestToken>().First(t => t.Token == msg.Token); token.Authorize(); PendingAuthorizationRequest = null; diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthServiceProviderTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs index 224a181..be53180 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthServiceProviderTokenManager.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthServiceProviderTokenManager.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -30,7 +30,7 @@ namespace WebFormsRelyingParty.Code { /// <exception cref="KeyNotFoundException">Thrown if the consumer key cannot be found.</exception> public IConsumerDescription GetConsumer(string consumerKey) { try { - return Global.DataContext.Consumer.First(c => c.ConsumerKey == consumerKey); + return Database.DataContext.Consumer.First(c => c.ConsumerKey == consumerKey); } catch (InvalidOperationException) { throw new KeyNotFoundException(); } @@ -47,7 +47,7 @@ namespace WebFormsRelyingParty.Code { /// been authorized, has expired or does not exist. /// </returns> public bool IsRequestTokenAuthorized(string requestToken) { - return Global.DataContext.IssuedToken.OfType<IssuedRequestToken>().Any( + return Database.DataContext.IssuedToken.OfType<IssuedRequestToken>().Any( t => t.Token == requestToken && t.User != null); } @@ -65,7 +65,7 @@ namespace WebFormsRelyingParty.Code { /// </remarks> public IServiceProviderRequestToken GetRequestToken(string token) { try { - return Global.DataContext.IssuedToken.OfType<IssuedRequestToken>().First(tok => tok.Token == token); + return Database.DataContext.IssuedToken.OfType<IssuedRequestToken>().First(tok => tok.Token == token); } catch (InvalidOperationException) { throw new KeyNotFoundException(); } @@ -85,7 +85,7 @@ namespace WebFormsRelyingParty.Code { /// </remarks> public IServiceProviderAccessToken GetAccessToken(string token) { try { - return Global.DataContext.IssuedToken.OfType<IssuedAccessToken>().First(tok => tok.Token == token); + return Database.DataContext.IssuedToken.OfType<IssuedAccessToken>().First(tok => tok.Token == token); } catch (InvalidOperationException) { throw new KeyNotFoundException(); } @@ -104,7 +104,7 @@ namespace WebFormsRelyingParty.Code { /// will automatically be saved without any extra handling). /// </remarks> public void UpdateToken(IServiceProviderRequestToken token) { - Global.DataContext.SaveChanges(); + Database.DataContext.SaveChanges(); } #endregion diff --git a/projecttemplates/WebFormsRelyingParty/Code/OAuthTokenManager.cs b/projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs index ff757c9..fbba776 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/OAuthTokenManager.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthTokenManager.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; @@ -37,7 +37,7 @@ namespace WebFormsRelyingParty.Code { /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> public string GetTokenSecret(string token) { try { - return Global.DataContext.IssuedToken.First(t => t.Token == token).TokenSecret; + return Database.DataContext.IssuedToken.First(t => t.Token == token).TokenSecret; } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException(); } @@ -59,7 +59,7 @@ namespace WebFormsRelyingParty.Code { public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { Consumer consumer; try { - consumer = Global.DataContext.Consumer.First(c => c.ConsumerKey == request.ConsumerKey); + consumer = Database.DataContext.Consumer.First(c => c.ConsumerKey == request.ConsumerKey); } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException(); } @@ -75,8 +75,8 @@ namespace WebFormsRelyingParty.Code { if (request.ExtraData.TryGetValue("scope", out scope)) { token.Scope = scope; } - Global.DataContext.AddToIssuedToken(token); - Global.DataContext.SaveChanges(); + Database.DataContext.AddToIssuedToken(token); + Database.DataContext.SaveChanges(); } /// <summary> @@ -103,7 +103,7 @@ namespace WebFormsRelyingParty.Code { /// </para> /// </remarks> public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - var requestTokenEntity = Global.DataContext.IssuedToken.OfType<IssuedRequestToken>() + var requestTokenEntity = Database.DataContext.IssuedToken.OfType<IssuedRequestToken>() .Include("User") .First(t => t.Consumer.ConsumerKey == consumerKey && t.Token == requestToken); @@ -117,9 +117,9 @@ namespace WebFormsRelyingParty.Code { Consumer = requestTokenEntity.Consumer, }; - Global.DataContext.DeleteObject(requestTokenEntity); - Global.DataContext.AddToIssuedToken(accessTokenEntity); - Global.DataContext.SaveChanges(); + Database.DataContext.DeleteObject(requestTokenEntity); + Database.DataContext.AddToIssuedToken(accessTokenEntity); + Database.DataContext.SaveChanges(); } /// <summary> @@ -130,7 +130,7 @@ namespace WebFormsRelyingParty.Code { /// Request or Access token, or invalid if the token is not recognized. /// </returns> public TokenType GetTokenType(string token) { - IssuedToken tok = Global.DataContext.IssuedToken.FirstOrDefault(t => t.Token == token); + IssuedToken tok = Database.DataContext.IssuedToken.FirstOrDefault(t => t.Token == token); if (tok == null) { return TokenType.InvalidToken; } else { diff --git a/projecttemplates/WebFormsRelyingParty/Code/Policies.cs b/projecttemplates/RelyingPartyLogic/Policies.cs index 676b3f2..6bf72d3 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/Policies.cs +++ b/projecttemplates/RelyingPartyLogic/Policies.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace WebFormsRelyingParty.Code { +namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; diff --git a/projecttemplates/RelyingPartyLogic/Properties/AssemblyInfo.cs b/projecttemplates/RelyingPartyLogic/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8cb040c --- /dev/null +++ b/projecttemplates/RelyingPartyLogic/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("RelyingPartyLogic")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft IT")] +[assembly: AssemblyProduct("RelyingPartyLogic")] +[assembly: AssemblyCopyright("Copyright © Microsoft IT 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("86d51499-3206-4eea-9bfe-b7950dac606b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj b/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj new file mode 100644 index 0000000..7000e2b --- /dev/null +++ b/projecttemplates/RelyingPartyLogic/RelyingPartyLogic.csproj @@ -0,0 +1,131 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.30729</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{17932639-1F50-48AF-B0A5-E2BF832F82CC}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>RelyingPartyLogic</RootNamespace> + <AssemblyName>RelyingPartyLogic</AssemblyName> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\lib\log4net.dll</HintPath> + </Reference> + <Reference Include="Microsoft.SqlServer.ConnectionInfo" /> + <Reference Include="Microsoft.SqlServer.Smo" /> + <Reference Include="Microsoft.SqlServer.Management.Sdk.Sfc" /> + <Reference Include="System" /> + <Reference Include="System.Data" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.DataSetExtensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.Entity"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.IdentityModel"> + <RequiredTargetFramework>3.0</RequiredTargetFramework> + </Reference> + <Reference Include="System.Runtime.Serialization"> + <RequiredTargetFramework>3.0</RequiredTargetFramework> + </Reference> + <Reference Include="System.Security" /> + <Reference Include="System.ServiceModel"> + <RequiredTargetFramework>3.0</RequiredTargetFramework> + </Reference> + <Reference Include="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\..\Windows\assembly\GAC_MSIL\System.Web.Entity\3.5.0.0__b77a5c561934e089\System.Web.Entity.dll</HintPath> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Web.Extensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Drawing" /> + <Reference Include="System.Web" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Configuration" /> + <Reference Include="System.Web.Services" /> + <Reference Include="System.EnterpriseServices" /> + <Reference Include="System.Web.Mobile" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Database.cs" /> + <Compile Include="DataRoleProvider.cs" /> + <Compile Include="Model.AuthenticationToken.cs" /> + <Compile Include="Model.Consumer.cs" /> + <Compile Include="Model.Designer.cs"> + <DependentUpon>Model.edmx</DependentUpon> + <AutoGen>True</AutoGen> + <DesignTime>True</DesignTime> + </Compile> + <Compile Include="Model.IssuedAccessToken.cs" /> + <Compile Include="Model.IssuedRequestToken.cs" /> + <Compile Include="Model.User.cs" /> + <Compile Include="OAuthAuthenticationModule.cs" /> + <Compile Include="OAuthAuthorizationManager.cs" /> + <Compile Include="OAuthConsumerTokenManager.cs" /> + <Compile Include="OAuthPrincipalAuthorizationPolicy.cs" /> + <Compile Include="OAuthServiceProvider.cs" /> + <Compile Include="OAuthServiceProviderTokenManager.cs" /> + <Compile Include="OAuthTokenManager.cs" /> + <Compile Include="Policies.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="Utilities.cs" /> + </ItemGroup> + <ItemGroup> + <EntityDeploy Include="Model.edmx"> + <Generator>EntityModelCodeGenerator</Generator> + <LastGenOutput>Model.Designer.cs</LastGenOutput> + </EntityDeploy> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\DotNetOpenAuth\DotNetOpenAuth.csproj"> + <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project> + <Name>DotNetOpenAuth</Name> + </ProjectReference> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="CreateDatabase.sql" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project>
\ No newline at end of file diff --git a/projecttemplates/RelyingPartyLogic/Utilities.cs b/projecttemplates/RelyingPartyLogic/Utilities.cs new file mode 100644 index 0000000..02eb273 --- /dev/null +++ b/projecttemplates/RelyingPartyLogic/Utilities.cs @@ -0,0 +1,64 @@ +//----------------------------------------------------------------------- +// <copyright file="Utilities.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace RelyingPartyLogic { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text; + using System.Web; + using DotNetOpenAuth.OpenId; + using Microsoft.SqlServer.Management.Common; + using Microsoft.SqlServer.Management.Smo; + + public class Utilities { + internal const string DefaultNamespace = "RelyingPartyLogic"; + + /// <summary> + /// Gets the full URI of the web application root. Guaranteed to end in a slash. + /// </summary> + public static Uri ApplicationRoot { + get { + string appRoot = HttpContext.Current.Request.ApplicationPath; + if (!appRoot.EndsWith("/", StringComparison.Ordinal)) { + appRoot += "/"; + } + + return new Uri(HttpContext.Current.Request.Url, appRoot); + } + } + + public static void CreateDatabase(Identifier claimedId, string friendlyId) { + const string SqlFormat = @" +CREATE DATABASE [{0}] ON (NAME='{0}', FILENAME='{0}') +GO +USE ""{0}"" +GO +{1} +EXEC [dbo].[AddUser] 'admin', 'admin', '{2}', '{3}' +GO +"; + string schemaSql; + using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(DefaultNamespace + ".CreateDatabase.sql"))) { + schemaSql = sr.ReadToEnd(); + } + string databasePath = HttpContext.Current.Server.MapPath("~/App_Data/Database.mdf"); + string sql = string.Format(CultureInfo.InvariantCulture, SqlFormat, databasePath, schemaSql, claimedId, "Admin"); + + var serverConnection = new ServerConnection(".\\sqlexpress"); + try { + serverConnection.ExecuteNonQuery(sql); + var server = new Server(serverConnection); + server.DetachDatabase(databasePath, true); + } finally { + serverConnection.Disconnect(); + } + } + } +} diff --git a/projecttemplates/WebFormsRelyingParty/Admin/Default.aspx.cs b/projecttemplates/WebFormsRelyingParty/Admin/Default.aspx.cs index cc9abf1..261ddea 100644 --- a/projecttemplates/WebFormsRelyingParty/Admin/Default.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Admin/Default.aspx.cs @@ -14,10 +14,11 @@ namespace WebFormsRelyingParty.Admin { using System.Web; using System.Web.UI; using System.Web.UI.WebControls; + using RelyingPartyLogic; public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - this.usersRepeater.DataSource = Global.DataContext.User.Include("AuthenticationTokens"); + this.usersRepeater.DataSource = Database.DataContext.User.Include("AuthenticationTokens"); this.usersRepeater.DataBind(); } } diff --git a/projecttemplates/WebFormsRelyingParty/Code/Utilities.cs b/projecttemplates/WebFormsRelyingParty/Code/Utilities.cs index 25d293e..43c5236 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/Utilities.cs +++ b/projecttemplates/WebFormsRelyingParty/Code/Utilities.cs @@ -15,20 +15,6 @@ namespace WebFormsRelyingParty.Code { private const string CsrfCookieName = "CsrfCookie"; private static readonly RandomNumberGenerator CryptoRandomDataGenerator = new RNGCryptoServiceProvider(); - /// <summary> - /// Gets the full URI of the web application root. Guaranteed to end in a slash. - /// </summary> - public static Uri ApplicationRoot { - get { - string appRoot = HttpContext.Current.Request.ApplicationPath; - if (!appRoot.EndsWith("/", StringComparison.Ordinal)) { - appRoot += "/"; - } - - return new Uri(HttpContext.Current.Request.Url, appRoot); - } - } - public static string SetCsrfCookie() { // Generate an unpredictable secret that goes to the user agent and must come back // with authorization to guarantee the user interacted with this page rather than diff --git a/projecttemplates/WebFormsRelyingParty/Default.aspx.cs b/projecttemplates/WebFormsRelyingParty/Default.aspx.cs index 72e8973..cf78d83 100644 --- a/projecttemplates/WebFormsRelyingParty/Default.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Default.aspx.cs @@ -11,10 +11,11 @@ namespace WebFormsRelyingParty { using System.Web; using System.Web.UI; using System.Web.UI.WebControls; + using RelyingPartyLogic; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - User user = Global.LoggedInUser; + User user = Database.LoggedInUser; this.Label1.Text = user != null ? HttpUtility.HtmlEncode(user.FirstName) : "<not logged in>"; } } diff --git a/projecttemplates/WebFormsRelyingParty/Global.asax.cs b/projecttemplates/WebFormsRelyingParty/Global.asax.cs index 8a14dfc..31928fd 100644 --- a/projecttemplates/WebFormsRelyingParty/Global.asax.cs +++ b/projecttemplates/WebFormsRelyingParty/Global.asax.cs @@ -13,10 +13,6 @@ namespace WebFormsRelyingParty { using System.Web; public class Global : System.Web.HttpApplication { - private const string DataContextKey = "DataContext"; - - private const string DataContextTransactionKey = "DataContextTransaction"; - /// <summary> /// The logger for this sample to use. /// </summary> @@ -26,105 +22,6 @@ namespace WebFormsRelyingParty { get { return logger; } } - public static User LoggedInUser { - get { return Global.DataContext.AuthenticationToken.Where(token => token.ClaimedIdentifier == HttpContext.Current.User.Identity.Name).Select(token => token.User).FirstOrDefault(); } - } - - public static string ApplicationPath { - get { - string path = HttpContext.Current.Request.ApplicationPath; - if (!path.EndsWith("/")) { - path += "/"; - } - - return path; - } - } - - /// <summary> - /// Gets the transaction-protected database connection for the current request. - /// </summary> - public static DatabaseEntities DataContext { - get { - DatabaseEntities dataContext = DataContextSimple; - if (dataContext == null) { - dataContext = new DatabaseEntities(); - try { - dataContext.Connection.Open(); - } catch (EntityException entityEx) { - var sqlEx = entityEx.InnerException as SqlException; - if (sqlEx != null) { - if (sqlEx.Class == 14 && sqlEx.Number == 15350) { - // Most likely the database schema hasn't been created yet. - HttpContext.Current.Response.Redirect("~/Setup.aspx"); - } - } - - throw; - } - - DataContextTransactionSimple = dataContext.Connection.BeginTransaction(); - DataContextSimple = dataContext; - } - - return dataContext; - } - } - - private static DatabaseEntities DataContextSimple { - get { - if (HttpContext.Current != null) { - return HttpContext.Current.Items[DataContextKey] as DatabaseEntities; - } else if (OperationContext.Current != null) { - object data; - if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextKey, out data)) { - return data as DatabaseEntities; - } else { - return null; - } - } else { - throw new InvalidOperationException(); - } - } - - set { - if (HttpContext.Current != null) { - HttpContext.Current.Items[DataContextKey] = value; - } else if (OperationContext.Current != null) { - OperationContext.Current.IncomingMessageProperties[DataContextKey] = value; - } else { - throw new InvalidOperationException(); - } - } - } - - private static IDbTransaction DataContextTransactionSimple { - get { - if (HttpContext.Current != null) { - return HttpContext.Current.Items[DataContextTransactionKey] as IDbTransaction; - } else if (OperationContext.Current != null) { - object data; - if (OperationContext.Current.IncomingMessageProperties.TryGetValue(DataContextTransactionKey, out data)) { - return data as IDbTransaction; - } else { - return null; - } - } else { - throw new InvalidOperationException(); - } - } - - set { - if (HttpContext.Current != null) { - HttpContext.Current.Items[DataContextTransactionKey] = value; - } else if (OperationContext.Current != null) { - OperationContext.Current.IncomingMessageProperties[DataContextTransactionKey] = value; - } else { - throw new InvalidOperationException(); - } - } - } - protected void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); Logger.Info("Web application starting..."); @@ -137,7 +34,6 @@ namespace WebFormsRelyingParty { } protected void Application_EndRequest(object sender, EventArgs e) { - CommitAndCloseDatabaseIfNecessary(); } protected void Application_AuthenticateRequest(object sender, EventArgs e) { @@ -145,11 +41,6 @@ namespace WebFormsRelyingParty { protected void Application_Error(object sender, EventArgs e) { Logger.Error("An unhandled exception occurred in ASP.NET processing: " + Server.GetLastError(), Server.GetLastError()); - if (DataContextTransactionSimple != null) { - DataContextTransactionSimple.Rollback(); - DataContextTransactionSimple.Dispose(); - DataContextTransactionSimple = null; - } } protected void Session_End(object sender, EventArgs e) { @@ -161,19 +52,5 @@ namespace WebFormsRelyingParty { // this would be automatic, but in partial trust scenarios it is not. log4net.LogManager.Shutdown(); } - - private static void CommitAndCloseDatabaseIfNecessary() { - var dataContext = DataContextSimple; - if (dataContext != null) { - dataContext.SaveChanges(); - if (DataContextTransactionSimple != null) { - DataContextTransactionSimple.Commit(); - DataContextTransactionSimple.Dispose(); - } - - dataContext.Dispose(); - DataContextSimple = null; - } - } } }
\ No newline at end of file diff --git a/projecttemplates/WebFormsRelyingParty/LoginFrame.aspx.cs b/projecttemplates/WebFormsRelyingParty/LoginFrame.aspx.cs index 0d7e7fc..aebf266 100644 --- a/projecttemplates/WebFormsRelyingParty/LoginFrame.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/LoginFrame.aspx.cs @@ -12,6 +12,7 @@ using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; + using RelyingPartyLogic; using WebFormsRelyingParty.Code; public partial class LoginFrame : System.Web.UI.Page { @@ -51,7 +52,7 @@ private void LoginUser(string claimedIdentifier, string friendlyIdentifier, ClaimsResponse claims, Token samlToken, bool trustedEmail) { // Create an account for this user if we don't already have one. - AuthenticationToken openidToken = Global.DataContext.AuthenticationToken.FirstOrDefault(token => token.ClaimedIdentifier == claimedIdentifier); + AuthenticationToken openidToken = Database.DataContext.AuthenticationToken.FirstOrDefault(token => token.ClaimedIdentifier == claimedIdentifier); if (openidToken == null) { // this is a user we haven't seen before. User user = new User(); @@ -89,7 +90,7 @@ } } - Global.DataContext.AddToUser(user); + Database.DataContext.AddToUser(user); } bool persistentCookie = false; diff --git a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs index c3a143f..21b15d2 100644 --- a/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Members/AccountInfo.aspx.cs @@ -13,30 +13,31 @@ namespace WebFormsRelyingParty.Members { using System.Web.UI.WebControls; using DotNetOpenAuth.InfoCard; using DotNetOpenAuth.OpenId.RelyingParty; + using RelyingPartyLogic; public partial class AccountInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - Global.LoggedInUser.AuthenticationTokens.Load(); - this.Repeater1.DataSource = Global.LoggedInUser.AuthenticationTokens; + Database.LoggedInUser.AuthenticationTokens.Load(); + this.Repeater1.DataSource = Database.LoggedInUser.AuthenticationTokens; - if (!Global.LoggedInUser.IssuedToken.IsLoaded) { - Global.LoggedInUser.IssuedToken.Load(); + if (!Database.LoggedInUser.IssuedToken.IsLoaded) { + Database.LoggedInUser.IssuedToken.Load(); } - this.tokenListRepeater.DataSource = Global.LoggedInUser.IssuedToken; - foreach (var token in Global.LoggedInUser.IssuedToken) { + this.tokenListRepeater.DataSource = Database.LoggedInUser.IssuedToken; + foreach (var token in Database.LoggedInUser.IssuedToken) { if (!token.ConsumerReference.IsLoaded) { token.ConsumerReference.Load(); } } - this.authorizedClientsPanel.Visible = Global.LoggedInUser.IssuedToken.Count > 0; + this.authorizedClientsPanel.Visible = Database.LoggedInUser.IssuedToken.Count > 0; if (!IsPostBack) { this.Repeater1.DataBind(); this.tokenListRepeater.DataBind(); - this.emailBox.Text = Global.LoggedInUser.EmailAddress; - this.emailVerifiedLabel.Visible = Global.LoggedInUser.EmailAddressVerified; - this.firstNameBox.Text = Global.LoggedInUser.FirstName; - this.lastNameBox.Text = Global.LoggedInUser.LastName; + this.emailBox.Text = Database.LoggedInUser.EmailAddress; + this.emailVerifiedLabel.Visible = Database.LoggedInUser.EmailAddressVerified; + this.firstNameBox.Text = Database.LoggedInUser.FirstName; + this.lastNameBox.Text = Database.LoggedInUser.LastName; } this.firstNameBox.Focus(); @@ -48,9 +49,9 @@ namespace WebFormsRelyingParty.Members { protected void deleteOpenId_Command(object sender, CommandEventArgs e) { string claimedId = (string)e.CommandArgument; - var token = Global.DataContext.AuthenticationToken.First(t => t.ClaimedIdentifier == claimedId && t.User.Id == Global.LoggedInUser.Id); - Global.DataContext.DeleteObject(token); - Global.DataContext.SaveChanges(); + var token = Database.DataContext.AuthenticationToken.First(t => t.ClaimedIdentifier == claimedId && t.User.Id == Database.LoggedInUser.Id); + Database.DataContext.DeleteObject(token); + Database.DataContext.SaveChanges(); this.Repeater1.DataBind(); } @@ -59,10 +60,10 @@ namespace WebFormsRelyingParty.Members { return; } - Global.LoggedInUser.EmailAddress = this.emailBox.Text; - Global.LoggedInUser.FirstName = this.firstNameBox.Text; - Global.LoggedInUser.LastName = this.lastNameBox.Text; - this.emailVerifiedLabel.Visible = Global.LoggedInUser.EmailAddressVerified; + Database.LoggedInUser.EmailAddress = this.emailBox.Text; + Database.LoggedInUser.FirstName = this.firstNameBox.Text; + Database.LoggedInUser.LastName = this.lastNameBox.Text; + this.emailVerifiedLabel.Visible = Database.LoggedInUser.EmailAddressVerified; } protected void InfoCardSelector1_ReceivedToken(object sender, ReceivedTokenEventArgs e) { @@ -71,32 +72,32 @@ namespace WebFormsRelyingParty.Members { protected void revokeToken_Command(object sender, CommandEventArgs e) { string token = (string)e.CommandArgument; - var tokenToRevoke = Global.DataContext.IssuedToken.FirstOrDefault(t => t.Token == token && t.User.Id == Global.LoggedInUser.Id); + var tokenToRevoke = Database.DataContext.IssuedToken.FirstOrDefault(t => t.Token == token && t.User.Id == Database.LoggedInUser.Id); if (tokenToRevoke != null) { - Global.DataContext.DeleteObject(tokenToRevoke); + Database.DataContext.DeleteObject(tokenToRevoke); } this.tokenListRepeater.DataBind(); - this.noAuthorizedClientsPanel.Visible = Global.LoggedInUser.IssuedToken.Count == 0; + this.noAuthorizedClientsPanel.Visible = Database.LoggedInUser.IssuedToken.Count == 0; } private void AddIdentifier(string claimedId, string friendlyId) { // Check that this identifier isn't already tied to a user account. // We do this again here in case the LoggingIn event couldn't verify // and in case somehow the OP changed it anyway. - var existingToken = Global.DataContext.AuthenticationToken.FirstOrDefault(token => token.ClaimedIdentifier == claimedId); + var existingToken = Database.DataContext.AuthenticationToken.FirstOrDefault(token => token.ClaimedIdentifier == claimedId); if (existingToken == null) { var token = new AuthenticationToken(); token.ClaimedIdentifier = claimedId; token.FriendlyIdentifier = friendlyId; - Global.LoggedInUser.AuthenticationTokens.Add(token); - Global.DataContext.SaveChanges(); + Database.LoggedInUser.AuthenticationTokens.Add(token); + Database.DataContext.SaveChanges(); this.Repeater1.DataBind(); // Clear the box for the next entry this.openIdSelector.Identifier = null; } else { - if (existingToken.User == Global.LoggedInUser) { + if (existingToken.User == Database.LoggedInUser) { this.alreadyLinkedLabel.Visible = true; } else { this.differentAccountLabel.Visible = true; diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs index 044e9c0..935e8ab 100644 --- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs @@ -13,6 +13,7 @@ namespace WebFormsRelyingParty.Members { using System.Web.UI.WebControls; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.Messages; + using RelyingPartyLogic; using WebFormsRelyingParty.Code; public partial class OAuthAuthorize : System.Web.UI.Page { @@ -23,14 +24,14 @@ namespace WebFormsRelyingParty.Members { Response.Redirect("AccountInfo.aspx"); } - this.csrfCheck.Value = Utilities.SetCsrfCookie(); + this.csrfCheck.Value = Code.Utilities.SetCsrfCookie(); this.consumerNameLabel.Text = HttpUtility.HtmlEncode(OAuthServiceProvider.PendingAuthorizationConsumer.Name); OAuth10ConsumerWarning.Visible = pendingRequest.IsUnsafeRequest; serviceProviderDomainNameLabel.Text = HttpUtility.HtmlEncode(this.Request.Url.Host); this.consumerDomainNameLabel3.Text = this.consumerDomainNameLabel2.Text = this.consumerDomainNameLabel1.Text = HttpUtility.HtmlEncode(OAuthServiceProvider.PendingAuthorizationConsumer.Name); } else { - Utilities.VerifyCsrfCookie(this.csrfCheck.Value); + Code.Utilities.VerifyCsrfCookie(this.csrfCheck.Value); } } diff --git a/projecttemplates/WebFormsRelyingParty/MyTemplate.vstemplate b/projecttemplates/WebFormsRelyingParty/MyTemplate.vstemplate index d472aaa..11e4373 100644 --- a/projecttemplates/WebFormsRelyingParty/MyTemplate.vstemplate +++ b/projecttemplates/WebFormsRelyingParty/MyTemplate.vstemplate @@ -15,6 +15,12 @@ <Icon>__TemplateIcon.ico</Icon> </TemplateData> <TemplateContent> + <Project TargetFileName="RelyingPartyLogic.csproj" File="RelyingPartyLogic" ReplaceParameters="true"> + <ProjectItem ReplaceParameters="true">Class1.cs</ProjectItem> + <Folder Name="Properties" TargetFolderName="Properties"> + <ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem> + </Folder> + </Project> <Project TargetFileName="WebFormsRelyingParty.csproj" File="WebFormsRelyingParty.csproj" ReplaceParameters="true"> <Folder Name="Admin" TargetFolderName="Admin"> <ProjectItem ReplaceParameters="true" TargetFileName="Admin.Master">Admin.Master</ProjectItem> diff --git a/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs b/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs index 274b5da..e7d1619 100644 --- a/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs +++ b/projecttemplates/WebFormsRelyingParty/OAuth.ashx.cs @@ -13,6 +13,7 @@ namespace WebFormsRelyingParty { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.Messages; + using RelyingPartyLogic; using WebFormsRelyingParty.Code; /// <summary> diff --git a/projecttemplates/WebFormsRelyingParty/Setup.aspx.cs b/projecttemplates/WebFormsRelyingParty/Setup.aspx.cs index 4f73c5f..22125a4 100644 --- a/projecttemplates/WebFormsRelyingParty/Setup.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Setup.aspx.cs @@ -9,8 +9,7 @@ using System.Web.UI.WebControls; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; - using Microsoft.SqlServer.Management.Common; - using Microsoft.SqlServer.Management.Smo; + using RelyingPartyLogic; public partial class Setup : System.Web.UI.Page { private bool databaseCreated; @@ -27,7 +26,7 @@ if (e.IsDirectedIdentity) { this.noOPIdentifierLabel.Visible = true; } else if (!this.databaseCreated) { - this.CreateDatabase(e.ClaimedIdentifier, this.openidLogin.Text); + Utilities.CreateDatabase(e.ClaimedIdentifier, this.openidLogin.Text); this.MultiView1.ActiveViewIndex = 1; // indicate we have already created the database so that if the @@ -36,29 +35,5 @@ this.databaseCreated = true; } } - - private void CreateDatabase(Identifier claimedId, string friendlyId) { - const string SqlFormat = @" -CREATE DATABASE [{0}] ON (NAME='{0}', FILENAME='{0}') -GO -USE ""{0}"" -GO -{1} -EXEC [dbo].[AddUser] 'admin', 'admin', '{2}', '{3}' -GO -"; - string databasePath = HttpContext.Current.Server.MapPath("~/App_Data/Database.mdf"); - string schemaSql = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Admin/CreateDatabase.sql")); - string sql = string.Format(CultureInfo.InvariantCulture, SqlFormat, databasePath, schemaSql, claimedId, "Admin"); - - var serverConnection = new ServerConnection(".\\sqlexpress"); - try { - serverConnection.ExecuteNonQuery(sql); - var server = new Server(serverConnection); - server.DetachDatabase(databasePath, true); - } finally { - serverConnection.Disconnect(); - } - } } } diff --git a/projecttemplates/WebFormsRelyingParty/Site.Master b/projecttemplates/WebFormsRelyingParty/Site.Master index f4e1a25..3cf191e 100644 --- a/projecttemplates/WebFormsRelyingParty/Site.Master +++ b/projecttemplates/WebFormsRelyingParty/Site.Master @@ -1,6 +1,6 @@ <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebFormsRelyingParty.Site" %> -<%@ Import Namespace="WebFormsRelyingParty" %> +<%@ Import Namespace="RelyingPartyLogic" %> <%@ Import Namespace="System.Linq" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> @@ -16,7 +16,7 @@ <asp:LoginView runat="server"> <LoggedInTemplate> <% - var authToken = Global.DataContext.AuthenticationToken.Include("User").First(token => token.ClaimedIdentifier == Page.User.Identity.Name); + var authToken = Database.DataContext.AuthenticationToken.Include("User").First(token => token.ClaimedIdentifier == Page.User.Identity.Name); if (!string.IsNullOrEmpty(authToken.User.EmailAddress)) { Response.Write(HttpUtility.HtmlEncode(authToken.User.EmailAddress)); } else if (!string.IsNullOrEmpty(authToken.User.FirstName)) { diff --git a/projecttemplates/WebFormsRelyingParty/Web.config b/projecttemplates/WebFormsRelyingParty/Web.config index b38a25a..e02090d 100644 --- a/projecttemplates/WebFormsRelyingParty/Web.config +++ b/projecttemplates/WebFormsRelyingParty/Web.config @@ -129,11 +129,12 @@ </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> - <add name="OAuthAuthenticationModule" type="WebFormsRelyingParty.Code.OAuthAuthenticationModule" /> + <add name="OAuthAuthenticationModule" type="RelyingPartyLogic.OAuthAuthenticationModule, RelyingPartyLogic" /> + <add name="Database" type="RelyingPartyLogic.Database, RelyingPartyLogic"/> </httpModules> <roleManager enabled="true" defaultProvider="Database"> <providers> - <add name="Database" type="WebFormsRelyingParty.Code.DataRoleProvider" /> + <add name="Database" type="RelyingPartyLogic.DataRoleProvider, RelyingPartyLogic" /> </providers> </roleManager> </system.web> diff --git a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj index b1ba4b7..ec8543d 100644 --- a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj +++ b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj @@ -34,9 +34,6 @@ <SpecificVersion>False</SpecificVersion> <HintPath>..\..\lib\log4net.dll</HintPath> </Reference> - <Reference Include="Microsoft.SqlServer.ConnectionInfo" /> - <Reference Include="Microsoft.SqlServer.Smo" /> - <Reference Include="Microsoft.SqlServer.Management.Sdk.Sfc" /> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Core"> @@ -87,14 +84,6 @@ <Content Include="Web.config" /> </ItemGroup> <ItemGroup> - <Compile Include="Code\OAuthAuthenticationModule.cs" /> - <Compile Include="Code\OAuthAuthorizationManager.cs" /> - <Compile Include="Code\OAuthConsumerTokenManager.cs" /> - <Compile Include="Code\OAuthPrincipalAuthorizationPolicy.cs" /> - <Compile Include="Code\OAuthServiceProvider.cs" /> - <Compile Include="Code\OAuthServiceProviderTokenManager.cs" /> - <Compile Include="Code\OAuthTokenManager.cs" /> - <Compile Include="Code\Policies.cs" /> <Compile Include="Code\Utilities.cs" /> <Compile Include="Members\OAuthAuthorize.aspx.cs"> <DependentUpon>OAuthAuthorize.aspx</DependentUpon> @@ -103,10 +92,6 @@ <Compile Include="Members\OAuthAuthorize.aspx.designer.cs"> <DependentUpon>OAuthAuthorize.aspx</DependentUpon> </Compile> - <Compile Include="Model.IssuedRequestToken.cs" /> - <Compile Include="Model.IssuedAccessToken.cs" /> - <Compile Include="Model.Consumer.cs" /> - <Compile Include="Model.User.cs" /> <Compile Include="LoginFrame.aspx.cs"> <DependentUpon>LoginFrame.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -166,22 +151,10 @@ <Compile Include="Members\Default.aspx.designer.cs"> <DependentUpon>Default.aspx</DependentUpon> </Compile> - <Compile Include="Model.AuthenticationToken.cs" /> - <Compile Include="Model.Designer.cs"> - <AutoGen>True</AutoGen> - <DesignTime>True</DesignTime> - <DependentUpon>Model.edmx</DependentUpon> - </Compile> <Compile Include="OAuth.ashx.cs"> <DependentUpon>OAuth.ashx</DependentUpon> </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> - <EntityDeploy Include="Model.edmx"> - <Generator>EntityModelCodeGenerator</Generator> - <LastGenOutput>Model.Designer.cs</LastGenOutput> - </EntityDeploy> - <Compile Include="Code\DataRoleProvider.cs"> - </Compile> <Compile Include="Setup.aspx.cs"> <DependentUpon>Setup.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -265,7 +238,8 @@ <Content Include="xrds.aspx" /> </ItemGroup> <ItemGroup> - <None Include="Admin\CreateDatabase.sql" /> + <Content Include="bin\RelyingPartyLogic.dll" /> + <Content Include="bin\RelyingPartyLogic.pdb" /> <Content Include="Members\OAuthAuthorize.aspx" /> <Content Include="OAuth.ashx" /> </ItemGroup> @@ -274,6 +248,10 @@ <Project>{3191B653-F76D-4C1A-9A5A-347BC3AAAAB7}</Project> <Name>DotNetOpenAuth</Name> </ProjectReference> + <ProjectReference Include="..\RelyingPartyLogic\RelyingPartyLogic.csproj"> + <Project>{17932639-1F50-48AF-B0A5-E2BF832F82CC}</Project> + <Name>RelyingPartyLogic</Name> + </ProjectReference> </ItemGroup> <ItemGroup> <Folder Include="App_Data\" /> |