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

904 lines
39 KiB
C#

using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Resources;
using Weee.DAL;
using Weee.Filter;
using Weee.Models;
using Weee.ViewModels;
using System;
using log4net;
using System.Linq;
using System.Data.Entity;
using System.IO;
using CScommon;
using System.Threading;
using NLog;
using CaptchaMvc.Models;
using CaptchaMvc.Infrastructure;
using CaptchaMvc.Interface;
using System.Web.Configuration;
using Weee.Service;
using Customize.Insynerger.Interfaces;
using Customize.Insynerger;
using Weee.Models.Customize.Insynerger;
using Customize.ViewModels;
using System.Threading.Tasks;
using System.Net;
using System.Configuration;
using DocumentFormat.OpenXml.ExtendedProperties;
using Qcarbon.Interfaces.adminCheck;
using System.Web.Routing;
using Qcarbon.Database.adminCheck;
using Qcarbon.ViewModels.admin;
using NPOI.SS.Formula.PTG;
using System.Security.Principal;
using System.Security.Claims;
using Customize.ViewModels.Insynerger;
namespace Weee.Controllers
{
[AllowAnonymous]
//[MvcMultilanguage]disable obsolete warning, not sure OK or not
public class AccountController : QcarbonControllerBase
{
private readonly EmailService.Service service = DependencyResolver.Current.GetService<EmailService.Service>();//CFT-36
private readonly WeeeDataContext db;
private readonly UserManager<User> usermanager;
protected WeeeSiteInfoService _siteInfoService;
protected IadminCheckService _adminCheckService;
protected Logger log;
string CaptchaEnabled = WebConfigurationManager.AppSettings["CaptchaEnabled"];
private readonly string baseUrl = "";
public AccountController(WeeeDataContext d,UserManager<User> u, WeeeSiteInfoService siteInfoService)
:base(d)
{
db = d;
usermanager = u;
_siteInfoService = siteInfoService;
baseUrl = ConfigurationManager.AppSettings["InsynergerAPIurl"];
}
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
var userid = User.Identity.GetUserId();
_adminCheckService = new adminCheckService(db, userid);
log = NLog.LogManager.GetCurrentClassLogger();
}
[Route("account/logout")]
[Filter.MvcLog("Sign out")]
public ActionResult Logout()
{
HttpContext.GetOwinContext().Authentication.SignOut();
return RedirectToAction("index", "Home", new { area = "" });
}
[Route("account/release")]
[AllowAnonymous]
public ActionResult Release()
{
return View();
}
[Route("account/login")]
public async Task<ActionResult> Login(string returnurl, string where, string access_token)
{
Session.Clear();// .Abandon();
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
var ViewModel = new LoginViewModel();
// 思納捷轉址登入處
if (!string.IsNullOrWhiteSpace(access_token))
{
access_token= access_token.Trim();
User user = null;
if (ViewBag.SynergerOn)
{
HttpResponseRec httpRec = //await isa.myInfo2username(access_token);
await isa.login(ViewModel.UserName, ViewModel.Password, access_token);
if (httpRec.statusCode == HttpStatusCode.OK && httpRec.result!=null)
{
User usr = (User)httpRec.result;
user = (from a in db.Users
where a.UserName == usr.UserName
select a).FirstOrDefault();
if (user != null)
{
if (user.Company == null && user.CompanyID > 0)
user.Company = (from a in db.Companies
where a.ID == user.CompanyID
select a).FirstOrDefault();
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = usermanager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
{
IsPersistent = ViewModel.RememberMe
}, identity);
ViewModel.UserName = user.UserName;
ActionResult ret = normalCompanyLogin(ViewModel, user, identity, true, true); // isa.IsSynergerOn());
if (ret != null)
return ret;
}
else
ViewModel.errMsg = $"username {httpRec.result} not existed!";
}
else if (!string.IsNullOrWhiteSpace(httpRec.errorMessage))
ViewModel.errMsg = httpRec.errorMessage;
}
}
if (!string.IsNullOrWhiteSpace(ViewModel.errMsg))
ModelState.AddModelError("", ViewModel.errMsg);
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
ViewModel.CaptchaUse = CaptchaUse();
if (CaptchaUse())
ViewModel.CaptchaItem = GetCaptcha();
if (returnurl != null && returnurl.Contains("changepassword"))
{
return RedirectToAction("changepassword", "PROFILE", new { Length = 7});
}
if (returnurl != null && (User.Identity.IsAuthenticated))
{
if (User.IsInRole(ProgramConstants.admin))
{
return RedirectToAction("index", "home", new { area = "admin" });
}
else if (User.IsInRole(ProgramConstants.certification))
{
return RedirectToAction("index", "home", new { area = "certification" });
}
else if (User.IsInRole(ProgramConstants.normalcompany))
{
return RedirectToAction("index", "home");
}
}
/* to do: login layout is broken when user zoom in */
ViewModel.cmd = "登入";
ViewBag.ReturnUrl = returnurl;
if(where != null && where.Trim() != "" && where == "password")
{
ViewBag.SuccessSendResetPasswordEmail = Resource.SuccessSendResetPasswordEmail;
}
return View(ViewModel);
}
protected ActionResult normalCompanyLogin(LoginViewModel ViewModel, User user
, ClaimsIdentity identity, bool emailConfirmed, bool synergerLogined)
{
if (!_adminCheckService.adminCheckPass())//若未能規避權限控管檢查
{
try
{
AdminAccess aa = _adminCheckService.getAdminAccess();
if (aa == null)
throw new Exception("伺服器尚未匯入金鑰,請洽系統管理員處理");
DateTime td = DateTime.Today;
if (aa.activeStartDate > td || aa.activeEndDate < td)
throw new Exception($"伺服器不在金鑰可使用期間之中(" +
$"{aa.activeStartDate.Value.ToString("yyyy/MM/dd")}-" +
$"{aa.activeEndDate.Value.ToString("yyyy/MM/dd")})" +
$",請洽系統管理員處理");
//var userid = User.Identity.GetUserId();
IcompanyAdminCheckService _companyAdminCheckService = new companyAdminCheckService(db, user.Id);
int companyId = _companyAdminCheckService.userName2companyID(ViewModel.UserName);
companyAdminAccessVM caa = _companyAdminCheckService.getCompanyAdminAccessVM(companyId);
string tds = DateTime.Today.ToString("yyyy/MM/dd");
Thread.Sleep(10);
if (caa==null || caa.activeStartDate.CompareTo(tds) > 0 || caa.activeEndDate.CompareTo(tds) < 0)
throw new Exception($"您的帳戶不在可使用期間之中(" +
$"{caa.activeStartDate}-{caa.activeEndDate})" +
$",請洽系統管理員處理");
}
catch (Exception ex)
{
log.Error(ex);
log.Error(CScommon.Exceptions.inner(ex));
log.Error(ex.StackTrace);
ModelState.AddModelError("", ex.Message);
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
ViewModel.CaptchaUse = CaptchaUse();
if (CaptchaUse())
ViewModel.CaptchaItem = GetCaptcha();
return View(ViewModel);
}
}
if (usermanager.IsInRole(user.Id, ProgramConstants.normalcompany))
{
copyReportTemplate(CScommon.ProgramConstants.OrganizationExcelLCAdata, identity.Name);//盤查表
copyReportTemplate(CScommon.ProgramConstants.OrganizationExcelList, identity.Name);//清冊
copyReportTemplate(CScommon.ProgramConstants.OrganizationWordReport, identity.Name, true);//組織型報告書
copyReportTemplate(CScommon.ProgramConstants.OrganizationExcelLCArisk, identity.Name);//風險評估表
copyReportTemplate(CScommon.ProgramConstants.ProductWordReport, identity.Name, true);//產品型報告書
copyReportTemplate(CScommon.ProgramConstants.ProductExcelLCAdata, identity.Name, true);//產品型盤查表
copyReportTemplate(CScommon.ProgramConstants.ProductExcelList, identity.Name, true);//產品型清冊
copyReportTemplate(CScommon.ProgramConstants.ProductSensitivity, identity.Name, true);//敏感度分析
InsynergerPreloginVM synergerVM=new InsynergerPreloginVM();
synergerVM.id = ViewModel.UserName;
if (string.IsNullOrWhiteSpace(ViewModel.Password))
synergerVM.pd = "";
else
synergerVM.pd = CScommon.GoldenKeyEnDe.ToMD5( ViewModel.Password);
Session["synergerVM"]=synergerVM;
//if (synergerLogined)
if (false)//undone !!... 暫時關掉轉自動登入畫面
{
return RedirectToAction("Insynerger", "Home");//, new { area = "" });
}
else
return RedirectToAction("WeeeCarbonFootprint", "Home", new { area = "" });
}
if (emailConfirmed)
ModelState.AddModelError("", Resources.Resource.StaticLabelaccountpending);
else
return RedirectToAction("ResendConfirmEmail", "Account", new { userName = user.UserName });
return null;
}
[HttpPost]
[AllowAnonymous]
[Route("account/login")]
[Filter.MvcLog("Sign In")]
public async Task<ActionResult> Login(string returnurl, LoginViewModel ViewModel)
{
//Session.Clear();// .Abandon();
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
ViewModel.CaptchaUse = CaptchaUse();
if(CaptchaUse() && ViewModel != null && ViewModel.CaptchaItem != null)
{
if (!CheckCaptcha(ViewModel.CaptchaItem))
{
ViewModel.CaptchaItem = GetCaptcha();
ModelState.AddModelError("", "識別碼錯誤");
return View(ViewModel);
}
}
if (!string.IsNullOrWhiteSpace(ViewModel.cmd) &&
ViewModel.cmd.CompareTo(Resource.SignUp) == 0)
return RedirectToAction("Register");
string errMsg = "";
if (ModelState.IsValid)
{
User user = null;
bool synergerLogined = false;
if (ViewBag.SynergerOn)
{
HttpResponseRec httpRec =
await isa.login(ViewModel.UserName, ViewModel.Password);
if (httpRec.statusCode == HttpStatusCode.OK)
{
user = (from a in db.Users
where a.UserName == ViewModel.UserName
select a).FirstOrDefault();
if (user != null)
{
if (user.Company == null && user.CompanyID > 0)
{
user.Company = (from a in db.Companies
where a.ID == user.CompanyID
select a).FirstOrDefault();
}
synergerLogined = true;
}
}
else if (!string.IsNullOrWhiteSpace(httpRec.errorMessage))
errMsg = httpRec.errorMessage;
//else
// errMsg=httpRec.statusCode.ToString();
}
if (user==null && string.IsNullOrWhiteSpace(errMsg))
user = usermanager.Find(ViewModel.UserName, ViewModel.Password);
if (user == null)
{
if (errMsg == "")
errMsg = Resource.LoginFailed;
}
else
{
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = usermanager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
{
IsPersistent = ViewModel.RememberMe
}, identity);
if (returnurl != null)
return RedirectPermanent(returnurl);
bool emailConfirmed = user.EmailConfirmed;
if (user.Company == null)
{
if (usermanager.IsInRole(user.Id, ProgramConstants.admin))
return RedirectToAction("Index", "Home", new { area = "admin" });
if (emailConfirmed)
ModelState.AddModelError("", Resources.Resource.StaticLabelaccountpending);
else
return RedirectToAction("ResendConfirmEmail", "Account", new { userName = user.UserName });
}
else if (user.Company.CompanyType == typeof(CertificationCompany))
{
if (usermanager.IsInRole(user.Id, ProgramConstants.certification))
return RedirectToAction("Index", "Home", new { area = "certification" });
if (emailConfirmed)
ModelState.AddModelError("", Resources.Resource.StaticLabelaccountpending);
else
return RedirectToAction("ResendConfirmEmail", "Account", new { userName = user.UserName });
}
else if (user.Company.CompanyType == typeof(NormalCompany))
{
ActionResult ret = normalCompanyLogin(ViewModel, user, identity, emailConfirmed, synergerLogined);
if (ret != null)
return ret;
}
HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
ViewModel.CaptchaItem = GetCaptcha();
return View(ViewModel);
}
}
if (CaptchaUse() && ViewModel.CaptchaItem != null)
{
var vm = ViewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
ViewModel.CaptchaItem = GetCaptcha();
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", errMsg);// "The user name or password provided is incorrect.");
return View(ViewModel);
}
private void copyReportTemplate(string templateFile, string userName, bool rootAsWell=false)
{
string templateSourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data"
, templateFile);
string templateTargetPath ;
try
{
templateTargetPath = Server.MapPath( "~/Browser_Local/WebFilesRoot");
}
catch
{
templateTargetPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory
, "Browser_Local\\WebFilesRoot");
}
//Logger log = NLog.LogManager.GetCurrentClassLogger();
//log.Info($"copyReportTemplate templateTargetPath={templateTargetPath}");
string port = Request.ServerVariables["SERVER_PORT"];
if (!Directory.Exists(templateTargetPath))
{
if (port=="80" || port=="443")
throw new Exception($"virtual directory {templateTargetPath} WebFilesRoot does not exist!");
else
Directory.CreateDirectory(templateTargetPath);
}
string rootPath = templateTargetPath;
templateTargetPath = Path.Combine(templateTargetPath, userName);
if (!Directory.Exists(templateTargetPath))
Directory.CreateDirectory(templateTargetPath);
rootPath = Path.Combine(rootPath, templateFile);
templateTargetPath = Path.Combine(templateTargetPath, templateFile);
//always copy
Mutex mutex = new Mutex();
mutex.WaitOne();
for(int i=0; i<5; i++)
{
try
{
if (rootAsWell) {
if (System.IO.File.Exists(rootPath))
System.IO.File.Delete(rootPath);
System.IO.File.Copy(templateSourcePath, rootPath);
}
if (System.IO.File.Exists(templateTargetPath))
System.IO.File.Delete(templateTargetPath);
System.IO.File.Copy(templateSourcePath, templateTargetPath);
break;
}
catch
{
Task.Delay(1000);
}
}
mutex.ReleaseMutex();
}
[Route("account/CertificationRegister")]
public ActionResult CertificationRegister()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("account/CertificationRegister")]
public ActionResult CertificationRegister(CertificationRegisterViewModel viewModel)
{
if (ModelState.IsValid)
{
viewModel.User.IsCompanyAdmin = true;
viewModel.User.IsSystemAdmin = false;
viewModel.Company.Users.Add(viewModel.User);
var transac = db.Database.BeginTransaction();
try
{
db.Companies.Add(viewModel.Company);
db.SaveChanges();
usermanager.AddPassword(viewModel.User.Id, viewModel.Password);
db.SaveChanges();
transac.Commit();
}
catch(Exception ex)
{
transac.Rollback();
ex = CScommon.Exceptions.inner(ex);
Logger log = NLog.LogManager.GetCurrentClassLogger();
log.Error(ex.StackTrace);
throw;
}
return RedirectToAction("LOGIN", "ACCOUNT");
}
return View(viewModel);
}
[Route("account/Register")]
public ActionResult Register()
{
if (Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.SignOut();
return RedirectToAction("Register");
}
else
{
var re = new RegisterViewModel();
re.CaptchaUse = CaptchaUse();
if (CaptchaUse())
re.CaptchaItem = GetCaptcha();
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
ViewBag.OrganizationOnly = configB("OrganizationOnly");
return View(re);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("account/Register")]
[Filter.MvcLog("Register")]
public ActionResult Register(RegisterViewModel viewModel)
{
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
ViewBag.OrganizationOnly = configB("OrganizationOnly");
viewModel.CaptchaUse = CaptchaUse();
if (CaptchaUse() && viewModel != null && viewModel.CaptchaItem != null)
{
if (!CheckCaptcha(viewModel.CaptchaItem))
{
viewModel.CaptchaItem = GetCaptcha();
ModelState.AddModelError("", "識別碼錯誤");
return View(viewModel);
}
}
if (!string.IsNullOrWhiteSpace(viewModel.User.UserName) &&
usermanager.FindByName(viewModel.User.UserName) != null)
{
ModelState.AddModelError(string.Empty, Resource.UserAccountNameDuplicated);
if (CaptchaUse() && viewModel.CaptchaItem != null)
{
var vm = viewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
viewModel.CaptchaItem = GetCaptcha();
}
return View(viewModel);
}
//Start CFT-28
//if(!string.IsNullOrWhiteSpace(viewModel.Company.VATNumber))
//{
// string vatNumber = viewModel.Company.VATNumber.ToString().Trim();
// var query = db.Companies.Where(c => c.VATNumber.Trim() != null && c.VATNumber.Trim() != "" ? c.VATNumber.Trim().ToLower() == vatNumber.Trim().ToLower() : false).FirstOrDefault();
// if (query != null)
// {
// ModelState.AddModelError(string.Empty, Resource.VATNumberDuplicated);
// if (CaptchaUse() && viewModel.CaptchaItem != null)
// {
// var vm = viewModel.CaptchaItem;
// if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
// viewModel.CaptchaItem = GetCaptcha();
// }
// return View(viewModel);
// }
//}
//End CFT-28
if (ModelState.IsValid)
{
viewModel.User.IsCompanyAdmin = true;
viewModel.User.IsSystemAdmin = false;
viewModel.User.CreatedTime = DateTime.Now;
viewModel.Company.Users.Add(viewModel.User);
if (viewModel.IsAuditor && checkCertificationCompanyNameExist(viewModel.Company.Name))
{
ModelState.AddModelError(string.Empty, "公司名稱\"" + viewModel.Company.Name + "\"已存在");
if (CaptchaUse() && viewModel.CaptchaItem != null)
{
var vm = viewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
viewModel.CaptchaItem = GetCaptcha();
}
return View(viewModel);
}
using (var trans = db.Database.BeginTransaction())
{
//var trans = db.Database.BeginTransaction();
try
{
string err = CScommon.FieldCheck.loginID(viewModel.User.UserName);
if (err != "")
throw new Exception(err);
if (viewModel.SynergerGroupId!=null)
{
SynergerUser su = new SynergerUser();
su.groupId =(int) viewModel.SynergerGroupId;
su.userId = viewModel.User.Id;
su.isSelf = true;
db.SynergerUser.Add(su);
}
if (!viewModel.IsAuditor)//一般使用者
{
viewModel.Company.Fabs.Add(viewModel.Fab);
db.Companies.Add(viewModel.Company);
}
else//查證稽核使用者
{
string json =JsonUtl.fromT(viewModel.Company);
CertificationCompany cerComp =JsonUtl.toT<CertificationCompany>(json);
foreach (User usr in viewModel.Company.Users)
cerComp.Users.Add(usr);
db.Companies.Add(cerComp);
}
db.SaveChanges();
usermanager.AddPassword(viewModel.User.Id, viewModel.Password);
db.SaveChanges();
//trans.Commit();
//CFT-65
var UserAccountType = new UserAccountType();
UserAccountType.AccountType =(ACCOUNT_TYPE) viewModel.UserAccountType;
UserAccountType.UserId = viewModel.User.Id;
UserAccountType.StartTime = DateTime.Now;
UserAccountType.EndTime = DateTime.Now.AddMonths(1);
UserAccountType.Enabled = true;
db.UserAccountType.Add(UserAccountType);
db.SaveChanges();
//send email to register to confrim
service.SendRequestMessaageToAdminOrUser(
viewModel.User.Email, viewModel.User.UserName
, "user", "register", ViewBag.baseUrl);//CFT-36
ViewBag.RegistedMessage = Resource.RegistedSuccessful;
trans.Commit();
if (CaptchaUse() && viewModel.CaptchaItem != null)
{
var vm = viewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
viewModel.CaptchaItem = GetCaptcha();
}
return View(viewModel);
//return RedirectToAction("LOGIN", "ACCOUNT");
//End CFT-35
}
catch (Exception ex)
{
trans.Rollback();
Exception inn = CScommon.Exceptions.inner(ex);
string err = $"json:{JsonUtl.fromT(viewModel)}\n" +
$"message:{inn.Message}\n" +
$"stacktrace:{ex.StackTrace}";
writeLog(db, "", err);
Logger log = NLog.LogManager.GetCurrentClassLogger();
log.Error(ex.StackTrace);
ModelState.AddModelError(string.Empty, ex.Message);
if (CaptchaUse() && viewModel.CaptchaItem != null)
{
var vm = viewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
viewModel.CaptchaItem = GetCaptcha();
}
return View(viewModel);
}
}
}
if (CaptchaUse() && viewModel.CaptchaItem != null)
{
var vm = viewModel.CaptchaItem;
if (string.IsNullOrEmpty(vm.ImageUrl) || string.IsNullOrWhiteSpace(vm.tokenValue))
viewModel.CaptchaItem = GetCaptcha();
}
return View(viewModel);
}
//CFT-46
[Route("account/RegisterConfirm")]
public ActionResult RegisterConfirm(string key)
{
var siteInfo = _siteInfoService.GetWebSiteInfo();
try
{
if (siteInfo != null)
{
//ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
if (string.IsNullOrWhiteSpace(key))
throw new Exception("參數錯誤");
string userName = service.Decrypt(key);
var userInfo = db.Users.FirstOrDefault(u => u.UserName.Trim().ToLower() == userName);
if (userInfo != null)
{
userInfo.EmailConfirmed = true;
var entry = db.Entry(userInfo);
entry.State = EntityState.Modified;
db.SaveChanges();
//通知系統管理者開通帳號
//Start CFT-35
var email = db.Users.Where(u => u.IsSystemAdmin == true).Select(u => u.Email).FirstOrDefault();//CFT-36
service.SendRequestMessaageToAdminOrUser(email, userName
, "admin", "", ViewBag.baseUrl);//CFT-36
return View(siteInfo);
}
else
{
return RedirectToAction("Register");
}
}
catch (Exception ex)
{
Exception inn = CScommon.Exceptions.inner(ex);
ModelState.AddModelError(string.Empty, inn);
return View(siteInfo);
}
}
[Route("account/ResendConfirmEmail")]
public ActionResult ResendConfirmEmail(string userName)
{
ResendConfirmEmailViewModel ViewModel = new ResendConfirmEmailViewModel();
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
ViewBag.userName = userName;
return View(ViewModel);
}
[HttpPost]
[Route("account/ResendConfirmEmail")]
public ActionResult ResendConfirmEmail( ResendConfirmEmailViewModel ViewModel)
{
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
var email = ViewModel.Email;
string userName = ViewModel.UserName;
var info = db.Users.FirstOrDefault(u => u.UserName == ViewModel.UserName);
if(info != null)
{
info.Email = email;
db.Users.Attach(info);
db.SaveChanges();
//send email to register to confrim
service.SendRequestMessaageToAdminOrUser(email, userName
, "user", "register", ViewBag.baseUrl);
ViewBag.Message = Resource.SuccessSendEmail;
}
return View(ViewModel);
}
//End CFT-46
//CFT-45
[Route("account/ResetPassword")]
public ActionResult ResetPassword(string userName)
{
if (userName == null || userName.Trim() == "")
{
ViewBag.Message = Resource.UserNameRequired;
return RedirectToAction("LOGIN", "ACCOUNT");
}
var info = db.Users.FirstOrDefault(u => u.UserName == userName);
if (info != null)
{
//send email to register to confrim
service.SendRequestMessaageToAdminOrUser(info.Email
, info.UserName, "user", "password", ViewBag.baseUrl);
ViewBag.SuccessSendResetPasswordEmail = Resource.SuccessSendResetPasswordEmail;
}
return RedirectToAction("LOGIN","ACCOUNT", new { where = "password"});
}
[AllowAnonymous]
[Route("account/ForgetPass")]
public ActionResult ForgetPass(ForgetPassViewModel ViewModel)
{
var re = ViewModel;// new ForgetPassViewModel();
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
{
ViewModel.SiteInfo = siteInfo;
HttpContext.Application["customLoginImg"] = siteInfo.loginImagePath;
}
else
HttpContext.Application["customLoginImg"] = null;
IinsynergerAuthenticate isa = new insynergerAuthenticate(db, baseUrl);
ViewBag.SynergerOn = isa.IsSynergerOn();
if (ViewModel == null || ViewModel.DoSearch == 0)
return View(re);
if (ViewModel != null &&
!string.IsNullOrWhiteSpace(ViewModel.UserName) &&
!string.IsNullOrWhiteSpace(ViewModel.Email))
{
var list = db.Users.Where(x =>
x.Email == ViewModel.Email && x.UserName == ViewModel.UserName).ToList();
if (list != null && list.Count() > 0)
{
var info = list.FirstOrDefault();
//Logger log = NLog.LogManager.GetCurrentClassLogger();
//log.Info($"baseUrl={baseUrl} ViewBag.baseUrl={ViewBag.baseUrl}");
service.SendRequestMessaageToAdminOrUser(info.Email
, info.UserName, "user", "password", ViewBag.baseUrl);
ViewBag.SuccessSendResetPasswordEmail = Resource.SuccessSendResetPasswordEmail;
}
else
ModelState.AddModelError("", "帳號或Email錯誤");
}
else
ModelState.AddModelError("", "帳號或Email空白");
return View(re);
}
[Route("account/ConfirmResetPassword")]
[Filter.MvcLog("ConfirmResetPassword")]
public ActionResult ConfirmResetPassword(string key)
{
string userName = service.Decrypt(key);
var userInfo = db.Users.FirstOrDefault(u => u.UserName == userName);
if(userInfo != null)
{
return RedirectToAction("changepassword2", "PROFILE", new { key = key });
}
else
{
return RedirectToAction("LOGIN","ACCOUNT");
}
}
private string trimLeft(string oriS, string keyword) {
string ret = oriS;
int i = oriS.IndexOf(keyword);
if (i > 0)
ret = oriS.Substring(i);
return ret;
}
private CaptchaViewModel GetCaptcha()
{
var re = new CaptchaViewModel();
var parameterLength = new ParameterModel(DefaultCaptchaManager.LengthAttribute, 3);
var parameters = new ParameterModelContainer(new[] { parameterLength });
var info = CaptchaUtils.CaptchaManager.GenerateNew(this, parameters);
string trim2defaultCaptcha = trimLeft(info.ImageUrl, "DefaultCaptcha");
re.ImageUrl = trim2defaultCaptcha;// info.ImageUrl.Substring(2);
//log.Info($"ImageUrl={re.ImageUrl}");
re.tokenValue = info.TokenValue;
return re;
}
private bool CheckCaptcha(CaptchaViewModel model)
{
var captchaValue = CaptchaUtils.CaptchaManager.StorageProvider
.GetValue(model.CaptchaToken, TokenType.Validation);
if (captchaValue == null || !captchaValue.IsEqual(model.Captcha))
return false;
else
return true;
}
private bool CaptchaUse()
{
return CaptchaEnabled == "1";
}
[Route("account/version")]
[AllowAnonymous]
public ActionResult Version()
{
var ViewModel = new LoginViewModel();
var siteInfo = _siteInfoService.GetWebSiteInfo();
if (siteInfo != null)
ViewModel.SiteInfo = siteInfo;
return View(ViewModel);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool checkCertificationCompanyNameExist(string name)
{
var exist = (from a in db.Companies
join b in db.CertificationCompanies on a.ID equals b.ID
where a.Name == name
select a).Any();
return exist;
}
}
}