Добавил роли

parent ad067cc2
......@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Store.Models;
using Store.Models.Users;
using Store.Repositories.Interfaces;
using Store.ViewModels.Auths;
......@@ -36,7 +37,7 @@ public class AccountsController : Controller
{
if (user.Password.Equals(model.Password))
{
await AuthenticateAsync(user.Email);
await AuthenticateAsync(user);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "пароль введен неверно");
......@@ -71,13 +72,17 @@ public class AccountsController : Controller
var user = _userRepository.GetUserByEmail(viewModel.Email);
if (user is null)
{
_userRepository.Create(new User
var role = _userRepository.GetRoles().FirstOrDefault(s => s.Name == "user");
var newUser = new User
{
Email = viewModel.Email,
Password = viewModel.Password
});
Password = viewModel.Password,
RoleId = role?.Id,
Role = role
};
_userRepository.Create(newUser);
_userRepository.Save();
await AuthenticateAsync(viewModel.Email);
await AuthenticateAsync(newUser);
return RedirectToAction("Index", "Home");
}
......@@ -93,11 +98,12 @@ public class AccountsController : Controller
return RedirectToAction("Login");
}
private async Task AuthenticateAsync(string userName)
private async Task AuthenticateAsync(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, userName)
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Role?.Name)
};
ClaimsIdentity id = new ClaimsIdentity(
claims,
......
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Store.ViewModels;
namespace Store.Controllers;
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
......@@ -18,6 +20,7 @@ public class HomeController : Controller
return View();
}
[Authorize(Roles = "admin, user")]
public IActionResult Privacy()
{
return View();
......
......@@ -15,7 +15,7 @@ public static class ServicesAppExtension
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(opt =>
{
opt.LoginPath = new PathString("/Account/Login");
opt.LoginPath = new PathString("/Accounts/Login");
});
//repositories
......
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
......@@ -11,7 +12,7 @@ using Store.Models;
namespace Store.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20220718150011_Init")]
[Migration("20220718152553_Init")]
partial class Init
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
......@@ -23,7 +24,36 @@ namespace Store.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Store.Models.User", b =>
modelBuilder.Entity("Store.Models.Users.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1,
Name = "admin"
},
new
{
Id = 2,
Name = "user"
});
});
modelBuilder.Entity("Store.Models.Users.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
......@@ -39,9 +69,37 @@ namespace Store.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int?>("RoleId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("Users");
b.HasData(
new
{
Id = 1,
Email = "email@test",
Password = "1234",
RoleId = 1
});
});
modelBuilder.Entity("Store.Models.Users.User", b =>
{
b.HasOne("Store.Models.Users.Role", "Role")
.WithMany("Users")
.HasForeignKey("RoleId");
b.Navigation("Role");
});
modelBuilder.Entity("Store.Models.Users.Role", b =>
{
b.Navigation("Users");
});
#pragma warning restore 612, 618
}
......
......@@ -9,6 +9,19 @@ namespace Store.Migrations
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Roles",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Roles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
......@@ -16,18 +29,46 @@ namespace Store.Migrations
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Email = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false)
Password = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<int>(type: "integer", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
table.ForeignKey(
name: "FK_Users_Roles_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id");
});
migrationBuilder.InsertData(
table: "Roles",
columns: new[] { "Id", "Name" },
values: new object[,]
{
{ 1, "admin" },
{ 2, "user" }
});
migrationBuilder.InsertData(
table: "Users",
columns: new[] { "Id", "Email", "Password", "RoleId" },
values: new object[] { 1, "email@test", "1234", 1 });
migrationBuilder.CreateIndex(
name: "IX_Users_RoleId",
table: "Users",
column: "RoleId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "Roles");
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
......@@ -21,7 +22,36 @@ namespace Store.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Store.Models.User", b =>
modelBuilder.Entity("Store.Models.Users.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1,
Name = "admin"
},
new
{
Id = 2,
Name = "user"
});
});
modelBuilder.Entity("Store.Models.Users.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
......@@ -37,9 +67,37 @@ namespace Store.Migrations
.IsRequired()
.HasColumnType("text");
b.Property<int?>("RoleId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("Users");
b.HasData(
new
{
Id = 1,
Email = "email@test",
Password = "1234",
RoleId = 1
});
});
modelBuilder.Entity("Store.Models.Users.User", b =>
{
b.HasOne("Store.Models.Users.Role", "Role")
.WithMany("Users")
.HasForeignKey("RoleId");
b.Navigation("Role");
});
modelBuilder.Entity("Store.Models.Users.Role", b =>
{
b.Navigation("Users");
});
#pragma warning restore 612, 618
}
......
using Microsoft.EntityFrameworkCore;
using Store.Models.Users;
namespace Store.Models;
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> contextOptions) : base(contextOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Role>().HasData(new Role {Id = 1, Name = "admin"});
modelBuilder.Entity<Role>().HasData(new Role {Id = 2, Name = "user"});
modelBuilder.Entity<User>().HasData(new User {Id = 1, Email = "email@test", Password = "1234", RoleId = 1});
}
}
\ No newline at end of file
namespace Store.Models.Users;
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public List<User> Users { get; set; }
public Role()
{
Users = new List<User>();
}
}
\ No newline at end of file
namespace Store.Models;
namespace Store.Models.Users;
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public int? RoleId { get; set; }
public Role? Role { get; set; }
}
\ No newline at end of file
......@@ -27,6 +27,6 @@ app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
pattern: "{controller=Accounts}/{action=Login}");
app.Run();
\ No newline at end of file
using Store.Models;
using Store.Models.Users;
namespace Store.Repositories.Interfaces;
......@@ -6,4 +7,5 @@ public interface IUserRepository : IRepository<User>
{
User? GetUserById(int id);
User? GetUserByEmail(string email);
List<Role> GetRoles();
}
\ No newline at end of file
using Microsoft.EntityFrameworkCore;
using Store.Models;
using Store.Models.Users;
using Store.Repositories.Interfaces;
namespace Store.Repositories;
......@@ -34,11 +36,13 @@ public class UserRepository : IUserRepository
public User? GetUserById(int id)
{
return _context.Users.FirstOrDefault(s => s.Id == id);
return _context.Users.Include(u => u.Role).FirstOrDefault(s => s.Id == id);
}
public User? GetUserByEmail(string email)
{
return _context.Users.FirstOrDefault(s => s.Email == email);
return _context.Users.Include(u => u.Role).FirstOrDefault(s => s.Email == email);
}
public List<Role> GetRoles() => _context.Roles.ToList();
}
\ No newline at end of file
namespace Store.Services;
public class AuthService
{
}
\ No newline at end of file
namespace Store.Services;
public interface IAuthService
{
}
\ No newline at end of file
......@@ -14,4 +14,8 @@
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.5" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations" />
</ItemGroup>
</Project>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment