You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

410 lines
16 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. using Microsoft.AspNet.Identity;
  2. using Microsoft.AspNet.Identity.EntityFramework;
  3. using Microsoft.Owin.Security;
  4. using Sevomin.Models;
  5. using Sevomin.Models.Helpers;
  6. using Sevomin.Models.Repositories;
  7. using System;
  8. using System.Threading.Tasks;
  9. using System.Web;
  10. using System.Web.Mvc;
  11. using System.Linq;
  12. using System.Net.Mail;
  13. namespace Sevomin.WebFrontend.Controllers
  14. {
  15. public class AccountController : BaseController
  16. {
  17. public AccountController()
  18. : this(new SevominUserManager(new UserStore<User>(SevominDbContext.Current)))
  19. {
  20. }
  21. public AccountController(SevominUserManager userManager)
  22. {
  23. UserManager = userManager;
  24. }
  25. public SevominUserManager UserManager { get; private set; }
  26. private IAuthenticationManager AuthenticationManager
  27. {
  28. get
  29. {
  30. return HttpContext.GetOwinContext().Authentication;
  31. }
  32. }
  33. [HttpPost]
  34. [ValidateAntiForgeryToken]
  35. public async Task<ActionResult> Signup(SignupViewModel model)
  36. {
  37. User user;
  38. if (model.IsAvalin)
  39. {
  40. user = new Avalin(model.Email, model.DisplayName);
  41. user.SignUpDate = DateTime.UtcNow;
  42. }
  43. else
  44. {
  45. user = new Dovomin(model.Email, model.DisplayName, string.Empty);
  46. user.SignUpDate = DateTime.UtcNow;
  47. }
  48. user.DisplayName = model.DisplayName;
  49. user.Email = model.Email;
  50. user.ConfirmationCode = Sevomin.Models.User.GetConfirmationCode();
  51. var result = await UserManager.CreateAsync(user, model.Password);
  52. if (result.Succeeded)
  53. {
  54. RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(SevominDbContext.Current));
  55. if (!(await roleManager.RoleExistsAsync("Avalin")))
  56. await roleManager.CreateAsync(new IdentityRole("Avalin"));
  57. if (!(await roleManager.RoleExistsAsync("Dovomin")))
  58. await roleManager.CreateAsync(new IdentityRole("Dovomin"));
  59. //Todo: Check this
  60. UserManager.UserValidator = new UserValidator<User>(UserManager);
  61. if (user is Avalin)
  62. await UserManager.AddToRoleAsync(user.Id, "Avalin");
  63. else if(user is Dovomin)
  64. await UserManager.AddToRoleAsync(user.Id, "Dovomin");
  65. #if !DEBUG
  66. SevominEmailer emailer = new SevominEmailer();
  67. emailer.EmailType = EmailType.EmailConfirmation;
  68. emailer.Parameters.Add("display-name", user.DisplayName);
  69. emailer.Parameters.Add("confirmation-code", user.ConfirmationCode);
  70. await emailer.SendAsync(user.Email, true, false);
  71. #endif
  72. await SignInAsync(user, isPersistent: false);
  73. return RedirectToAction("MyProfile", "Account");
  74. }
  75. else
  76. {
  77. AddErrors(result);
  78. }
  79. return View("Intro", model);
  80. }
  81. public async Task<ActionResult> CheckUsername(string Email)
  82. {
  83. bool result = (await UserManager.FindByNameAsync(Email)) == null;
  84. if(result)
  85. return Json(true, JsonRequestBehavior.AllowGet);
  86. return Json("این ایمیل قبلا در سایت استفاده شده. کلمه عبور خود را فراموش کرده اید؟", JsonRequestBehavior.AllowGet);
  87. }
  88. public ActionResult ConfirmEmail(string code)
  89. {
  90. var user = UserRepository.Current.FindWithConfirmationCode(code);
  91. if (user == null)
  92. return HttpNotFound();
  93. if (Request.IsAuthenticated && User.Identity.Name.ToLower() != user.UserName.ToLower())
  94. {
  95. ViewBag.Result = new PostResultViewModel(false,
  96. string.Format("شما نمیتوانید با حساب کاربری {0} حساب دیگری را فعال کنید",
  97. User.Identity.Name));
  98. return View();
  99. }
  100. user.EmailConfirmed = true;
  101. user.ConfirmationCode = string.Empty;
  102. UserRepository.Current.Save();
  103. UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
  104. ViewBag.Result = new PostResultViewModel(true, string.Format("حساب کاربری شما با موفقیت تایید شد. لطفا {0} سایت شوید",
  105. HtmlHelper.GenerateLink
  106. (this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "وارد", "Login", "Login", "Account", null, null)));
  107. return View();
  108. }
  109. public ActionResult Login(string returnUrl)
  110. {
  111. if(Request.IsAuthenticated)
  112. return RedirectToAction("Index", "Home");
  113. ViewBag.ReturnUrl = returnUrl;
  114. return View();
  115. }
  116. [HttpPost]
  117. [ValidateAntiForgeryToken]
  118. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  119. {
  120. if (ModelState.IsValid)
  121. {
  122. var user = await UserManager.FindAsync(model.Username, model.Password);
  123. if (user != null)
  124. {
  125. await SignInAsync(user, true);
  126. return RedirectToLocal(returnUrl);
  127. }
  128. else
  129. {
  130. ModelState.AddModelError("", "نام کاربری و یا کلمه عبور وارد شده صحیح نمی باشد.");
  131. }
  132. }
  133. // If we got this far, something failed, redisplay form
  134. return View(model);
  135. }
  136. public ActionResult Logout()
  137. {
  138. AuthenticationManager.SignOut();
  139. return RedirectToAction("Index", "Home");
  140. }
  141. public ActionResult Forgot()
  142. {
  143. return View();
  144. }
  145. [HttpPost]
  146. [ValidateAntiForgeryToken]
  147. public async Task<ActionResult> Forgot(ForgotPasswordViewModel model)
  148. {
  149. var user = UserRepository.Current.Find(model.Email);
  150. if (user == null)
  151. {
  152. ViewBag.Result = new PostResultViewModel(false, "کاربری با این آدرس ایمیل یافت نشد. لطفا دوباره تلاش کنید.");
  153. return View();
  154. }
  155. user.ConfirmationCode = Sevomin.Models.User.GetConfirmationCode();
  156. UserRepository.Current.Save();
  157. #if !DEBUG
  158. SevominEmailer emailer = new SevominEmailer {EmailType = EmailType.PasswordReset};
  159. emailer.Parameters.Add("display-name", user.DisplayName);
  160. emailer.Parameters.Add("reset-code", user.ConfirmationCode);
  161. await emailer.SendAsync(user.Email, true, false);
  162. #endif
  163. ViewBag.Result = new PostResultViewModel(true, "آدرس بازیابی رمز عبور برای شما ارسال شد.");
  164. return View();
  165. }
  166. public ActionResult ResetPassword(string code)
  167. {
  168. var user = UserRepository.Current.FindWithConfirmationCode(code);
  169. if (user == null)
  170. return HttpNotFound();
  171. ViewBag.Code = code;
  172. return View();
  173. }
  174. [HttpPost]
  175. [ValidateAntiForgeryToken]
  176. public async Task<ActionResult> ResetPassword(string code, ResetPasswordViewModel model)
  177. {
  178. var user = UserRepository.Current.FindWithConfirmationCode(code);
  179. if (user == null)
  180. return HttpNotFound();
  181. await UserManager.RemovePasswordAsync(user.Id);
  182. await UserManager.AddPasswordAsync(user.Id, model.Password);
  183. user.ConfirmationCode = string.Empty;
  184. UserRepository.Current.Save();
  185. ViewBag.Result = new PostResultViewModel(true, "رمز عبور شما با موفقیت بازنشانی شد.");
  186. return View();
  187. }
  188. [Authorize]
  189. public ActionResult ChangePassword()
  190. {
  191. return View();
  192. }
  193. [Authorize]
  194. [HttpPost]
  195. public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
  196. {
  197. var user = await UserManager.FindAsync(User.Identity.Name, model.Password);
  198. if (user != null)
  199. {
  200. await UserManager.RemovePasswordAsync(user.Id);
  201. await UserManager.AddPasswordAsync(user.Id, model.NewPassword);
  202. UserRepository.Current.Save();
  203. ViewBag.Result = new PostResultViewModel(true, "رمز عبور شما با موفقیت به روز شد.");
  204. return View();
  205. }
  206. else
  207. {
  208. ViewBag.Result = new PostResultViewModel(false, "رمز عبور فعلی وارد شده با اطلاعات ما مطابقت ندارد. لطفا دوباره تلاش کنید.");
  209. return View();
  210. }
  211. }
  212. [Authorize(Roles = "Avalin,Dovomin")]
  213. public async Task<ActionResult> MyProfile(bool? success)
  214. {
  215. if (success.HasValue)
  216. {
  217. ViewBag.Result = new PostResultViewModel(success.Value, success.Value ? "پروفایل شما با موفقیت ویرایش شد." : "در ویرایش پروفایل شما خطایی رخ داده.");
  218. }
  219. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  220. if (u is Avalin)
  221. {
  222. return View("ProfileAvalin", new AvalinViewModel((Avalin)u));
  223. }
  224. else
  225. {
  226. Dovomin dovomin = (Dovomin)u;
  227. DovominViewModel dvm = new DovominViewModel(dovomin);
  228. ViewBag.OptOutEmail = dovomin.OptOutEmail;
  229. return View("ProfileDovomin", dvm);
  230. }
  231. }
  232. [Authorize(Roles = "Dovomin")]
  233. [HttpPost]
  234. public async Task<ActionResult> ProfileDovomin(string JalaliBirthDate, string FirstName,
  235. string LastName, string ContactPersonEMail, bool IsFullTime,
  236. bool IsPartTime, string Description, bool OptOutEmail, HttpPostedFileBase EnglishResume, HttpPostedFileBase PersianResume, FormCollection form)
  237. {
  238. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  239. if (u == null || !(u is Dovomin))
  240. throw new InvalidOperationException("نوع کاربر صحیح نیست");
  241. try
  242. {
  243. Dovomin dovomin = (Dovomin)u;
  244. dovomin.BirthDate = DateAssist.ValidateAndSetToMiladi(JalaliBirthDate);
  245. dovomin.Description = Description;
  246. dovomin.FirstName = FirstName;
  247. dovomin.LastName = LastName;
  248. dovomin.IsFulltime = IsFullTime;
  249. dovomin.IsPartTime = IsPartTime;
  250. dovomin.OptOutEmail = OptOutEmail;
  251. ParameterRepository.Current.AddParametersToDovomin(dovomin);
  252. foreach (var jp in dovomin.DovominParameters)
  253. {
  254. string value = form[string.Format("value-{0}", jp.Parameter.Id)];
  255. jp.SetValue(value);
  256. }
  257. if (EnglishResume != null)
  258. {
  259. dovomin.EnglishResume = string.Format("{0}-resume-en{2}", User.Identity.Name, "", System.IO.Path.GetExtension(EnglishResume.FileName));
  260. EnglishResume.SaveAs(System.IO.Path.Combine(Server.MapPath("~/App_Data/resumes"), dovomin.EnglishResume));
  261. }
  262. if (PersianResume != null)
  263. {
  264. dovomin.PersianResume = string.Format("{0}-resume-fa{2}", User.Identity.Name, "", System.IO.Path.GetExtension(PersianResume.FileName));
  265. PersianResume.SaveAs(System.IO.Path.Combine(Server.MapPath("~/App_Data/resumes"), dovomin.PersianResume));
  266. }
  267. SevominDbContext.Current.SaveChanges();
  268. return RedirectToAction("MyProfile", new { success = true });
  269. }
  270. catch (Exception)
  271. {
  272. throw;
  273. }
  274. }
  275. [Authorize(Roles = "Avalin")]
  276. [HttpPost]
  277. public async Task<ActionResult> ProfileAvalin(string CompanyName, string NationalId, string RegisterId,
  278. string Address, string CompanyPhoneNumber, string EMail)
  279. {
  280. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  281. try
  282. {
  283. if (u == null || !(u is Avalin))
  284. throw new InvalidOperationException("نوع کاربر صحیح نیست");
  285. Avalin avalin = (Avalin)u;
  286. avalin.CompanyName = CompanyName;
  287. avalin.NationalId = NationalId;
  288. avalin.RegisterId = RegisterId;
  289. avalin.Address = Address;
  290. avalin.CompanyPhoneNumber = CompanyPhoneNumber;
  291. avalin.Email = EMail;
  292. SevominDbContext.Current.SaveChanges();
  293. return RedirectToAction("MyProfile", new { success = true });
  294. }
  295. catch (Exception)
  296. {
  297. throw;
  298. }
  299. }
  300. public async Task<ActionResult> Dovomin(string userId)
  301. {
  302. User user = await UserManager.FindByIdAsync(userId);
  303. if ((user as Dovomin) == null)
  304. return HttpNotFound();
  305. if (!User.IsInRole("God"))
  306. {
  307. if (User.IsInRole("Dovomin"))
  308. {
  309. if (userId != user.Id)
  310. {
  311. return HttpNotFound();
  312. }
  313. else { }
  314. }
  315. else if (User.IsInRole("Avalin"))
  316. {
  317. Avalin avalin = (await UserManager.FindByNameAsync(User.Identity.Name)) as Avalin;
  318. bool showIt = avalin.Jobs.Any(j =>
  319. {
  320. bool ret = j.Applications.Any(c => c.DovominId == userId);
  321. return ret;
  322. });
  323. if (!showIt)
  324. return HttpNotFound();
  325. }
  326. }
  327. return View(new DovominViewModel(user as Dovomin));
  328. }
  329. private async Task SignInAsync(User user, bool isPersistent)
  330. {
  331. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  332. var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
  333. AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  334. }
  335. private ActionResult RedirectToLocal(string returnUrl)
  336. {
  337. if (Url.IsLocalUrl(returnUrl))
  338. {
  339. return Redirect(returnUrl);
  340. }
  341. else
  342. {
  343. return RedirectToAction("Index", "Home");
  344. }
  345. }
  346. private void AddErrors(IdentityResult result)
  347. {
  348. foreach (var error in result.Errors)
  349. {
  350. ModelState.AddModelError("", error);
  351. }
  352. }
  353. }
  354. }