Skip to content

Commit

Permalink
Day 14 - Login
Browse files Browse the repository at this point in the history
  • Loading branch information
fdeniz07 committed Sep 30, 2021
1 parent b0b5076 commit 3ddebda
Show file tree
Hide file tree
Showing 36 changed files with 827 additions and 149 deletions.
2 changes: 2 additions & 0 deletions BlogWeb/Areas/Admin/Controllers/CategoryController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
using CoreLayer.Utilities.Extensions;
using CoreLayer.Utilities.Results.ComplexTypes;
using EntityLayer.Dtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BlogWeb.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = "Admin,Editor")]
public class CategoryController : Controller
{
private readonly ICategoryService _categoryService;
Expand Down
5 changes: 2 additions & 3 deletions BlogWeb/Areas/Admin/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using BlogWeb.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace BlogWeb.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = "Admin,Editor")]
public class HomeController : Controller
{

Expand Down
133 changes: 128 additions & 5 deletions BlogWeb/Areas/Admin/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using AutoMapper;
using BlogWeb.Areas.Admin.Models;
using CoreLayer.Utilities.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

Expand All @@ -21,16 +22,19 @@ namespace BlogWeb.Areas.Admin.Controllers
public class UserController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly IWebHostEnvironment _env;
private readonly IMapper _mapper;

public UserController(UserManager<User> userManager, IMapper mapper, IWebHostEnvironment env)
public UserController(UserManager<User> userManager, IMapper mapper, IWebHostEnvironment env, SignInManager<User> signInManager)
{
_userManager = userManager;
_mapper = mapper;
_env = env;
_signInManager = signInManager;
}

[Authorize(Roles = "Admin")]
public async Task<IActionResult> Index()
{
var users = await _userManager.Users.ToListAsync();
Expand All @@ -42,6 +46,45 @@ public async Task<IActionResult> Index()
});
}

[HttpGet]
public IActionResult Login()
{
return View("UserLogin");
}

[HttpPost]
public async Task<IActionResult> Login(UserLoginDto userLoginDto)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(userLoginDto.Email);
if (user != null)
{
var result = await _signInManager.PasswordSignInAsync(user, userLoginDto.Password,
userLoginDto.RememberMe, false);// bu islem sonucunda bize bir result dönüyor.
if (result.Succeeded) // eger bir islem sonucunda result dönülüyorsa, basarili olup olmadigi her zaman kontrol edilir
{
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "E-posta adresiniz veya şifreniz yanlıştır.");
return View("UserLogin");
}
}
else
{
ModelState.AddModelError("", "E-posta adresiniz veya şifreniz yanlıştır.");
return View("UserLogin");
}
}
else
{
return View("UserLogin");
}
}

[Authorize(Roles = "Admin")]
[HttpGet]
public async Task<JsonResult> GetAllUsers()
{
Expand All @@ -57,12 +100,14 @@ public async Task<JsonResult> GetAllUsers()
return Json(userListDto);
}

[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult Add()
{
return PartialView("_UserAddPartial");
}

[Authorize(Roles = "Admin")]
[HttpPost]
public async Task<IActionResult> Add(UserAddDto userAddDto)
{
Expand Down Expand Up @@ -92,7 +137,7 @@ public async Task<IActionResult> Add(UserAddDto userAddDto)

if (ModelState.IsValid)
{
userAddDto.Image = await ImageUpload(userAddDto.UserName,userAddDto.ImageFile);
userAddDto.Image = await ImageUpload(userAddDto.UserName, userAddDto.ImageFile);
var user = _mapper.Map<User>(userAddDto);
var result = await _userManager.CreateAsync(user, userAddDto.Password); //burada bize IdentityResult dönüyor
if (result.Succeeded) //IdentityResult basarili ise
Expand Down Expand Up @@ -132,6 +177,24 @@ public async Task<IActionResult> Add(UserAddDto userAddDto)
return Json(userAddAjaxModelStateErrorModel);
}

[HttpGet]
public ViewResult AccessDenied()
{
return View();
}

[Authorize]
[HttpGet]
public async Task<IActionResult> Logut()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home", new
{
Area = ""
});
}

