Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,56 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Configuration;
using System.Web.Security;
namespace WebMatrix.WebData
{
internal static class ConfigUtil
{
private static bool _simpleMembershipEnabled = IsSimpleMembershipEnabled();
private static string _loginUrl = GetLoginUrl();
public static bool SimpleMembershipEnabled
{
get { return _simpleMembershipEnabled; }
}
public static string LoginUrl
{
get { return _loginUrl; }
}
private static string GetLoginUrl()
{
return ConfigurationManager.AppSettings[FormsAuthenticationSettings.LoginUrlKey] ??
(ShouldPreserveLoginUrl() ? FormsAuthentication.LoginUrl : FormsAuthenticationSettings.DefaultLoginUrl);
}
private static bool IsSimpleMembershipEnabled()
{
string settingValue = ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey];
bool enabled;
if (!String.IsNullOrEmpty(settingValue) && Boolean.TryParse(settingValue, out enabled))
{
return enabled;
}
// Simple Membership is enabled by default, but attempts to delegate to the current provider if not initialized.
return true;
}
private static bool ShouldPreserveLoginUrl()
{
string settingValue = ConfigurationManager.AppSettings[FormsAuthenticationSettings.PreserveLoginUrlKey];
bool preserveLoginUrl;
if (!String.IsNullOrEmpty(settingValue) && Boolean.TryParse(settingValue, out preserveLoginUrl))
{
return preserveLoginUrl;
}
// For backwards compatible with WebPages 1.0, we override the loginUrl value if
// the PreserveLoginUrl key is not present.
return false;
}
}
}

View File

@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using WebMatrix.Data;
namespace WebMatrix.WebData
{
internal class DatabaseConnectionInfo
{
private string _connectionStringName;
private string _connectionString;
private enum ConnectionType
{
ConnectionStringName = 0,
ConnectionString = 1
}
public string ConnectionString
{
get { return _connectionString; }
set
{
_connectionString = value;
Type = ConnectionType.ConnectionString;
}
}
public string ConnectionStringName
{
get { return _connectionStringName; }
set
{
_connectionStringName = value;
Type = ConnectionType.ConnectionStringName;
}
}
public string ProviderName { get; set; }
private ConnectionType Type { get; set; }
public Database Connect()
{
switch (Type)
{
case ConnectionType.ConnectionString:
return Database.OpenConnectionString(ConnectionString, ProviderName);
case ConnectionType.ConnectionStringName:
return Database.Open(ConnectionStringName);
default:
return null;
}
}
}
}

View File

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using WebMatrix.Data;
namespace WebMatrix.WebData
{
internal class DatabaseWrapper : IDatabase
{
private readonly Database _database;
public DatabaseWrapper(Database database)
{
_database = database;
}
public dynamic QuerySingle(string commandText, params object[] parameters)
{
return _database.QuerySingle(commandText, parameters);
}
public IEnumerable<dynamic> Query(string commandText, params object[] parameters)
{
return _database.Query(commandText, parameters);
}
public dynamic QueryValue(string commandText, params object[] parameters)
{
return _database.QueryValue(commandText, parameters);
}
public int Execute(string commandText, params object[] parameters)
{
return _database.Execute(commandText, parameters);
}
public void Dispose()
{
_database.Dispose();
}
}
}

View File

@ -0,0 +1,95 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Web.Security;
namespace WebMatrix.WebData
{
public abstract class ExtendedMembershipProvider : MembershipProvider
{
private const int OneDayInMinutes = 24 * 60;
/// <summary>
/// Deletes the OAuth and OpenID account with the specified provider name and provider user id.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="providerUserId">The provider user id.</param>
public abstract void DeleteOAuthAccount(string provider, string providerUserId);
/// <summary>
/// Creates a new OAuth account with the specified data or update an existing one if it already exists.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="providerUserId">The provider userid.</param>
/// <param name="userName">The username.</param>
public abstract void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName);
/// <summary>
/// Gets the id of the user with the specified provider name and provider user id.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="providerUserId">The provider user id.</param>
/// <returns></returns>
public abstract int GetUserIdFromOAuth(string provider, string providerUserId);
/// <summary>
/// Gets the username of a user with the given id
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns></returns>
public abstract string GetUserNameFromId(int userId);
/// <summary>
/// Gets all OAuth accounts associated with the specified username
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <returns></returns>
public abstract ICollection<OAuthAccountData> GetAccountsForUser(string userName);
public virtual string CreateUserAndAccount(string userName, string password)
{
return CreateUserAndAccount(userName, password, requireConfirmation: false, values: null);
}
public virtual string CreateUserAndAccount(string userName, string password, bool requireConfirmation)
{
return CreateUserAndAccount(userName, password, requireConfirmation, values: null);
}
public virtual string CreateUserAndAccount(string userName, string password, IDictionary<string, object> values)
{
return CreateUserAndAccount(userName, password, requireConfirmation: false, values: values);
}
public abstract string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values);
public virtual string CreateAccount(string userName, string password)
{
return CreateAccount(userName, password, requireConfirmationToken: false);
}
public abstract string CreateAccount(string userName, string password, bool requireConfirmationToken);
public abstract bool ConfirmAccount(string userName, string accountConfirmationToken);
public abstract bool ConfirmAccount(string accountConfirmationToken);
public abstract bool DeleteAccount(string userName);
public virtual string GeneratePasswordResetToken(string userName)
{
return GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow: OneDayInMinutes);
}
public abstract string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow);
public abstract int GetUserIdFromPasswordResetToken(string token);
public abstract bool IsConfirmed(string userName);
public abstract bool ResetPasswordWithToken(string token, string newPassword);
public abstract int GetPasswordFailuresSinceLastSuccess(string userName);
public abstract DateTime GetCreateDate(string userName);
public abstract DateTime GetPasswordChangedDate(string userName);
public abstract DateTime GetLastPasswordFailureDate(string userName);
internal virtual void VerifyInitialized()
{
}
}
}

