Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Services.Authentication Prototype/Service/Provider/HeuristicLabMembershipProvider.cs @ 3957

Last change on this file since 3957 was 3957, checked in by jhaider, 14 years ago

Added ValidateUser (#1046)

File size: 11.2 KB
Line 
1using System;
2using System.Configuration.Provider;
3using System.Linq;
4using System.Security.Cryptography;
5using System.Text;
6using System.Web.Configuration;
7using System.Web.Security;
8using Persistence;
9
10namespace Service.Provider {
11  class HeuristicLabMembershipProvider : MembershipProvider {
12
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      }
30    }
31
32    public override bool ChangePassword(string username, string oldPassword, string newPassword) {
33      using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext()) {
34        // check database connection
35        if (db == null) {
36          return false;
37        }
38        try {
39          // try to get user
40          HeuristicLabUser u = db.HeuristicLabUsers.Single(x => x.UserName == username);
41          if (u.ChangePassword(oldPassword, newPassword)) {
42            // save user to database only if needed
43            db.SubmitChanges();
44            return true;
45          } else {
46            return false;
47          }
48        }
49        catch (Exception) {
50          return false;
51        }
52      }
53    }
54
55    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) {
56      using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext()) {
57        // check database connection
58        if (db == null) {
59          return false;
60        }
61        try {
62          // try to get user
63          HeuristicLabUser u = db.HeuristicLabUsers.Single(x => x.UserName == username);
64          if (u.ChangePasswordQuestionAndAnswer(password, newPasswordQuestion, newPasswordAnswer)) {
65            // save user to database only if needed
66            db.SubmitChanges();
67            return true;
68          } else {
69            return false;
70          }
71        }
72        catch (Exception) {
73          return false;
74        }
75      }
76    }
77
78    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) {
79      using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext()) {
80        // check database connection
81        if (db == null) {
82          status = MembershipCreateStatus.ProviderError;
83          return null;
84        }
85        try {
86          // check for duplicate entries
87          if (db.HeuristicLabUsers.Count(x => x.UserName == username) > 0) {
88            status = MembershipCreateStatus.DuplicateUserName;
89            return null;
90          }
91          if (db.HeuristicLabUsers.Count(x => x.Email == email) > 0) {
92            status = MembershipCreateStatus.DuplicateEmail;
93            return null;
94          }
95
96          // create new user
97          HeuristicLabUser u = new HeuristicLabUser(username, email, passwordQuestion, "");
98          u.ChangePassword("INIT", password);
99          u.ChangePasswordQuestionAndAnswer(password, passwordQuestion, passwordAnswer);
100          // save user into database
101          db.HeuristicLabUsers.InsertOnSubmit(u);
102          db.SubmitChanges();
103
104          // success
105          status = MembershipCreateStatus.Success;
106          return u;
107        }
108        catch (Exception) {
109          // error
110          status = MembershipCreateStatus.ProviderError;
111          return null;
112        }
113      }
114    }
115
116    public override bool DeleteUser(string username, bool deleteAllRelatedData) {
117      using (DataClassesDataContext db = DatabaseUtil.createDataClassesDataContext()) {
118        // check database connection
119        if (db == null) {
120          return false;
121        }
122        try {
123          // try to get user
124          HeuristicLabUser u =
125            db.HeuristicLabUsers.Single<HeuristicLabUser>(x => x.UserName == username);
126
127          // optionally delete related data
128          if (deleteAllRelatedData) {
129            db.HeuristicLabUserRole.DeleteAllOnSubmit<HeuristicLabUserRole>(u.HeuristicLabUserRole);
130          }
131         
132          // delete user
133          db.HeuristicLabUsers.DeleteOnSubmit(u);
134          db.SubmitChanges();
135          return true;
136        }
137        catch (Exception) {
138          return false;
139        }
140      }
141    }
142
143    public override bool EnablePasswordReset {
144      get { throw new NotImplementedException(); }
145    }
146
147    public override bool EnablePasswordRetrieval {
148      get { throw new NotImplementedException(); }
149    }
150
151    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) {
152      throw new NotImplementedException();
153    }
154
155    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) {
156      throw new NotImplementedException();
157    }
158
159    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) {
160      throw new NotImplementedException();
161    }
162
163    public override int GetNumberOfUsersOnline() {
164      throw new NotImplementedException();
165    }
166
167    public override string GetPassword(string username, string answer) {
168
169      throw new NotImplementedException();
170    }
171
172    public override MembershipUser GetUser(string username, bool userIsOnline) {
173      throw new NotImplementedException();
174    }
175
176    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) {
177      throw new NotImplementedException();
178    }
179
180    public override string GetUserNameByEmail(string email) {
181      throw new NotImplementedException();
182    }
183
184    public override int MaxInvalidPasswordAttempts {
185      get { throw new NotImplementedException(); }
186    }
187
188    public override int MinRequiredNonAlphanumericCharacters {
189      get { throw new NotImplementedException(); }
190    }
191
192    public override int MinRequiredPasswordLength {
193      get { throw new NotImplementedException(); }
194    }
195
196    public override int PasswordAttemptWindow {
197      get { throw new NotImplementedException(); }
198    }
199
200    public override MembershipPasswordFormat PasswordFormat {
201      get { throw new NotImplementedException(); }
202    }
203
204    public override string PasswordStrengthRegularExpression {
205      get { throw new NotImplementedException(); }
206    }
207
208    public override bool RequiresQuestionAndAnswer {
209      get { throw new NotImplementedException(); }
210    }
211
212    public override bool RequiresUniqueEmail {
213      get { throw new NotImplementedException(); }
214    }
215
216    public override string ResetPassword(string username, string answer) {
217      throw new NotImplementedException();
218    }
219
220    public override bool UnlockUser(string userName) {
221      throw new NotImplementedException();
222    }
223
224    public override void UpdateUser(MembershipUser user) {
225      throw new NotImplementedException();
226    }
227    /// <summary>
228    /// Validates a user
229    /// </summary>
230    /// <param name="username"></param>
231    /// <param name="password"></param>
232    /// <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   
248    /// <summary>
249    /// compaiers to passwords
250    /// </summary>
251    /// <param name="password"></param>
252    /// <param name="dbpassword"></param>
253    /// <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;
308    }
309
310
311    /// <summary>
312    /// Decodes a encoded Password
313    /// </summary>
314    /// <param name="encodedPassword"></param>
315    /// <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;
335    }
336
337    /// <summary>
338    /// returns byte array  of an HexString
339    /// </summary>
340    /// <param name="hexString"></param>
341    /// <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;
348    }
349  }
350}
Note: See TracBrowser for help on using the repository browser.