[Authorize(Roles = "Admin")]
public async Task<JsonResult> Delete(int userId)
{
var user = await _userManager.FindByIdAsync(userId.ToString());
Expand Down Expand Up @@ -164,6 +227,7 @@ public async Task<JsonResult> Delete(int userId)
}
}

[Authorize(Roles = "Admin")]
[HttpGet]
public async Task<PartialViewResult> Update(int userId)
{
Expand All @@ -172,6 +236,7 @@ public async Task<PartialViewResult> Update(int userId)
return PartialView("_UserUpdatePartial", userUpdateDto);
}

[Authorize(Roles = "Admin")]
[HttpPost]
public async Task<IActionResult> Update(UserUpdateDto userUpdateDto)
{
Expand Down Expand Up @@ -212,25 +277,82 @@ public async Task<IActionResult> Update(UserUpdateDto userUpdateDto)
{
foreach (var error in result.Errors) //hatalar kullaniciya model üzerinden json a dönüstürülerek yansitilir
{
ModelState.AddModelError("",error.Description);
ModelState.AddModelError("", error.Description);
}
var userUpdateErrorViewModel = JsonSerializer.Serialize(new UserUpdateAjaxViewModel //Basarisiz update isleminden sonra view e bir model dönüyoruz ki, frontend e kullanici bu bilgileri görsün
{
UserUpdateDto = userUpdateDto,
UserUpdatePartial = await this.RenderViewToStringAsync("_UserUpdatePartial", userUpdateDto)
UserUpdatePartial = await this.RenderViewToStringAsync("_UserUpdatePartial", userUpdateDto)
});
return Json(userUpdateErrorViewModel);
}
}
var userUpdateModelStateErrorViewModel = JsonSerializer.Serialize(new UserUpdateAjaxViewModel
var userUpdateModelStateErrorViewModel = JsonSerializer.Serialize(new UserUpdateAjaxViewModel
{
UserUpdateDto = userUpdateDto,
UserUpdatePartial = await this.RenderViewToStringAsync("_UserUpdatePartial", userUpdateDto)
});
return Json(userUpdateModelStateErrorViewModel);
}

[Authorize]
[HttpGet]
public async Task<ViewResult> ChangeDetails()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
var updateDto = _mapper.Map<UserUpdateDto>(user);
return View(updateDto);
}

[Authorize]
[HttpPost]
public async Task<ViewResult> ChangeDetails(UserUpdateDto userUpdateDto)
{
if (ModelState.IsValid)
{
bool isNewImageUploaded = false;
var oldUser = await _userManager.GetUserAsync(HttpContext.User); //kullaniciyi güncellemeden bilgilerini oturumdan alip, burada sakliyoruz
var oldUserImage = oldUser.Image; //kullanicinin eski resmini bir degiskene atiyoruz
if (userUpdateDto.ImageFile != null) //Eger kullanici yeni bir resim yüklerse
{
userUpdateDto.Image = await ImageUpload(userUpdateDto.UserName, userUpdateDto.ImageFile); //kullanicinin yeni resmini güncelle
if (oldUserImage!="defaultUser.png") // Diger kullanicilarinda kullandigi ortak resmin kontrolü yapiliyor, ortak resim ise silme isleminin önüne geciyoruz
{
isNewImageUploaded = true;
}
}

var updatedUser = _mapper.Map<UserUpdateDto, User>(userUpdateDto, oldUser);
var result = await _userManager.UpdateAsync(updatedUser); // bilgileri db ye kaydediyoruz
if (result.Succeeded) //Bu kullanıcı dogru sekilde db ye gönderilmisse,
{
if (isNewImageUploaded) // yeni bir resim db ye eklendiyse
{
ImageDelete(oldUserImage); //eski resmi db den siliyoruz
}
TempData.Add("SuccessMessage", $"{ updatedUser.UserName} adlı kullanıcı başarıyla güncellenmiştir.");
return View(userUpdateDto);
}
else //Kullanici güncelleme bilgileri db ye dogru sekilde yansimamissa,
{
foreach (var error in result.Errors) //hatalar kullaniciya model üzerinden json a dönüstürülerek yansitilir
{
ModelState.AddModelError("", error.Description);
}
return View(userUpdateDto);
}
}
return View(userUpdateDto);
}

