fixing controler

This commit is contained in:
matiduck 2019-05-19 19:48:41 +02:00
parent a0ea7446ef
commit ce30b8378f
5 changed files with 152 additions and 109 deletions

View File

@ -1,69 +1,69 @@
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using MovieBase.Models;
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using MovieBase.Models;
using MovieBase.DAL;
namespace MovieBase
{
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 = ""
//});
}
}
namespace MovieBase
{
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 = ""
//});
}
}
}

View File

@ -1,17 +1,17 @@
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using MovieBase.Models;
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using MovieBase.Models;
using MovieBase.ViewModels;
namespace MovieBase.Controllers
namespace MovieBase.Controllers
{
[Authorize]
public class AccountController : Controller
@ -424,7 +424,7 @@ namespace MovieBase.Controllers
base.Dispose(disposing);
}
#region Helpers
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
@ -481,6 +481,6 @@ namespace MovieBase.Controllers
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
#endregion
}
}

View File

@ -1,4 +1,6 @@
using MovieBase.DAL;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using MovieBase.DAL;
using MovieBase.Models;
using Newtonsoft.Json;
using PagedList;
@ -16,22 +18,45 @@ namespace MovieBase.Controllers
//[Authorize]
public class MovieController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private ApplicationUserManager _userManager;
private ApplicationDbContext db = new ApplicationDbContext();
public ApplicationUserManager AppUserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public MovieController()
{
}
// GET: Movie
public ActionResult Index(int? page, string searchString)
{
public ActionResult Index(int? page, string searchString)
{
//TODO: Pure hack, don't know how to pass object otherwise.
TempData["imdbMovie"] = null;
var movies = db.Movies.OrderBy(m => m.Title);
var userId = User.Identity.GetUserId();
var movies = db.Movies.Where(m => m.WatchedByUsers.Select(u => u.Id).Contains(userId));
if (!string.IsNullOrEmpty(searchString))
{
movies = db.Movies.Where(m => m.Title.Contains(searchString)).OrderBy(m => m.Title);
movies = movies.Where(m => m.Title.Contains(searchString));
}
ViewBag.SearchString = searchString;
int pageNumber = page ?? 1;
return View(movies.ToPagedList(pageNumber, 3));
return View(movies.OrderBy(m => m.Title).ToPagedList(pageNumber, 3));
}
// GET: Movie/Create
@ -58,8 +83,25 @@ namespace MovieBase.Controllers
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
var user = AppUserManager.FindById(User.Identity.GetUserId());
using(var dbcontext = new ApplicationDbContext())
{
if (dbcontext.Movies.Any(m => m.Title == movie.Title))
{
var dbMovie = dbcontext.Movies.FirstOrDefault(m => m.Title == movie.Title);
if(dbMovie.WatchedByUsers == null)
{
dbMovie.WatchedByUsers = new List<ApplicationUser>();
}
dbMovie.WatchedByUsers.Add(user);
}
else
{
movie.WatchedByUsers.Add(user);
dbcontext.Movies.Add(movie);
}
dbcontext.SaveChanges();
}
return RedirectToAction("Index");
}
}

View File

@ -9,23 +9,23 @@ using System.Web;
namespace MovieBase.DAL
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Movie> Movies { get; set; }
//public DbSet<Actor> Actors { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().Property(x => x.MovieId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//modelBuilder.Entity<Actor>().Property(x => x.ActorId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
@ -33,8 +33,8 @@ namespace MovieBase.DAL
//modelBuilder.Entity<Actor>().HasKey(actor => actor.ActorId);
//modelBuilder.Entity<Movie>().HasMany(movie => movie.StarringActors).WithMany(actor => actor.Movies);
modelBuilder.Entity<ApplicationUser>().HasMany(user => user.WatchedMovies).WithMany(movie => movie.WatchedByUsers);
base.OnModelCreating(modelBuilder);
}
modelBuilder.Entity<ApplicationUser>().HasMany(user => user.WatchedMovies).WithMany(movie => movie.WatchedByUsers);
base.OnModelCreating(modelBuilder);
}
}
}

View File

@ -10,5 +10,6 @@ namespace MovieBase
{
ConfigureAuth(app);
}
}
}