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.

401 lines
15 KiB

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