[Authorize]
[HttpGet]
public ViewResult PasswordChange()
{
return View();
}

[Authorize(Roles = "Admin,Editor")]
public async Task<string> ImageUpload(string userName, IFormFile imageFile)
{
// ~/img/user.Picture
Expand All @@ -254,6 +376,7 @@ public async Task<string> ImageUpload(string userName, IFormFile imageFile)
return fileName; // FatihDeniz_587_5_38_12_28_09_2021.png - "~/img/user.Image"
}

[Authorize(Roles = "Admin,Editor")]
public bool ImageDelete(string imageName)
{
// Amac : Kullanici resmini güncelledikten sonra eski resmin sunucudan silinmesi veyahut silinen bir kullanicinin resmininde silinmesi
Expand Down
9 changes: 9 additions & 0 deletions BlogWeb/Areas/Admin/Models/UserViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using EntityLayer.Concrete;

namespace BlogWeb.Areas.Admin.Models
{
public class UserViewModel
{
public User User { get; set; }
}
}
12 changes: 12 additions & 0 deletions BlogWeb/Areas/Admin/Models/UserWithRolesViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using EntityLayer.Concrete;
using System.Collections.Generic;

namespace BlogWeb.Areas.Admin.Models
{
public class UserWithRolesViewModel
{
//Bu bölüm, yetkisiz kullanicilarin yetkisi olmayan bölümleri görmemesini saglar
public User User { get; set; }
public IList<string> Roles { get; set; }
}
}
30 changes: 30 additions & 0 deletions BlogWeb/Areas/Admin/ViewComponents/AdminMenuViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using BlogWeb.Areas.Admin.Models;
using EntityLayer.Concrete;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;

namespace BlogWeb.Areas.Admin.ViewComponents
{
public class AdminMenuViewComponent:ViewComponent
{
private readonly UserManager<User> _userManager;

public AdminMenuViewComponent(UserManager<User> userManager)
{
_userManager = userManager;
}

public ViewViewComponentResult Invoke()
{
var user = _userManager.GetUserAsync(HttpContext.User).Result;
var roles = _userManager.GetRolesAsync(user).Result;

return View(new UserWithRolesViewModel
{
User = user,
Roles = roles
});
}
}
}
27 changes: 27 additions & 0 deletions BlogWeb/Areas/Admin/ViewComponents/UserMenuViewComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using BlogWeb.Areas.Admin.Models;
using EntityLayer.Concrete;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;

namespace BlogWeb.Areas.Admin.ViewComponents
{
public class UserMenuViewComponent:ViewComponent
{
private readonly UserManager<User> _userManager;

public UserMenuViewComponent(UserManager<User> userManager)
{
_userManager = userManager;
}

public ViewViewComponentResult Invoke()
{
var user = _userManager.GetUserAsync(HttpContext.User).Result;
return View(new UserViewModel
{
User = user
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
@model BlogWeb.Areas.Admin.Models.UserWithRolesViewModel

<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">MENÜ</div>
<a class="nav-link" asp-area="Admin" asp-controller="Home" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div>
Dashboard
</a>
<div class="sb-sidenav-menu-heading">İçerikler</div>
<a class="nav-link" asp-area="Admin" asp-controller="Category" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-th-list"></i></div>
Kategoriler
</a>
<a class="nav-link" asp-area="Admin" asp-controller="Blog" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-file-alt"></i></div>
Makaleler
</a>
<a class="nav-link" asp-area="Admin" asp-controller="Comment" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-comments"></i></div>
Yorumlar
</a>
@if (Model.Roles.Any(r=>r.Equals("Admin")))
{
<div class="sb-sidenav-menu-heading">Kullanıcılar</div>
<a class="nav-link" asp-area="Admin" asp-controller="Role" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-user-shield"></i></div>
Roller
</a>
<a class="nav-link" asp-area="Admin" asp-controller="User" asp-action="Index">
<div class="sb-nav-link-icon"><i class="fas fa-users"></i></div>
Kullanıcılar
</a>
}
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Giriş Yapan Kullanıcı:</div>
@Model.User.UserName
</div>
</nav>
</div>
Loading

0 comments on commit 3ddebda

Please sign in to comment.