demo20230512/Areas/admin/Controllers/AccountController.cs
2023-05-12 10:20:28 +08:00

286 lines
9.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Weee.Areas.Admin.ViewModels;
using Weee.DAL;
using Weee.Models;
using Resources;
using System.Net;
using CScommon;
using Weee.Service;
using Weee.ViewModels;
namespace Weee.Areas.Admin.Controllers
{
public class AccountController : AdminControllerBase
{
private readonly UserManager<User> usermanager;
private readonly UserStore<User> userstore;
protected WeeeSiteInfoService _siteInfoService;
public AccountController(WeeeDataContext db, UserManager<User> u, UserStore<User> c, WeeeSiteInfoService siteInfoService) : base(db)
{
usermanager = u;
userstore = c;
_siteInfoService = siteInfoService;
}
public ActionResult Index()
{
return View(db.Users.Where(x => x.IsSystemAdmin).ToList());
}
public ActionResult UpdateProfile()
{
var id = User.Identity.GetUserId();
var viewModel = db.Users
.Where(x => x.Id == id)
.Select(x => new AccountUpdateProfileViewModel()
{
Id = x.Id,
AccountName = x.UserName,
Name = x.Name,
Email = x.Email
})
.Single();
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateProfile(AccountUpdateProfileViewModel viewModel)
{
if (User.Identity.GetUserId() != viewModel.Id)
{
ViewBag.ErrorMsg = Resource.AccountIsNotValid;
return View(viewModel);
}
var user = db.Users.Find(viewModel.Id);
user.Name = viewModel.Name;
user.Email = viewModel.Email;
db.SaveChanges();
ViewBag.SuccessMsg = Resource.SuccessUpdateProfile;
return View(viewModel);
}
public ActionResult ChangePassword()
{
var id = User.Identity.GetUserId();
var viewModel = db.Users
.Where(x => x.Id == id)
.Select(x => new AccountChangePasswordViewModel() { Id = x.Id })
.Single();
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(AccountChangePasswordViewModel viewModel)
{
var manager = DependencyResolver.Current.GetService<UserManager<Models.User>>();
var user = manager.Find(User.Identity.GetUserName(), viewModel.OriginalPassword ?? "");
if (user == null)
{
ViewBag.ErrorMsg = Resource.InvalidPasswordMsg;
return View();
}
if (!ModelState.IsValid || User.Identity.GetUserId() != viewModel.Id)
{
ViewBag.ErrorMsg = Resource.PwValidationConfirmationMsg;
return View();
}
//var passwordValidator = new PasswordValidator
//{
// RequiredLength = 6,
// RequireNonLetterOrDigit = false,
// RequireDigit = true,
// RequireLowercase = true,
// RequireUppercase = false,
//};
//var result = await passwordValidator.ValidateAsync(viewModel.NewPassword);
//if (!result.Succeeded)
//{
// ViewBag.ErrorMsg = Resource.PasswordRule;
// return View();
//}
string ck = PassWordUtl.PasswordCheck(viewModel.NewPassword);
if (!string.IsNullOrWhiteSpace(ck))
{
ViewBag.ErrorMsg = ck;
return View(new AccountChangePasswordViewModel());
}
var userId = usermanager.Find(User.Identity.GetUserName(), viewModel.OriginalPassword);
var hashed = usermanager.PasswordHasher.HashPassword(viewModel.NewPassword);
userstore.SetPasswordHashAsync(userId, hashed).Wait();
userstore.UpdateAsync(userId).Wait();
ViewBag.SuccessMsg = Resource.SuccessUpdatePassword;
return View(viewModel);
}
[AllowAnonymous]
public ActionResult login()
{
return RedirectToAction("login", "account", new { area = "" });
}
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult logout()
{
HttpContext.GetOwinContext().Authentication.SignOut();
return RedirectToAction("index", "Home", new { area = "" });
}
public ActionResult WebSiteInfoSet()
{
var re = new AccountWebSiteInfoSetViewModel();
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
re = JsonUtl.jsonCopy<WebSiteInfoViewModel, AccountWebSiteInfoSetViewModel>(siteInfo);
return View(re);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult WebSiteInfoSet(AccountWebSiteInfoSetViewModel viewModel)
{
var id = User.Identity.GetUserId();
if(!_siteInfoService.IsSysAdmin(id))
{
ViewBag.ErrorMsg = Resource.AccountIsNotValid;
return View(viewModel);
}
try
{
string errMsg = "";
var it = JsonUtl.jsonCopy<AccountWebSiteInfoSetViewModel, WebSiteInfoViewModel>(viewModel);
var result = _siteInfoService.SaveWebSiteInfo(it, out errMsg);
if (string.IsNullOrWhiteSpace(errMsg))
{
if (result != null)
{
viewModel.ID = result.ID;
viewModel.loginImagePath = result.loginImagePath;
}
TempData["SuccessMsg"] = Resource.SaveSuccess;
}
else
TempData["ErrorMsg"] = errMsg;
}
catch(Exception ex)
{
TempData["ErrorMsg"] = ex.Message;
}
return View(viewModel);
}
public ActionResult UploadImg()
{
if (Request == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
HttpPostedFileBase file = Request.Files["UploadedFile"];
try
{
var id = User.Identity.GetUserId();
if (!_siteInfoService.IsSysAdmin(id))
{
TempData["ErrorMsg"] = "只有SystemAdmin可以修改底圖";
return RedirectToAction("WebSiteInfoSet");
}
var list = db.UserAccountType.Where(x => x.UserId == id).ToList();
if (list == null || list.Count == 0)
{
TempData["ErrorMsg"] = "請先儲存再上傳圖檔";
return RedirectToAction("WebSiteInfoSet");
}
if (file == null || file.ContentLength == 0)
{
TempData["ErrorMsg"] = "未選擇檔案";
return RedirectToAction("WebSiteInfoSet");
}
string newFileName = ProgramConstants.WebSiteBackgroundImgNm + ".";
string fileFolder = ProgramConstants.WebSiteInfoPath;
if (!imgFileCk(file))
{
TempData["ErrorMsg"] = "上傳圖片檔案格式錯誤";
return RedirectToAction("WebSiteInfoSet");
}
string extesion = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
newFileName += extesion;
var storage = System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(Storage.AzureStorage)) as Storage.AzureStorage;
var uri = storage.SaveToAzure(file.InputStream, file.FileName, baseUrl, fileFolder, false
, newFileName);
var it = list.FirstOrDefault();
it.loginImagePath = newFileName;
db.SaveChanges();
TempData["SuccessMsg"] = "上傳圖片成功";
return RedirectToAction("WebSiteInfoSet");
}
catch (Exception ex)
{
TempData["ErrorMsg"] = ex.Message;
return RedirectToAction("WebSiteInfoSet");
}
}
public ActionResult DelSiteImg()
{
var id = User.Identity.GetUserId();
if (!_siteInfoService.IsSysAdmin(id))
{
TempData["ErrorMsg"] = "只有SystemAdmin可以刪除底圖";
return RedirectToAction("WebSiteInfoSet");
}
_siteInfoService.DelSiteImg();
TempData["SuccessMsg"] = "成功刪除圖片";
return RedirectToAction("WebSiteInfoSet");
}
private bool imgFileCk(HttpPostedFileBase file)
{
var formats = new List<string>() {"jpg", "png", "svg", "gif"};
if (file != null && file.ContentLength > 0)
{
string extesion = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
if (!string.IsNullOrWhiteSpace(extesion) && formats.Any(x => x == extesion.ToLower()))
return true;
else
return false;
}
return false;
}
}
}