View File

@ -0,0 +1,21 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
namespace WebMatrix.WebData
{
/// <summary>
/// Defines key names for use in a web.config &lt;appSettings&gt; section to override default settings.
/// </summary>
public static class FormsAuthenticationSettings
{
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "The term Login is used more frequently in ASP.Net")]
public static readonly string LoginUrlKey = "loginUrl";
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "The term Login is used more frequently in ASP.Net")]
public static readonly string DefaultLoginUrl = "~/Account/Login";
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "The term Login is used more frequently in ASP.Net")]
public static readonly string PreserveLoginUrlKey = "PreserveLoginUrl";
}
}

View File

@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Username", Scope = "member", Target = "WebMatrix.WebData.ExtendedMembershipProvider.#GetUsernameFromId(System.Int32)", Justification = "Username is one word.")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "username", Scope = "member", Target = "WebMatrix.WebData.ExtendedMembershipProvider.#GetAccountsForUser(System.String)", Justification = "Username is one word.")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "username", Scope = "member", Target = "WebMatrix.WebData.ExtendedMembershipProvider.#CreateOrUpdateOAuthAccount(System.String,System.String,System.String)", Justification = "Username is one word.")]

View File

@ -0,0 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace WebMatrix.WebData
{
internal interface IDatabase : IDisposable
{
dynamic QuerySingle(string commandText, params object[] args);
IEnumerable<dynamic> Query(string commandText, params object[] parameters);
dynamic QueryValue(string commandText, params object[] parameters);
int Execute(string commandText, params object[] args);
}
}

View File

@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Globalization;
using Microsoft.Internal.Web.Utils;
namespace WebMatrix.WebData
{
/// <summary>
/// Represents an OpenAuth and OpenID account.
/// </summary>
public class OAuthAccountData
{
/// <summary>
/// Initializes a new instance of the <see cref="OAuthAccountData"/> class.
/// </summary>
/// <param name="provider">The provider.</param>
/// <param name="providerUserId">The provider user id.</param>
public OAuthAccountData(string provider, string providerUserId)
{
if (String.IsNullOrEmpty(provider))
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "provider"),
"provider");
}
if (String.IsNullOrEmpty(providerUserId))
{
throw new ArgumentException(
String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, "providerUserId"),
"providerUserId");
}
Provider = provider;
ProviderUserId = providerUserId;
}
/// <summary>
/// Gets the provider name.
/// </summary>
public string Provider { get; private set; }
/// <summary>
/// Gets the provider user id.
/// </summary>
public string ProviderUserId { get; private set; }
}
}

View File

@ -0,0 +1,83 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Specialized;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Web.WebPages;
using System.Web.WebPages.Razor;
using WebMatrix.Data;
namespace WebMatrix.WebData
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class PreApplicationStartCode
{
// NOTE: Do not add public fields, methods, or other members to this class.
// This class does not show up in Intellisense so members on it will not be
// discoverable by users. Place new members on more appropriate classes that
// relate to the public API (for example, a LoginUrl property should go on a
// membership-related class).
private static bool _startWasCalled;
public static void Start()
{
// Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from
// another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the
// order so we have to guard against multiple calls.
// All Start calls are made on same thread, so no lock needed here.
if (_startWasCalled)
{
return;
}
_startWasCalled = true;
// Summary of Simple Membership startup behavior:
// 1. If the appSetting enabledSimpleMembership is present and equal to "false", NEITHER SimpleMembership NOR AutoFormsAuth are activated
// 2. If the appSetting is true, a non-boolean string or not present, BOTH may be activated
// a. SimpleMembership ONLY replaces the AspNetSqlMemberhipProvider, but it does replace it even if it isn't the default. This
// means that anything accessing this provider by name will get Simple Membership, but if this provider is no longer the default
// then SimpleMembership does not affect the default
// b. SimpleMembership delegates to the previous default provider UNLESS WebSecurity.InitializeDatabaseConnection is called.
// Initialize membership provider
WebSecurity.PreAppStartInit();
// Initialize Forms Authentication default configuration
SetUpFormsAuthentication();
// Wire up WebMatrix.Data's Database object to the ASP.NET Web Pages resource tracker
Database.ConnectionOpened += OnConnectionOpened;
// Auto import the WebMatrix.Data and WebMatrix.WebData namespaces to all apps that are executing.
WebPageRazorHost.AddGlobalImport("WebMatrix.Data");
WebPageRazorHost.AddGlobalImport("WebMatrix.WebData");
}
private static void OnConnectionOpened(object sender, ConnectionEventArgs e)
{
// Register all open connections for disposing at the end of the request
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(httpContext);
httpContextWrapper.RegisterForDispose(e.Connection);
}
}
private static void SetUpFormsAuthentication()
{
if (ConfigUtil.SimpleMembershipEnabled)
{
// Allow use of <add key="loginUrl" value="~/MyPath/LogOn" /> as a shortcut to specify
// a custom log in url
FormsAuthentication.EnableFormsAuthentication(new NameValueCollection()
{
{ "loginUrl", ConfigUtil.LoginUrl }
});
}
}
}
}

View File

@ -0,0 +1,16 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Web;
using WebMatrix.WebData;
// 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("WebMatrix.WebData")]
[assembly: AssemblyDescription("")]
[assembly: InternalsVisibleTo("WebPages.Functional.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("WebMatrix.WebData.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]

View File

@ -0,0 +1,189 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.214
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebMatrix.WebData.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class WebDataResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal WebDataResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WebMatrix.WebData.Resources.WebDataResources", typeof(WebDataResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Database operation failed..
/// </summary>
internal static string Security_DbFailure {
get {
return ResourceManager.GetString("Security_DbFailure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No user table found that has the name &quot;{0}&quot;..
/// </summary>
internal static string Security_FailedToFindUserTable {
get {
return ResourceManager.GetString("Security_FailedToFindUserTable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The &quot;WebSecurity.InitializeDatabaseConnection&quot; method can be called only once..
/// </summary>
internal static string Security_InitializeAlreadyCalled {
get {
return ResourceManager.GetString("Security_InitializeAlreadyCalled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You must call the &quot;WebSecurity.InitializeDatabaseConnection&quot; method before you call any other method of the &quot;WebSecurity&quot; class. This call should be placed in an _AppStart.cshtml file in the root of your site..
/// </summary>
internal static string Security_InitializeMustBeCalledFirst {
get {
return ResourceManager.GetString("Security_InitializeMustBeCalledFirst", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No account exists for &quot;{0}&quot;..
/// </summary>
internal static string Security_NoAccountFound {
get {
return ResourceManager.GetString("Security_NoAccountFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to To call this method, the &quot;Membership.Provider&quot; property must be an instance of &quot;ExtendedMembershipProvider&quot;..
/// </summary>
internal static string Security_NoExtendedMembershipProvider {
get {
return ResourceManager.GetString("Security_NoExtendedMembershipProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No user found was found that has the name &quot;{0}&quot;..
/// </summary>
internal static string Security_NoUserFound {
get {
return ResourceManager.GetString("Security_NoUserFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The membership password is too long. (Maximum length is 128 characters)..
/// </summary>
internal static string SimpleMembership_PasswordTooLong {
get {
return ResourceManager.GetString("SimpleMembership_PasswordTooLong", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Provider unrecognized attribute: &quot;{0}&quot;..
/// </summary>
internal static string SimpleMembership_ProviderUnrecognizedAttribute {
get {
return ResourceManager.GetString("SimpleMembership_ProviderUnrecognizedAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The role &quot;{0}&quot; cannot be deleted because there are still users in the role..
/// </summary>
internal static string SimpleRoleProvder_RolePopulated {
get {
return ResourceManager.GetString("SimpleRoleProvder_RolePopulated", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User &quot;{0}&quot; is already in role &quot;{1}&quot;..
/// </summary>
internal static string SimpleRoleProvder_UserAlreadyInRole {
get {
return ResourceManager.GetString("SimpleRoleProvder_UserAlreadyInRole", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User &quot;{0}&quot; is not in role &quot;{1}&quot;..
/// </summary>
internal static string SimpleRoleProvder_UserNotInRole {
get {
return ResourceManager.GetString("SimpleRoleProvder_UserNotInRole", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No role found that has the name &quot;{0}&quot;..
/// </summary>
internal static string SimpleRoleProvider_NoRoleFound {
get {
return ResourceManager.GetString("SimpleRoleProvider_NoRoleFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Role &quot;{0}&quot; already exists..
/// </summary>
internal static string SimpleRoleProvider_RoleExists {
get {
return ResourceManager.GetString("SimpleRoleProvider_RoleExists", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Security_DbFailure" xml:space="preserve">
<value>Database operation failed.</value>
</data>
<data name="Security_FailedToFindUserTable" xml:space="preserve">
<value>No user table found that has the name "{0}".</value>
</data>
<data name="Security_InitializeAlreadyCalled" xml:space="preserve">
<value>The "WebSecurity.InitializeDatabaseConnection" method can be called only once.</value>
</data>
<data name="Security_InitializeMustBeCalledFirst" xml:space="preserve">
<value>You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.</value>
</data>
<data name="Security_NoAccountFound" xml:space="preserve">
<value>No account exists for "{0}".</value>
</data>
<data name="Security_NoExtendedMembershipProvider" xml:space="preserve">
<value>To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".</value>
</data>
<data name="Security_NoUserFound" xml:space="preserve">
<value>No user found was found that has the name "{0}".</value>
</data>
<data name="SimpleMembership_PasswordTooLong" xml:space="preserve">
<value>The membership password is too long. (Maximum length is 128 characters).</value>
</data>
<data name="SimpleMembership_ProviderUnrecognizedAttribute" xml:space="preserve">
<value>Provider unrecognized attribute: "{0}".</value>
</data>
<data name="SimpleRoleProvder_RolePopulated" xml:space="preserve">
<value>The role "{0}" cannot be deleted because there are still users in the role.</value>
</data>
<data name="SimpleRoleProvder_UserAlreadyInRole" xml:space="preserve">
<value>User "{0}" is already in role "{1}".</value>
</data>
<data name="SimpleRoleProvder_UserNotInRole" xml:space="preserve">
<value>User "{0}" is not in role "{1}".</value>
</data>
<data name="SimpleRoleProvider_NoRoleFound" xml:space="preserve">
<value>No role found that has the name "{0}".</value>
</data>
<data name="SimpleRoleProvider_RoleExists" xml:space="preserve">
<value>Role "{0}" already exists.</value>
</data>
</root>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,421 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Globalization;
using System.Linq;
using System.Web.Security;
using WebMatrix.WebData.Resources;
namespace WebMatrix.WebData
{
public class SimpleRoleProvider : RoleProvider
{
private RoleProvider _previousProvider;
public SimpleRoleProvider()
: this(null)
{
}
public SimpleRoleProvider(RoleProvider previousProvider)
{
_previousProvider = previousProvider;
}
private RoleProvider PreviousProvider
{
get
{
if (_previousProvider == null)
{
throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);
}
else
{
return _previousProvider;
}
}
}
private string SafeUserTableName
{
get { return "[" + UserTableName + "]"; }
}
private string SafeUserNameColumn
{
get { return "[" + UserNameColumn + "]"; }
}
private string SafeUserIdColumn
{
get { return "[" + UserIdColumn + "]"; }
}
internal static string RoleTableName
{
get { return "webpages_Roles"; }
}
internal static string UsersInRoleTableName
{
get { return "webpages_UsersInRoles"; }
}
// represents the User table for the app
public string UserTableName { get; set; }
// represents the User created UserName column, i.e. Email
public string UserNameColumn { get; set; }
// Represents the User created id column, i.e. ID;
// REVIEW: we could get this from the primary key of UserTable in the future
public string UserIdColumn { get; set; }
internal DatabaseConnectionInfo ConnectionInfo { get; set; }
internal bool InitializeCalled { get; set; }
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override string ApplicationName
{
get
{
if (InitializeCalled)
{
throw new NotSupportedException();
}
else
{
return PreviousProvider.ApplicationName;
}
}
set
{
if (InitializeCalled)
{
throw new NotSupportedException();
}
else
{
PreviousProvider.ApplicationName = value;
}
}
}
private void VerifyInitialized()
{
if (!InitializeCalled)
{
throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);
}
}
private IDatabase ConnectToDatabase()
{
return new DatabaseWrapper(ConnectionInfo.Connect());
}
internal void CreateTablesIfNeeded()
{
using (var db = ConnectToDatabase())
{
if (!SimpleMembershipProvider.CheckTableExists(db, RoleTableName))
{
db.Execute(@"CREATE TABLE " + RoleTableName + @" (
RoleId int NOT NULL PRIMARY KEY IDENTITY,
RoleName nvarchar(256) NOT NULL UNIQUE)");
db.Execute(@"CREATE TABLE " + UsersInRoleTableName + @" (
UserId int NOT NULL,
RoleId int NOT NULL,
PRIMARY KEY (UserId, RoleId),
CONSTRAINT fk_UserId FOREIGN KEY (UserId) REFERENCES " + SafeUserTableName + "(" + SafeUserIdColumn + @"),
CONSTRAINT fk_RoleId FOREIGN KEY (RoleId) REFERENCES " + RoleTableName + "(RoleId) )");
}
}
}
private List<int> GetUserIdsFromNames(IDatabase db, string[] usernames)
{
List<int> userIds = new List<int>(usernames.Length);
foreach (string username in usernames)
{
int id = SimpleMembershipProvider.GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, username);
if (id == -1)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));
}
userIds.Add(id);
}
return userIds;
}
private static List<int> GetRoleIdsFromNames(IDatabase db, string[] roleNames)
{
List<int> roleIds = new List<int>(roleNames.Length);
foreach (string role in roleNames)
{
int id = FindRoleId(db, role);
if (id == -1)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvider_NoRoleFound, role));
}
roleIds.Add(id);
}
return roleIds;
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
if (!InitializeCalled)
{
PreviousProvider.AddUsersToRoles(usernames, roleNames);
}
else
{
using (var db = ConnectToDatabase())
{
int userCount = usernames.Length;
int roleCount = roleNames.Length;
List<int> userIds = GetUserIdsFromNames(db, usernames);
List<int> roleIds = GetRoleIdsFromNames(db, roleNames);
// Generate a INSERT INTO for each userid/rowid combination, where userIds are the first params, and roleIds follow
for (int uId = 0; uId < userCount; uId++)
{
for (int rId = 0; rId < roleCount; rId++)
{
if (IsUserInRole(usernames[uId], roleNames[rId]))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvder_UserAlreadyInRole, usernames[uId], roleNames[rId]));
}
// REVIEW: is there a way to batch up these inserts?
int rows = db.Execute("INSERT INTO " + UsersInRoleTableName + " VALUES (" + userIds[uId] + "," + roleIds[rId] + "); ");
if (rows != 1)
{
throw new ProviderException(WebDataResources.Security_DbFailure);
}
}
}
}
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override void CreateRole(string roleName)
{
if (!InitializeCalled)
{
PreviousProvider.CreateRole(roleName);
}
else
{
using (var db = ConnectToDatabase())
{
int roleId = FindRoleId(db, roleName);
if (roleId != -1)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WebDataResources.SimpleRoleProvider_RoleExists, roleName));
}
int rows = db.Execute("INSERT INTO " + RoleTableName + " (RoleName) VALUES (@0)", roleName);
if (rows != 1)
{
throw new ProviderException(WebDataResources.Security_DbFailure);
}
}
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
if (!InitializeCalled)
{
return PreviousProvider.DeleteRole(roleName, throwOnPopulatedRole);
}
using (var db = ConnectToDatabase())
{
int roleId = FindRoleId(db, roleName);
if (roleId == -1)
{
return false;
}
if (throwOnPopulatedRole)
{
int usersInRole = db.Query(@"SELECT * FROM " + UsersInRoleTableName + " WHERE (RoleId = @0)", roleId).Count();
if (usersInRole > 0)
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WebDataResources.SimpleRoleProvder_RolePopulated, roleName));
}
}
else
{
// Delete any users in this role first
db.Execute(@"DELETE FROM " + UsersInRoleTableName + " WHERE (RoleId = @0)", roleId);
}
int rows = db.Execute(@"DELETE FROM " + RoleTableName + " WHERE (RoleId = @0)", roleId);
return (rows == 1); // REVIEW: should this ever be > 1?
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
if (!InitializeCalled)
{
return PreviousProvider.FindUsersInRole(roleName, usernameToMatch);
}
using (var db = ConnectToDatabase())
{
// REVIEW: Is there any way to directly get out a string[]?
List<dynamic> userNames = db.Query(@"SELECT u." + SafeUserNameColumn + " FROM " + SafeUserTableName + " u, " + UsersInRoleTableName + " ur, " + RoleTableName + " r Where (r.RoleName = @0 and ur.RoleId = r.RoleId and ur.UserId = u." + SafeUserIdColumn + " and u." + SafeUserNameColumn + " LIKE @1)", new object[] { roleName, usernameToMatch }).ToList();
string[] users = new string[userNames.Count];
for (int i = 0; i < userNames.Count; i++)
{
users[i] = (string)userNames[i][0];
}
return users;
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override string[] GetAllRoles()
{
if (!InitializeCalled)
{
return PreviousProvider.GetAllRoles();
}
using (var db = ConnectToDatabase())
{
return db.Query(@"SELECT RoleName FROM " + RoleTableName).Select<dynamic, string>(d => (string)d[0]).ToArray();
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override string[] GetRolesForUser(string username)
{
if (!InitializeCalled)
{
return PreviousProvider.GetRolesForUser(username);
}
using (var db = ConnectToDatabase())
{
int userId = SimpleMembershipProvider.GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, username);
if (userId == -1)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));
}
string query = @"SELECT r.RoleName FROM " + UsersInRoleTableName + " u, " + RoleTableName + " r Where (u.UserId = @0 and u.RoleId = r.RoleId) GROUP BY RoleName";
return db.Query(query, new object[] { userId }).Select<dynamic, string>(d => (string)d[0]).ToArray();
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override string[] GetUsersInRole(string roleName)
{
if (!InitializeCalled)
{
return PreviousProvider.GetUsersInRole(roleName);
}
using (var db = ConnectToDatabase())
{
string query = @"SELECT u." + SafeUserNameColumn + " FROM " + SafeUserTableName + " u, " + UsersInRoleTableName + " ur, " + RoleTableName + " r Where (r.RoleName = @0 and ur.RoleId = r.RoleId and ur.UserId = u." + SafeUserIdColumn + ")";
return db.Query(query, new object[] { roleName }).Select<dynamic, string>(d => (string)d[0]).ToArray();
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override bool IsUserInRole(string username, string roleName)
{
if (!InitializeCalled)
{
return PreviousProvider.IsUserInRole(username, roleName);
}
using (var db = ConnectToDatabase())
{
var count = db.QuerySingle("SELECT COUNT(*) FROM " + SafeUserTableName + " u, " + UsersInRoleTableName + " ur, " + RoleTableName + " r Where (u." + SafeUserNameColumn + " = @0 and r.RoleName = @1 and ur.RoleId = r.RoleId and ur.UserId = u." + SafeUserIdColumn + ")", username, roleName);
return (count[0] == 1);
}
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
if (!InitializeCalled)
{
PreviousProvider.RemoveUsersFromRoles(usernames, roleNames);
}
else
{
foreach (string rolename in roleNames)
{
if (!RoleExists(rolename))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvider_NoRoleFound, rolename));
}
}
foreach (string username in usernames)
{
foreach (string rolename in roleNames)
{
if (!IsUserInRole(username, rolename))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvder_UserNotInRole, username, rolename));
}
}
}
using (var db = ConnectToDatabase())
{
List<int> userIds = GetUserIdsFromNames(db, usernames);
List<int> roleIds = GetRoleIdsFromNames(db, roleNames);
foreach (int userId in userIds)
{
foreach (int roleId in roleIds)
{
// Review: Is there a way to do these all in one query?
int rows = db.Execute("DELETE FROM " + UsersInRoleTableName + " WHERE UserId = " + userId + " and RoleId = " + roleId);
if (rows != 1)
{
throw new ProviderException(WebDataResources.Security_DbFailure);
}
}
}
}
}
}
private static int FindRoleId(IDatabase db, string roleName)
{
var result = db.QuerySingle(@"SELECT RoleId FROM " + RoleTableName + " WHERE (RoleName = @0)", roleName);
if (result == null)
{
return -1;
}
return (int)result[0];
}
// Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized
public override bool RoleExists(string roleName)
{
if (!InitializeCalled)
{
return PreviousProvider.RoleExists(roleName);
}
using (var db = ConnectToDatabase())
{
return (FindRoleId(db, roleName) != -1);
}
}
}
}

View File

@ -0,0 +1,130 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\tools\WebStack.settings.targets" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<CodeAnalysis Condition=" '$(CodeAnalysis)' == '' ">false</CodeAnalysis>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{55A15F40-1435-4248-A7F2-2A146BB83586}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>WebMatrix.WebData</RootNamespace>
<AssemblyName>WebMatrix.WebData</AssemblyName>
<FileAlignment>512</FileAlignment>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;ASPNETWEBPAGES</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\bin\Release\</OutputPath>
<DefineConstants>TRACE;ASPNETWEBPAGES</DefineConstants>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>
<DocumentationFile>$(OutputPath)\$(AssemblyName).xml</DocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'CodeCoverage|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\bin\CodeCoverage\</OutputPath>
<DefineConstants>TRACE;DEBUG;CODE_COVERAGE;ASPNETWEBPAGES</DefineConstants>
<DebugType>full</DebugType>
<CodeAnalysisRuleSet>..\Strict.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\CommonAssemblyInfo.cs">
<Link>Properties\CommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="..\CommonResources.Designer.cs">
<Link>Common\CommonResources.Designer.cs</Link>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>CommonResources.resx</DependentUpon>
</Compile>
<Compile Include="..\ExceptionHelper.cs">
<Link>ExceptionHelper.cs</Link>
</Compile>
<Compile Include="..\GlobalSuppressions.cs">
<Link>Common\GlobalSuppressions.cs</Link>
</Compile>
<Compile Include="..\TransparentCommonAssemblyInfo.cs">
<Link>Properties\TransparentCommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="ConfigUtil.cs" />
<Compile Include="DatabaseConnectionInfo.cs" />
<Compile Include="DatabaseWrapper.cs" />
<Compile Include="ExtendedMembershipProvider.cs" />
<Compile Include="FormsAuthenticationSettings.cs" />
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="IDatabase.cs" />
<Compile Include="OAuthAccountData.cs" />
<Compile Include="PreApplicationStartCode.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Resources\WebDataResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>WebDataResources.resx</DependentUpon>
</Compile>
<Compile Include="SimpleMembershipProvider.cs" />
<Compile Include="SimpleRoleProvider.cs" />
<Compile Include="WebSecurity.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\System.Web.Helpers\System.Web.Helpers.csproj">
<Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>
<Name>System.Web.Helpers</Name>
</ProjectReference>
<ProjectReference Include="..\System.Web.Razor\System.Web.Razor.csproj">
<Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>
<Name>System.Web.Razor</Name>
</ProjectReference>
<ProjectReference Include="..\System.Web.WebPages.Razor\System.Web.WebPages.Razor.csproj">
<Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>
<Name>System.Web.WebPages.Razor</Name>
</ProjectReference>
<ProjectReference Include="..\System.Web.WebPages\System.Web.WebPages.csproj">
<Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>
<Name>System.Web.WebPages</Name>
</ProjectReference>
<ProjectReference Include="..\WebMatrix.Data\WebMatrix.Data.csproj">
<Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>
<Name>WebMatrix.Data</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\CommonResources.resx">
<Link>Common\CommonResources.resx</Link>
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>CommonResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Include="Resources\WebDataResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>WebDataResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDictionary Include="..\CodeAnalysisDictionary.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,425 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.WebPages;
using WebMatrix.WebData.Resources;
namespace WebMatrix.WebData
{
public static class WebSecurity
{
public static readonly string EnableSimpleMembershipKey = "enableSimpleMembership";
/// <summary>
/// Gets a value indicating whether the <see cref="M:InitializeDatabaseConnection"/> method has been initialized.
/// </summary>
/// <value>
/// <c>true</c> if initialized; otherwise, <c>false</c>.
/// </value>
public static bool Initialized { get; private set; }
public static int CurrentUserId
{
get { return GetUserId(CurrentUserName); }
}
public static string CurrentUserName
{
get { return Context.User.Identity.Name; }
}
public static bool HasUserId
{
get { return CurrentUserId != -1; }
}
public static bool IsAuthenticated
{
get { return Request.IsAuthenticated; }
}
internal static HttpContextBase Context
{
get { return new HttpContextWrapper(HttpContext.Current); }
}
internal static HttpRequestBase Request
{
get { return Context.Request; }
}
internal static HttpResponseBase Response
{
get { return Context.Response; }
}
internal static void PreAppStartInit()
{
// Allow use of <add key="EnableSimpleMembershipKey" value="false" /> to disable registration of membership/role providers as default.
if (ConfigUtil.SimpleMembershipEnabled)
{
// called during PreAppStart, should also hook up the config for MembershipProviders?
// Replace the AspNetSqlMembershipProvider (which is the default that is registered in root web.config)
const string BuiltInMembershipProviderName = "AspNetSqlMembershipProvider";
var builtInMembership = Membership.Providers[BuiltInMembershipProviderName];
if (builtInMembership != null)
{
var simpleMembership = CreateDefaultSimpleMembershipProvider(BuiltInMembershipProviderName, currentDefault: builtInMembership);
Membership.Providers.Remove(BuiltInMembershipProviderName);
Membership.Providers.Add(simpleMembership);
}
Roles.Enabled = true;
const string BuiltInRolesProviderName = "AspNetSqlRoleProvider";
var builtInRoles = Roles.Providers[BuiltInRolesProviderName];
if (builtInRoles != null)
{
var simpleRoles = CreateDefaultSimpleRoleProvider(BuiltInRolesProviderName, currentDefault: builtInRoles);
Roles.Providers.Remove(BuiltInRolesProviderName);
Roles.Providers.Add(simpleRoles);
}
}
}
private static ExtendedMembershipProvider VerifyProvider()
{
ExtendedMembershipProvider provider = Membership.Provider as ExtendedMembershipProvider;
if (provider == null)
{
throw new InvalidOperationException(WebDataResources.Security_NoExtendedMembershipProvider);
}
provider.VerifyInitialized(); // Have the provider verify that it's initialized (only our SimpleMembershipProvider does anything here)
return provider;
}
public static void InitializeDatabaseConnection(string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
DatabaseConnectionInfo connect = new DatabaseConnectionInfo();
connect.ConnectionStringName = connectionStringName;
InitializeProviders(connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
public static void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
DatabaseConnectionInfo connect = new DatabaseConnectionInfo();
connect.ConnectionString = connectionString;
connect.ProviderName = providerName;
InitializeProviders(connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
private static void InitializeProviders(DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
SimpleMembershipProvider simpleMembership = Membership.Provider as SimpleMembershipProvider;
if (simpleMembership != null)
{
InitializeMembershipProvider(simpleMembership, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider;
if (simpleRoles != null)
{
InitializeRoleProvider(simpleRoles, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
Initialized = true;
}
internal static void InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool createTables)
{
if (simpleMembership.InitializeCalled)
{
throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled);
}
simpleMembership.ConnectionInfo = connect;
simpleMembership.UserIdColumn = userIdColumn;
simpleMembership.UserNameColumn = userNameColumn;
simpleMembership.UserTableName = userTableName;
if (createTables)
{
simpleMembership.CreateTablesIfNeeded();
}
else
{
// We want to validate the user table if we aren't creating them
simpleMembership.ValidateUserTable();
}
simpleMembership.InitializeCalled = true;
}
internal static void InitializeRoleProvider(SimpleRoleProvider simpleRoles, DatabaseConnectionInfo connect, string userTableName, string userIdColumn, string userNameColumn, bool createTables)
{
if (simpleRoles.InitializeCalled)
{
throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled);
}
simpleRoles.ConnectionInfo = connect;
simpleRoles.UserTableName = userTableName;
simpleRoles.UserIdColumn = userIdColumn;
simpleRoles.UserNameColumn = userNameColumn;
if (createTables)
{
simpleRoles.CreateTablesIfNeeded();
}
simpleRoles.InitializeCalled = true;
}
private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)
{
var membership = new SimpleMembershipProvider(previousProvider: currentDefault);
NameValueCollection config = new NameValueCollection();
membership.Initialize(name, config);
return membership;
}
private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault)
{
var roleProvider = new SimpleRoleProvider(previousProvider: currentDefault);
NameValueCollection config = new NameValueCollection();
roleProvider.Initialize(name, config);
return roleProvider;
}
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "Login is used more consistently in ASP.Net")]
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "This is a helper class, and we are not removing optional parameters from methods in helper classes")]
public static bool Login(string userName, string password, bool persistCookie = false)
{
VerifyProvider();
bool success = Membership.ValidateUser(userName, password);
if (success)
{
FormsAuthentication.SetAuthCookie(userName, persistCookie);
}
return success;
}
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Logout", Justification = "Login is used more consistently in ASP.Net")]
public static void Logout()
{
VerifyProvider();
FormsAuthentication.SignOut();
}
public static bool ChangePassword(string userName, string currentPassword, string newPassword)
{
VerifyProvider();
bool success = false;
try
{
var currentUser = Membership.GetUser(userName, true /* userIsOnline */);
success = currentUser.ChangePassword(currentPassword, newPassword);
}
catch (ArgumentException)
{
// An argument exception is thrown if the new password does not meet the provider's requirements
}
return success;
}
public static bool ConfirmAccount(string accountConfirmationToken)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.ConfirmAccount(accountConfirmationToken);
}
public static bool ConfirmAccount(string userName, string accountConfirmationToken)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.ConfirmAccount(userName, accountConfirmationToken);
}
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "This is a helper class, and we are not removing optional parameters from methods in helper classes")]
public static string CreateAccount(string userName, string password, bool requireConfirmationToken = false)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.CreateAccount(userName, password, requireConfirmationToken);
}
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "This is a helper class, and we are not removing optional parameters from methods in helper classes")]
public static string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
IDictionary<string, object> values = null;
if (propertyValues != null)
{
values = new RouteValueDictionary(propertyValues);
}
return provider.CreateUserAndAccount(userName, password, requireConfirmationToken, values);
}
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "This is a helper class, and we are not removing optional parameters from methods in helper classes")]
public static string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow = 1440)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow);
}
public static bool UserExists(string userName)
{
VerifyProvider();
return Membership.GetUser(userName) != null;
}
public static int GetUserId(string userName)
{
VerifyProvider();
MembershipUser user = Membership.GetUser(userName);
if (user == null)
{
return -1;
}
// REVIEW: This cast is breaking the abstraction for the membershipprovider, we basically assume that userids are ints
return (int)user.ProviderUserKey;
}
public static int GetUserIdFromPasswordResetToken(string token)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GetUserIdFromPasswordResetToken(token);
}
public static bool IsCurrentUser(string userName)
{
VerifyProvider();
return String.Equals(CurrentUserName, userName, StringComparison.OrdinalIgnoreCase);
}
public static bool IsConfirmed(string userName)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.IsConfirmed(userName);
}
// Make sure the logged on user is same as the one specified by the id
private static bool IsUserLoggedOn(int userId)
{
VerifyProvider();
return CurrentUserId == userId;
}
// Make sure the user was authenticated
public static void RequireAuthenticatedUser()
{
VerifyProvider();
var user = Context.User;
if (user == null || !user.Identity.IsAuthenticated)
{
Response.SetStatus(HttpStatusCode.Unauthorized);
}
}
// Make sure the user was authenticated
public static void RequireUser(int userId)
{
VerifyProvider();
if (!IsUserLoggedOn(userId))
{
Response.SetStatus(HttpStatusCode.Unauthorized);
}
}
public static void RequireUser(string userName)
{
VerifyProvider();
if (!String.Equals(CurrentUserName, userName, StringComparison.OrdinalIgnoreCase))
{
Response.SetStatus(HttpStatusCode.Unauthorized);
}
}
public static void RequireRoles(params string[] roles)
{
VerifyProvider();
foreach (string role in roles)
{
if (!Roles.IsUserInRole(CurrentUserName, role))
{
Response.SetStatus(HttpStatusCode.Unauthorized);
return;
}
}
}
public static bool ResetPassword(string passwordResetToken, string newPassword)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.ResetPasswordWithToken(passwordResetToken, newPassword);
}
public static bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, int intervalInSeconds)
{
VerifyProvider();
return IsAccountLockedOut(userName, allowedPasswordAttempts, TimeSpan.FromSeconds(intervalInSeconds));
}
public static bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, TimeSpan interval)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return IsAccountLockedOutInternal(provider, userName, allowedPasswordAttempts, interval);
}
internal static bool IsAccountLockedOutInternal(ExtendedMembershipProvider provider, string userName, int allowedPasswordAttempts, TimeSpan interval)
{
return (provider.GetUser(userName, false) != null &&
provider.GetPasswordFailuresSinceLastSuccess(userName) > allowedPasswordAttempts &&
provider.GetLastPasswordFailureDate(userName).Add(interval) > DateTime.UtcNow);
}
public static int GetPasswordFailuresSinceLastSuccess(string userName)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GetPasswordFailuresSinceLastSuccess(userName);
}
public static DateTime GetCreateDate(string userName)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GetCreateDate(userName);
}
public static DateTime GetPasswordChangedDate(string userName)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GetPasswordChangedDate(userName);
}
public static DateTime GetLastPasswordFailureDate(string userName)
{
ExtendedMembershipProvider provider = VerifyProvider();
Debug.Assert(provider != null); // VerifyProvider checks this
return provider.GetLastPasswordFailureDate(userName);
}
}
}