Free cookie consent management tool by TermsFeed Policy Generator

Changeset 3958


Ignore:
Timestamp:
06/26/10 11:13:25 (14 years ago)
Author:
jhaider
Message:

added Initialize and ApplicationName (#10436)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.Services.Authentication Prototype/Service/Provider/HeuristicLabMembershipProvider.cs

    r3957 r3958  
    11using System;
     2using System.Collections.Specialized;
     3using System.Configuration;
    24using System.Configuration.Provider;
    35using System.Linq;
     
    1113  class HeuristicLabMembershipProvider : MembershipProvider {
    1214
    13       private string pApplicationName;
    14       private bool pEnablePasswordReset;
    15       private bool pEnablePasswordRetrieval;
    16       private bool pRequiresQuestionAndAnswer;
    17       private bool pRequiresUniqueEmail;
    18       private int pMaxInvalidPasswordAttempts;
    19       private int pPasswordAttemptWindow;
    20       private MembershipPasswordFormat pPasswordFormat;
    21       private MachineKeySection machineKey;
    22 
    23       public override string ApplicationName {
    24       get {
    25         throw new NotImplementedException();
    26       }
    27       set {
    28         throw new NotImplementedException();
    29       }
     15    private string pApplicationName;
     16    private bool pEnablePasswordReset;
     17    private bool pEnablePasswordRetrieval;
     18    private bool pRequiresQuestionAndAnswer;
     19    private bool pRequiresUniqueEmail;
     20    private int pMaxInvalidPasswordAttempts;
     21    private int pPasswordAttemptWindow;
     22    private int pMinRequiredPasswordLength;
     23    private MembershipPasswordFormat pPasswordFormat;
     24    private MachineKeySection machineKey;
     25
     26
     27    public override void Initialize(string name, NameValueCollection config) {
     28      //
     29      // Initialize values from web.config.
     30      //
     31
     32      if (config == null)
     33        throw new ArgumentNullException("config");
     34
     35      if (name == null || name.Length == 0)
     36        name = "HeuristicLabMembershipProvider";
     37
     38      if (String.IsNullOrEmpty(config["description"])) {
     39        config.Remove("description");
     40        config.Add("description", "Heuristic Lab Membership provider");
     41      }
     42
     43      // Initialize the abstract base class.
     44      base.Initialize(name, config);
     45
     46      pApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
     47      pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
     48      pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
     49      pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
     50      pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
     51      pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
     52      pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
     53      pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
     54
     55      string tempFormat = config["passwordFormat"];
     56      if (tempFormat == null) {
     57        tempFormat = "Hashed";
     58      }
     59
     60      switch (tempFormat) {
     61        case "Hashed":
     62          pPasswordFormat = MembershipPasswordFormat.Hashed;
     63          break;
     64        case "Encrypted":
     65          pPasswordFormat = MembershipPasswordFormat.Encrypted;
     66          break;
     67        case "Clear":
     68          pPasswordFormat = MembershipPasswordFormat.Clear;
     69          break;
     70        default:
     71          throw new ProviderException("Password format not supported.");
     72      }
     73
     74      // Get encryption and decryption key information from the configuration.
     75      Configuration cfg =
     76        WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
     77      machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");
     78
     79      if (machineKey.ValidationKey.Contains("AutoGenerate"))
     80        if (PasswordFormat != MembershipPasswordFormat.Clear)
     81          throw new ProviderException("Hashed or Encrypted passwords " +
     82                                      "are not supported with auto-generated keys.");
     83    }
     84
     85    public override string ApplicationName {
     86      get { return pApplicationName; }
     87      set { pApplicationName = value; }
    3088    }
    3189
     
    122180        try {
    123181          // try to get user
    124           HeuristicLabUser u = 
     182          HeuristicLabUser u =
    125183            db.HeuristicLabUsers.Single<HeuristicLabUser>(x => x.UserName == username);
    126184
     
    129187            db.HeuristicLabUserRole.DeleteAllOnSubmit<HeuristicLabUserRole>(u.HeuristicLabUserRole);
    130188          }
    131          
     189
    132190          // delete user
    133191          db.HeuristicLabUsers.DeleteOnSubmit(u);
     
    231289    /// <param name="password"></param>
    232290    /// <returns></returns>
    233     public override bool ValidateUser(string username, string password)
    234     {
    235         bool isValid = false;
    236         using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext())
    237         {
    238             if (db == null)
    239             {
    240                 return false;
    241             }
    242             HeuristicLabUser u = db.HeuristicLabUsers.Single(x => x.UserName == username);
    243             isValid = CheckPassword(password, u.GetPassword());
    244         }
    245         return isValid;
    246     }
    247    
     291    public override bool ValidateUser(string username, string password) {
     292      bool isValid = false;
     293      using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext()) {
     294        if (db == null) {
     295          return false;
     296        }
     297        HeuristicLabUser u = db.HeuristicLabUsers.Single(x => x.UserName == username);
     298        isValid = CheckPassword(password, u.GetPassword());
     299      }
     300      return isValid;
     301    }
     302
    248303    /// <summary>
    249304    /// compaiers to passwords
     
    252307    /// <param name="dbpassword"></param>
    253308    /// <returns></returns>
    254     private bool CheckPassword(string password, string dbpassword)
    255     {
    256         string pass1 = password;
    257         string pass2 = dbpassword;
    258 
    259         switch (PasswordFormat)
    260         {
    261             case MembershipPasswordFormat.Encrypted:
    262                 pass2 = DecodePassword(dbpassword);
    263                 break;
    264             case MembershipPasswordFormat.Hashed:
    265                 pass1 = EncodePassword(password);
    266                 break;
    267             default:
    268                 break;
    269         }
    270 
    271         if (pass1 == pass2)
    272         {
    273             return true;
    274         }
    275 
    276         return false;
    277     }
    278 
    279 
    280    /// <summary>
    281    /// Encodes a password
    282    /// </summary>
    283    /// <param name="password"></param>
    284    /// <returns></returns>
    285    private string EncodePassword(string password)
    286     {
    287         string encodedPassword = password;
    288 
    289         switch (PasswordFormat)
    290         {
    291             case MembershipPasswordFormat.Clear:
    292                 break;
    293             case MembershipPasswordFormat.Encrypted:
    294                 encodedPassword =
    295                   Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
    296                 break;
    297             case MembershipPasswordFormat.Hashed:
    298                 HMACSHA1 hash = new HMACSHA1();
    299                 hash.Key = HexToByte(machineKey.ValidationKey);
    300                 encodedPassword =
    301                   Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
    302                 break;
    303             default:
    304                 throw new ProviderException("Unsupported password format.");
    305         }
    306 
    307         return encodedPassword;
     309    private bool CheckPassword(string password, string dbpassword) {
     310      string pass1 = password;
     311      string pass2 = dbpassword;
     312
     313      switch (PasswordFormat) {
     314        case MembershipPasswordFormat.Encrypted:
     315          pass2 = DecodePassword(dbpassword);
     316          break;
     317        case MembershipPasswordFormat.Hashed:
     318          pass1 = EncodePassword(password);
     319          break;
     320        default:
     321          break;
     322      }
     323
     324      if (pass1 == pass2) {
     325        return true;
     326      }
     327
     328      return false;
     329    }
     330
     331
     332    /// <summary>
     333    /// Encodes a password
     334    /// </summary>
     335    /// <param name="password"></param>
     336    /// <returns></returns>
     337    private string EncodePassword(string password) {
     338      string encodedPassword = password;
     339
     340      switch (PasswordFormat) {
     341        case MembershipPasswordFormat.Clear:
     342          break;
     343        case MembershipPasswordFormat.Encrypted:
     344          encodedPassword =
     345            Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
     346          break;
     347        case MembershipPasswordFormat.Hashed:
     348          HMACSHA1 hash = new HMACSHA1();
     349          hash.Key = HexToByte(machineKey.ValidationKey);
     350          encodedPassword =
     351            Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
     352          break;
     353        default:
     354          throw new ProviderException("Unsupported password format.");
     355      }
     356
     357      return encodedPassword;
    308358    }
    309359
     
    314364    /// <param name="encodedPassword"></param>
    315365    /// <returns></returns>
    316     private string DecodePassword(string encodedPassword)
    317     {
    318         string password = encodedPassword;
    319 
    320         switch (PasswordFormat)
    321         {
    322             case MembershipPasswordFormat.Clear:
    323                 break;
    324             case MembershipPasswordFormat.Encrypted:
    325                 password =
    326                   Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
    327                 break;
    328             case MembershipPasswordFormat.Hashed:
    329                 throw new ProviderException("Cannot unencode a hashed password.");
    330             default:
    331                 throw new ProviderException("Unsupported password format.");
    332         }
    333 
    334         return password;
     366    private string DecodePassword(string encodedPassword) {
     367      string password = encodedPassword;
     368
     369      switch (PasswordFormat) {
     370        case MembershipPasswordFormat.Clear:
     371          break;
     372        case MembershipPasswordFormat.Encrypted:
     373          password =
     374            Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
     375          break;
     376        case MembershipPasswordFormat.Hashed:
     377          throw new ProviderException("Cannot unencode a hashed password.");
     378        default:
     379          throw new ProviderException("Unsupported password format.");
     380      }
     381
     382      return password;
    335383    }
    336384
     
    340388    /// <param name="hexString"></param>
    341389    /// <returns></returns>
    342     private static byte[] HexToByte(string hexString)
    343     {
    344         byte[] returnBytes = new byte[hexString.Length / 2];
    345         for (int i = 0; i < returnBytes.Length; i++)
    346             returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
    347         return returnBytes;
     390    private static byte[] HexToByte(string hexString) {
     391      byte[] returnBytes = new byte[hexString.Length / 2];
     392      for (int i = 0; i < returnBytes.Length; i++)
     393        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
     394      return returnBytes;
     395    }
     396
     397    /// <summary>
     398    /// returns the configuration string, if the value is null or empty the default value is returned
     399    /// </summary>
     400    /// <param name="configValue"></param>
     401    /// <param name="defaultValue"></param>
     402    /// <returns></returns>
     403    private string GetConfigValue(string configValue, string defaultValue) {
     404      if (String.IsNullOrEmpty(configValue))
     405        return defaultValue;
     406
     407      return configValue;
    348408    }
    349409  }
Note: See TracChangeset for help on using the changeset viewer.