Exercise Files
This commit is contained in:
34
Ch03/03_Challenge/Website/App_Start/BundleConfig.cs
Normal file
34
Ch03/03_Challenge/Website/App_Start/BundleConfig.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System.Web;
|
||||
using System.Web.Optimization;
|
||||
|
||||
namespace HPlusSports
|
||||
{
|
||||
public class BundleConfig
|
||||
{
|
||||
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
|
||||
public static void RegisterBundles(BundleCollection bundles)
|
||||
{
|
||||
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
|
||||
"~/Scripts/jquery-{version}.js"));
|
||||
|
||||
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
|
||||
"~/Scripts/jquery.validate*"));
|
||||
|
||||
// Use the development version of Modernizr to develop with and learn from. Then, when you're
|
||||
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
|
||||
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
|
||||
"~/Scripts/modernizr-*"));
|
||||
|
||||
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
|
||||
"~/Scripts/bootstrap.js",
|
||||
"~/Scripts/respond.js"));
|
||||
|
||||
bundles.Add(new StyleBundle("~/Content/css").Include(
|
||||
"~/Content/bootstrap.css",
|
||||
"~/Content/site.css"));
|
||||
|
||||
bundles.Add(new ScriptBundle("~/bundles/site").Include(
|
||||
"~/Scripts/site.js"));
|
||||
}
|
||||
}
|
||||
}
|
||||
15
Ch03/03_Challenge/Website/App_Start/DatabaseConfig.cs
Normal file
15
Ch03/03_Challenge/Website/App_Start/DatabaseConfig.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using HPlusSports.Models;
|
||||
using System.Data.Entity;
|
||||
|
||||
namespace HPlusSports.App_Start
|
||||
{
|
||||
public class DatabaseConfig
|
||||
{
|
||||
public static void Initialize()
|
||||
{
|
||||
Database.SetInitializer(new HPlusSportsDbContextInitializer());
|
||||
var context = new HPlusSportsDbContext();
|
||||
context.Database.Initialize(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
26
Ch03/03_Challenge/Website/App_Start/Dependencies.cs
Normal file
26
Ch03/03_Challenge/Website/App_Start/Dependencies.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
using Autofac;
|
||||
using Autofac.Integration.Mvc;
|
||||
|
||||
namespace HPlusSports.App_Start
|
||||
{
|
||||
public class Dependencies
|
||||
{
|
||||
public static void Register()
|
||||
{
|
||||
var builder = new ContainerBuilder();
|
||||
builder.RegisterControllers(typeof(Dependencies).Assembly);
|
||||
builder.RegisterType<HPlusSportsDbContext>()
|
||||
.InstancePerRequest();
|
||||
|
||||
var container = builder.Build();
|
||||
|
||||
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
13
Ch03/03_Challenge/Website/App_Start/FilterConfig.cs
Normal file
13
Ch03/03_Challenge/Website/App_Start/FilterConfig.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace HPlusSports
|
||||
{
|
||||
public class FilterConfig
|
||||
{
|
||||
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
|
||||
{
|
||||
filters.Add(new HandleErrorAttribute());
|
||||
}
|
||||
}
|
||||
}
|
||||
157
Ch03/03_Challenge/Website/App_Start/IdentityConfig.cs
Normal file
157
Ch03/03_Challenge/Website/App_Start/IdentityConfig.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Entity;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Identity.EntityFramework;
|
||||
using Microsoft.AspNet.Identity.Owin;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security;
|
||||
using HPlusSports.Models;
|
||||
|
||||
namespace HPlusSports
|
||||
{
|
||||
public class EmailService : IIdentityMessageService
|
||||
{
|
||||
public Task SendAsync(IdentityMessage message)
|
||||
{
|
||||
// Plug in your email service here to send an email.
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
|
||||
public class SmsService : IIdentityMessageService
|
||||
{
|
||||
public Task SendAsync(IdentityMessage message)
|
||||
{
|
||||
// Plug in your SMS service here to send a text message.
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
|
||||
public class ApplicationUserManager : UserManager<ApplicationUser>
|
||||
{
|
||||
public ApplicationUserManager(IUserStore<ApplicationUser> store)
|
||||
: base(store)
|
||||
{
|
||||
}
|
||||
|
||||
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
|
||||
{
|
||||
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
|
||||
// Configure validation logic for usernames
|
||||
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
|
||||
{
|
||||
AllowOnlyAlphanumericUserNames = false,
|
||||
RequireUniqueEmail = true
|
||||
};
|
||||
|
||||
// Configure validation logic for passwords
|
||||
manager.PasswordValidator = new PasswordValidator
|
||||
{
|
||||
RequiredLength = 6,
|
||||
RequireNonLetterOrDigit = false,
|
||||
RequireDigit = false,
|
||||
RequireLowercase = false,
|
||||
RequireUppercase = false,
|
||||
};
|
||||
|
||||
// Configure user lockout defaults
|
||||
manager.UserLockoutEnabledByDefault = true;
|
||||
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
|
||||
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
|
||||
|
||||
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
|
||||
// You can write your own provider and plug it in here.
|
||||
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
|
||||
{
|
||||
MessageFormat = "Your security code is {0}"
|
||||
});
|
||||
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
|
||||
{
|
||||
Subject = "Security Code",
|
||||
BodyFormat = "Your security code is {0}"
|
||||
});
|
||||
manager.EmailService = new EmailService();
|
||||
manager.SmsService = new SmsService();
|
||||
var dataProtectionProvider = options.DataProtectionProvider;
|
||||
if (dataProtectionProvider != null)
|
||||
{
|
||||
manager.UserTokenProvider =
|
||||
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the application sign-in manager which is used in this application.
|
||||
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
|
||||
{
|
||||
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
|
||||
: base(userManager, authenticationManager)
|
||||
{
|
||||
}
|
||||
|
||||
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
|
||||
{
|
||||
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
|
||||
}
|
||||
|
||||
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
|
||||
{
|
||||
Initialized = Initalize(context);
|
||||
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
|
||||
}
|
||||
|
||||
#region DEMO CODE - Do not use in your real site!
|
||||
const string AdminEmailAddress = "admin@hplussports.com";
|
||||
|
||||
static volatile bool Initialized = false;
|
||||
|
||||
private static bool Initalize(IOwinContext context)
|
||||
{
|
||||
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
|
||||
|
||||
if (!roleManager.RoleExists(UserRoles.Admin))
|
||||
{
|
||||
Console.Out.Write($"User {AdminEmailAddress} doesn't exist - creating... ");
|
||||
var result = roleManager.Create(new IdentityRole(UserRoles.Admin));
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
Console.Out.WriteLine("done.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception(String.Join("; ", result.Errors.ToArray()));
|
||||
}
|
||||
}
|
||||
|
||||
var userManager = context.GetUserManager<ApplicationUserManager>();
|
||||
|
||||
if (!userManager.Users.Any(x => x.Email == AdminEmailAddress))
|
||||
{
|
||||
Console.Out.Write($"User {AdminEmailAddress} doesn't exist - creating... ");
|
||||
|
||||
var adminUser = new ApplicationUser(AdminEmailAddress) { Email = AdminEmailAddress };
|
||||
var result = userManager.Create(adminUser, "password");
|
||||
if (result.Succeeded)
|
||||
{
|
||||
userManager.AddToRole(adminUser.Id, UserRoles.Admin);
|
||||
Console.Out.WriteLine("done.");
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception(String.Join("; ", result.Errors.ToArray()));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
25
Ch03/03_Challenge/Website/App_Start/RouteConfig.cs
Normal file
25
Ch03/03_Challenge/Website/App_Start/RouteConfig.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
|
||||
namespace HPlusSports
|
||||
{
|
||||
public class RouteConfig
|
||||
{
|
||||
public static void RegisterRoutes(RouteCollection routes)
|
||||
{
|
||||
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
|
||||
|
||||
routes.MapMvcAttributeRoutes();
|
||||
|
||||
routes.MapRoute(
|
||||
name: "Default",
|
||||
url: "{controller}/{action}/{id}",
|
||||
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Ch03/03_Challenge/Website/App_Start/Startup.Auth.cs
Normal file
67
Ch03/03_Challenge/Website/App_Start/Startup.Auth.cs
Normal file
@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.AspNet.Identity.Owin;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security.Cookies;
|
||||
using Owin;
|
||||
using HPlusSports.Models;
|
||||
|
||||
namespace HPlusSports
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
|
||||
public void ConfigureAuth(IAppBuilder app)
|
||||
{
|
||||
// Configure the db context, user manager and signin manager to use a single instance per request
|
||||
app.CreatePerOwinContext(ApplicationDbContext.Create);
|
||||
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
|
||||
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
|
||||
|
||||
// Enable the application to use a cookie to store information for the signed in user
|
||||
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
|
||||
// Configure the sign in cookie
|
||||
app.UseCookieAuthentication(new CookieAuthenticationOptions
|
||||
{
|
||||
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
|
||||
LoginPath = new PathString("/Account/Login"),
|
||||
Provider = new CookieAuthenticationProvider
|
||||
{
|
||||
// Enables the application to validate the security stamp when the user logs in.
|
||||
// This is a security feature which is used when you change a password or add an external login to your account.
|
||||
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
|
||||
validateInterval: TimeSpan.FromMinutes(30),
|
||||
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
|
||||
}
|
||||
});
|
||||
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
|
||||
|
||||
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
|
||||
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
|
||||
|
||||
// Enables the application to remember the second login verification factor such as phone or email.
|
||||
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
|
||||
// This is similar to the RememberMe option when you log in.
|
||||
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
|
||||
|
||||
// Uncomment the following lines to enable logging in with third party login providers
|
||||
//app.UseMicrosoftAccountAuthentication(
|
||||
// clientId: "",
|
||||
// clientSecret: "");
|
||||
|
||||
//app.UseTwitterAuthentication(
|
||||
// consumerKey: "",
|
||||
// consumerSecret: "");
|
||||
|
||||
//app.UseFacebookAuthentication(
|
||||
// appId: "",
|
||||
// appSecret: "");
|
||||
|
||||
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
|
||||
//{
|
||||
// ClientId = "",
|
||||
// ClientSecret = ""
|
||||
//});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user