· 10 years ago · Mar 20, 2016, 03:36 AM
1public ActionResult Create(TicketVM model)
2 {
3
4
5 if (!ModelState.IsValid)
6 {
7 ConfigureViewModel(model);
8 return View(model);
9 }
10
11 Ticket ticket = new Ticket
12 {
13 UserID = (int)WebSecurity.CurrentUserId,
14 Issue = model.Issue,
15 IssuedTo = model.IssuedTo,
16 CategoryID = model.CategoryID
17 };
18
19 db.Tickets.Add(ticket);
20 db.SaveChanges();
21
22 return RedirectToAction("Index");
23
24 }
25
26Line 32: using (var context = new UsersContext())
27Line 33: {
28Line 34: if (!context.Database.Exists()) <--- ERROR HERE
29Line 35: {
30Line 36: // Create the SimpleMembership database without Entity Framework migration schema
31
32using System;
33using System.Data.Entity;
34using System.Data.Entity.Infrastructure;
35using System.Threading;
36using System.Web.Mvc;
37using WebMatrix.WebData;
38using RecreationalServicesTicketingSystem.Models;
39
40namespace RecreationalServicesTicketingSystem.Filters
41{
42 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
43 public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
44 {
45 private static SimpleMembershipInitializer _initializer;
46 private static object _initializerLock = new object();
47 private static bool _isInitialized;
48
49 public override void OnActionExecuting(ActionExecutingContext filterContext)
50 {
51 // Ensure ASP.NET Simple Membership is initialized only once per app start
52 LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
53 }
54
55 private class SimpleMembershipInitializer
56 {
57 public SimpleMembershipInitializer()
58 {
59 Database.SetInitializer<UsersContext>(null);
60
61 try
62 {
63 using (var context = new UsersContext())
64 {
65 if (!context.Database.Exists())
66 {
67 // Create the SimpleMembership database without Entity Framework migration schema
68 ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
69 }
70 }
71
72 WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
73 }
74 catch (Exception ex)
75 {
76 throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
77 }
78 }
79 }
80 }
81}
82
83<?xml version="1.0" encoding="utf-8"?>
84<!--
85 For more information on how to configure your ASP.NET application, please visit
86 http://go.microsoft.com/fwlink/?LinkId=169433
87 -->
88<configuration>
89 <configSections>
90 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
91 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
92 </configSections>
93 <connectionStrings>
94 <add name="DefaultConnection" connectionString="Data Source=.SQLEXPRESS;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" />
95 </connectionStrings>
96 <appSettings>
97 <add key="webpages:Version" value="2.0.0.0" />
98 <add key="webpages:Enabled" value="false" />
99 <add key="PreserveLoginUrl" value="true" />
100 <add key="ClientValidationEnabled" value="true" />
101 <add key="UnobtrusiveJavaScriptEnabled" value="true" />
102 </appSettings>
103 <system.web>
104 <compilation debug="true" targetFramework="4.0" />
105 <httpRuntime targetFramework="4.5" />
106 <authentication mode="Forms">
107 <forms loginUrl="~/Account/Login" timeout="2880" />
108 </authentication>
109 <pages>
110 <namespaces>
111 <add namespace="System.Web.Helpers" />
112 <add namespace="System.Web.Mvc" />
113 <add namespace="System.Web.Mvc.Ajax" />
114 <add namespace="System.Web.Mvc.Html" />
115 <add namespace="System.Web.Optimization" />
116 <add namespace="System.Web.Routing" />
117 <add namespace="System.Web.WebPages" />
118 </namespaces>
119 </pages>
120 </system.web>
121 <system.webServer>
122 <validation validateIntegratedModeConfiguration="false" />
123 <handlers>
124 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
125 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
126 <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
127 <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
128 <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%Microsoft.NETFramework64v4.0.30319aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
129 <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
130 </handlers>
131 </system.webServer>
132 <runtime>
133 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
134 <dependentAssembly>
135 <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
136 <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
137 </dependentAssembly>
138 <dependentAssembly>
139 <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
140 <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
141 </dependentAssembly>
142 <dependentAssembly>
143 <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
144 <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
145 </dependentAssembly>
146 <dependentAssembly>
147 <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
148 <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
149 </dependentAssembly>
150 <dependentAssembly>
151 <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
152 <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
153 </dependentAssembly>
154 <dependentAssembly>
155 <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
156 <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
157 </dependentAssembly>
158 <dependentAssembly>
159 <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
160 <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
161 </dependentAssembly>
162 </assemblyBinding>
163 </runtime>
164 <entityFramework>
165 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
166 <providers>
167 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
168 </providers>
169 </entityFramework>
170</configuration>
171
172namespace RecreationalServicesTicketingSystem.Models
173{
174 public class UsersContext : DbContext
175 {
176 public UsersContext()
177 : base("DefaultConnection")
178 {
179 }
180
181 public DbSet<UserProfile> UserProfiles { get; set; }
182 }
183
184 [Table("UserProfile")]
185 public class UserProfile
186 {
187 [Key]
188 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
189 public int UserId { get; set; }
190 public string UserName { get; set; }
191 }
192
193 public class RegisterExternalLoginModel
194 {
195 [Required]
196 [Display(Name = "User name")]
197 public string UserName { get; set; }
198
199 public string ExternalLoginData { get; set; }
200 }
201
202 public class LocalPasswordModel
203 {
204 [Required]
205 [DataType(DataType.Password)]
206 [Display(Name = "Current password")]
207 public string OldPassword { get; set; }
208
209 [Required]
210 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
211 [DataType(DataType.Password)]
212 [Display(Name = "New password")]
213 public string NewPassword { get; set; }
214
215 [DataType(DataType.Password)]
216 [Display(Name = "Confirm new password")]
217 [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
218 public string ConfirmPassword { get; set; }
219 }
220
221 public class LoginModel
222 {
223 [Required]
224 [Display(Name = "User name")]
225 public string UserName { get; set; }
226
227 [Required]
228 [DataType(DataType.Password)]
229 [Display(Name = "Password")]
230 public string Password { get; set; }
231
232 [Display(Name = "Remember me?")]
233 public bool RememberMe { get; set; }
234 }
235
236 public class RegisterModel
237 {
238 [Required]
239 [Display(Name = "User name")]
240 public string UserName { get; set; }
241
242 [Required]
243 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
244 [DataType(DataType.Password)]
245 [Display(Name = "Password")]
246 public string Password { get; set; }
247
248 [DataType(DataType.Password)]
249 [Display(Name = "Confirm password")]
250 [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
251 public string ConfirmPassword { get; set; }
252 }
253
254 public class ExternalLogin
255 {
256 public string Provider { get; set; }
257 public string ProviderDisplayName { get; set; }
258 public string ProviderUserId { get; set; }
259 }
260}
261
262namespace RecreationalServicesTicketingSystem.Controllers
263{
264 [Authorize]
265 [InitializeSimpleMembership]
266 public class AccountController : Controller
267 {
268 //
269 // GET: /Account/Login
270
271 [AllowAnonymous]
272 public ActionResult Login(string returnUrl)
273 {
274 ViewBag.ReturnUrl = returnUrl;
275 return View();
276 }
277
278 //
279 // POST: /Account/Login
280
281 [HttpPost]
282 [AllowAnonymous]
283 [ValidateAntiForgeryToken]
284 public ActionResult Login(LoginModel model, string returnUrl)
285 {
286 if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
287 {
288 return RedirectToLocal(returnUrl);
289 }
290
291 // If we got this far, something failed, redisplay form
292 ModelState.AddModelError("", "The user name or password provided is incorrect.");
293 return View(model);
294 }
295
296 //
297 // POST: /Account/LogOff
298
299 [HttpPost]
300 [ValidateAntiForgeryToken]
301 public ActionResult LogOff()
302 {
303 WebSecurity.Logout();
304
305 return RedirectToAction("Index", "Home");
306 }
307
308 //
309 // GET: /Account/Register
310
311 [AllowAnonymous]
312 public ActionResult Register()
313 {
314 return View();
315 }
316
317 //
318 // POST: /Account/Register
319
320 [HttpPost]
321 [AllowAnonymous]
322 [ValidateAntiForgeryToken]
323 public ActionResult Register(RegisterModel model)
324 {
325 if (ModelState.IsValid)
326 {
327 // Attempt to register the user
328 try
329 {
330 WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
331 WebSecurity.Login(model.UserName, model.Password);
332 return RedirectToAction("Index", "Home");
333 }
334 catch (MembershipCreateUserException e)
335 {
336 ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
337 }
338 }
339
340 // If we got this far, something failed, redisplay form
341 return View(model);
342 }
343
344 //
345 // POST: /Account/Disassociate
346
347 [HttpPost]
348 [ValidateAntiForgeryToken]
349 public ActionResult Disassociate(string provider, string providerUserId)
350 {
351 string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
352 ManageMessageId? message = null;
353
354 // Only disassociate the account if the currently logged in user is the owner
355 if (ownerAccount == User.Identity.Name)
356 {
357 // Use a transaction to prevent the user from deleting their last login credential
358 using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
359 {
360 bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
361 if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
362 {
363 OAuthWebSecurity.DeleteAccount(provider, providerUserId);
364 scope.Complete();
365 message = ManageMessageId.RemoveLoginSuccess;
366 }
367 }
368 }
369
370 return RedirectToAction("Manage", new { Message = message });
371 }
372
373 //
374 // GET: /Account/Manage
375
376 public ActionResult Manage(ManageMessageId? message)
377 {
378 ViewBag.StatusMessage =
379 message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
380 : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
381 : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
382 : "";
383 ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
384 ViewBag.ReturnUrl = Url.Action("Manage");
385 return View();
386 }
387
388 //
389 // POST: /Account/Manage
390
391 [HttpPost]
392 [ValidateAntiForgeryToken]
393 public ActionResult Manage(LocalPasswordModel model)
394 {
395 bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
396 ViewBag.HasLocalPassword = hasLocalAccount;
397 ViewBag.ReturnUrl = Url.Action("Manage");
398 if (hasLocalAccount)
399 {
400 if (ModelState.IsValid)
401 {
402 // ChangePassword will throw an exception rather than return false in certain failure scenarios.
403 bool changePasswordSucceeded;
404 try
405 {
406 changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
407 }
408 catch (Exception)
409 {
410 changePasswordSucceeded = false;
411 }
412
413 if (changePasswordSucceeded)
414 {
415 return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
416 }
417 else
418 {
419 ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
420 }
421 }
422 }
423 else
424 {
425 // User does not have a local password so remove any validation errors caused by a missing
426 // OldPassword field
427 ModelState state = ModelState["OldPassword"];
428 if (state != null)
429 {
430 state.Errors.Clear();
431 }
432
433 if (ModelState.IsValid)
434 {
435 try
436 {
437 WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
438 return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
439 }
440 catch (Exception)
441 {
442 ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name "{0}" may already exist.", User.Identity.Name));
443 }
444 }
445 }
446
447 // If we got this far, something failed, redisplay form
448 return View(model);
449 }
450
451 //
452 // POST: /Account/ExternalLogin
453
454 [HttpPost]
455 [AllowAnonymous]
456 [ValidateAntiForgeryToken]
457 public ActionResult ExternalLogin(string provider, string returnUrl)
458 {
459 return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
460 }
461
462 //
463 // GET: /Account/ExternalLoginCallback
464
465 [AllowAnonymous]
466 public ActionResult ExternalLoginCallback(string returnUrl)
467 {
468 AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
469 if (!result.IsSuccessful)
470 {
471 return RedirectToAction("ExternalLoginFailure");
472 }
473
474 if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
475 {
476 return RedirectToLocal(returnUrl);
477 }
478
479 if (User.Identity.IsAuthenticated)
480 {
481 // If the current user is logged in add the new account
482 OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
483 return RedirectToLocal(returnUrl);
484 }
485 else
486 {
487 // User is new, ask for their desired membership name
488 string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
489 ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
490 ViewBag.ReturnUrl = returnUrl;
491 return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
492 }
493 }
494
495 //
496 // POST: /Account/ExternalLoginConfirmation
497
498 [HttpPost]
499 [AllowAnonymous]
500 [ValidateAntiForgeryToken]
501 public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
502 {
503 string provider = null;
504 string providerUserId = null;
505
506 if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
507 {
508 return RedirectToAction("Manage");
509 }
510
511 if (ModelState.IsValid)
512 {
513 // Insert a new user into the database
514 using (UsersContext db = new UsersContext())
515 {
516 UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
517 // Check if user already exists
518 if (user == null)
519 {
520 // Insert name into the profile table
521 db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
522 db.SaveChanges();
523
524 OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
525 OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
526
527 return RedirectToLocal(returnUrl);
528 }
529 else
530 {
531 ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
532 }
533 }
534 }
535
536 ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
537 ViewBag.ReturnUrl = returnUrl;
538 return View(model);
539 }
540
541 //
542 // GET: /Account/ExternalLoginFailure
543
544 [AllowAnonymous]
545 public ActionResult ExternalLoginFailure()
546 {
547 return View();
548 }
549
550 [AllowAnonymous]
551 [ChildActionOnly]
552 public ActionResult ExternalLoginsList(string returnUrl)
553 {
554 ViewBag.ReturnUrl = returnUrl;
555 return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
556 }
557
558 [ChildActionOnly]
559 public ActionResult RemoveExternalLogins()
560 {
561 ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
562 List<ExternalLogin> externalLogins = new List<ExternalLogin>();
563 foreach (OAuthAccount account in accounts)
564 {
565 AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);
566
567 externalLogins.Add(new ExternalLogin
568 {
569 Provider = account.Provider,
570 ProviderDisplayName = clientData.DisplayName,
571 ProviderUserId = account.ProviderUserId,
572 });
573 }
574
575 ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
576 return PartialView("_RemoveExternalLoginsPartial", externalLogins);
577 }
578
579 #region Helpers
580 private ActionResult RedirectToLocal(string returnUrl)
581 {
582 if (Url.IsLocalUrl(returnUrl))
583 {
584 return Redirect(returnUrl);
585 }
586 else
587 {
588 return RedirectToAction("Index", "Home");
589 }
590 }
591
592 public enum ManageMessageId
593 {
594 ChangePasswordSuccess,
595 SetPasswordSuccess,
596 RemoveLoginSuccess,
597 }
598
599 internal class ExternalLoginResult : ActionResult
600 {
601 public ExternalLoginResult(string provider, string returnUrl)
602 {
603 Provider = provider;
604 ReturnUrl = returnUrl;
605 }
606
607 public string Provider { get; private set; }
608 public string ReturnUrl { get; private set; }
609
610 public override void ExecuteResult(ControllerContext context)
611 {
612 OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
613 }
614 }
615
616 private static string ErrorCodeToString(MembershipCreateStatus createStatus)
617 {
618 // See http://go.microsoft.com/fwlink/?LinkID=177550 for
619 // a full list of status codes.
620 switch (createStatus)
621 {
622 case MembershipCreateStatus.DuplicateUserName:
623 return "User name already exists. Please enter a different user name.";
624
625 case MembershipCreateStatus.DuplicateEmail:
626 return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
627
628 case MembershipCreateStatus.InvalidPassword:
629 return "The password provided is invalid. Please enter a valid password value.";
630
631 case MembershipCreateStatus.InvalidEmail:
632 return "The e-mail address provided is invalid. Please check the value and try again.";
633
634 case MembershipCreateStatus.InvalidAnswer:
635 return "The password retrieval answer provided is invalid. Please check the value and try again.";
636
637 case MembershipCreateStatus.InvalidQuestion:
638 return "The password retrieval question provided is invalid. Please check the value and try again.";
639
640 case MembershipCreateStatus.InvalidUserName:
641 return "The user name provided is invalid. Please check the value and try again.";
642
643 case MembershipCreateStatus.ProviderError:
644 return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
645
646 case MembershipCreateStatus.UserRejected:
647 return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
648
649 default:
650 return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
651 }
652 }
653 #endregion
654 }
655}