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.

286 lines
10 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. int spaceIndex = model.DisplayName.IndexOf(' ');
  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. 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. await SignInAsync(user, isPersistent: false);
  65. return RedirectToAction("MyProfile", "Account");
  66. }
  67. else
  68. {
  69. AddErrors(result);
  70. }
  71. return View("Intro", model);
  72. }
  73. public async Task<ActionResult> CheckUsername(string Email)
  74. {
  75. bool result = (await UserManager.FindByNameAsync(Email)) == null;
  76. if(result)
  77. return Json(true, JsonRequestBehavior.AllowGet);
  78. return Json("این ایمیل قبلا در سایت استفاده شده. کلمه عبور خود را فراموش کرده اید؟", JsonRequestBehavior.AllowGet);
  79. }
  80. public ActionResult Login(string returnUrl)
  81. {
  82. if(Request.IsAuthenticated)
  83. return RedirectToAction("Index", "Home");
  84. ViewBag.ReturnUrl = returnUrl;
  85. return View();
  86. }
  87. [HttpPost]
  88. [ValidateAntiForgeryToken]
  89. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  90. {
  91. if (ModelState.IsValid)
  92. {
  93. var user = await UserManager.FindAsync(model.Username, model.Password);
  94. if (user != null)
  95. {
  96. await SignInAsync(user, true);
  97. return RedirectToLocal(returnUrl);
  98. }
  99. else
  100. {
  101. ModelState.AddModelError("", "نام کاربری و یا کلمه عبور وارد شده صحیح نمی باشد.");
  102. }
  103. }
  104. // If we got this far, something failed, redisplay form
  105. return View(model);
  106. }
  107. public ActionResult Logout()
  108. {
  109. AuthenticationManager.SignOut();
  110. return RedirectToAction("Index", "Home");
  111. }
  112. [Authorize]
  113. public async Task<ActionResult> MyProfile(bool? success)
  114. {
  115. if (success.HasValue)
  116. {
  117. ViewBag.Result = new PostResultViewModel(success.Value, success.Value ? "پروفایل شما با موفقیت ویرایش شد." : "در ویرایش پروفایل شما خطایی رخ داده.");
  118. }
  119. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  120. if (u is Avalin)
  121. {
  122. return View("ProfileAvalin", new AvalinViewModel(u as Avalin));
  123. }
  124. else
  125. {
  126. Dovomin dovomin = (Dovomin)u;
  127. DovominViewModel dvm = new DovominViewModel(dovomin);
  128. return View("ProfileDovomin", dvm);
  129. }
  130. }
  131. [Authorize]
  132. [HttpPost]
  133. public async Task<ActionResult> ProfileDovomin(string JalaliBirthDate, string FirstName,
  134. string LastName, string ContactPersonEMail, bool IsFullTime,
  135. bool IsPartTime, string Description, HttpPostedFileBase EnglishResume, HttpPostedFileBase PersianResume, FormCollection form)
  136. {
  137. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  138. if (u == null || !(u is Dovomin))
  139. throw new InvalidOperationException("نوع کاربر صحیح نیست");
  140. try
  141. {
  142. Dovomin dovomin = (Dovomin)u;
  143. dovomin.BirthDate = DateAssist.ValidateAndSetToMiladi(JalaliBirthDate);
  144. dovomin.Description = Description;
  145. dovomin.FirstName = FirstName;
  146. dovomin.LastName = LastName;
  147. dovomin.IsFulltime = IsFullTime;
  148. dovomin.IsPartTime = IsPartTime;
  149. ParameterRepository.Current.AddParametersToDovomin(dovomin);
  150. foreach (var jp in dovomin.DovominParameters)
  151. {
  152. string value = form[string.Format("value-{0}", jp.Parameter.Id)];
  153. jp.SetValue(value);
  154. }
  155. if (EnglishResume != null)
  156. {
  157. dovomin.EnglishResume = string.Format("{0}-resume-en{2}", User.Identity.Name, "", System.IO.Path.GetExtension(EnglishResume.FileName));
  158. EnglishResume.SaveAs(System.IO.Path.Combine(Server.MapPath("~/App_Data/resumes"), dovomin.EnglishResume));
  159. }
  160. if (PersianResume != null)
  161. {
  162. dovomin.PersianResume = string.Format("{0}-resume-fa{2}", User.Identity.Name, "", System.IO.Path.GetExtension(PersianResume.FileName));
  163. PersianResume.SaveAs(System.IO.Path.Combine(Server.MapPath("~/App_Data/resumes"), dovomin.PersianResume));
  164. }
  165. SevominDbContext.Current.SaveChanges();
  166. return RedirectToAction("MyProfile", new { success = true });
  167. }
  168. catch (Exception)
  169. {
  170. throw;
  171. }
  172. }
  173. [Authorize]
  174. [HttpPost]
  175. public async Task<ActionResult> ProfileAvalin(string CompanyName, string NationalId, string RegisterId,
  176. string Address, string CompanyPhoneNumber, string EMail)
  177. {
  178. User u = await UserManager.FindByNameAsync(User.Identity.Name);
  179. try
  180. {
  181. if (u == null || !(u is Avalin))
  182. throw new InvalidOperationException("نوع کاربر صحیح نیست");
  183. Avalin avalin = (Avalin)u;
  184. avalin.CompanyName = CompanyName;
  185. avalin.NationalId = NationalId;
  186. avalin.RegisterId = RegisterId;
  187. avalin.Address = Address;
  188. avalin.CompanyPhoneNumber = CompanyPhoneNumber;
  189. avalin.Email = EMail;
  190. SevominDbContext.Current.SaveChanges();
  191. return RedirectToAction("MyProfile", new { success = true });
  192. }
  193. catch (Exception)
  194. {
  195. throw;
  196. }
  197. }
  198. public async Task<ActionResult> Dovomin(string userId)
  199. {
  200. User user = await UserManager.FindByIdAsync(userId);
  201. if ((user as Dovomin) == null)
  202. return HttpNotFound();
  203. if (User.IsInRole("Dovomin"))
  204. {
  205. if (userId != user.Id)
  206. {
  207. return HttpNotFound();
  208. }
  209. else { }
  210. }
  211. else if (User.IsInRole("Avalin"))
  212. {
  213. Avalin avalin = (await UserManager.FindByNameAsync(User.Identity.Name)) as Avalin;
  214. bool showIt = avalin.Jobs.Any(j => {
  215. bool ret = j.Applications.Any(c => c.DovominId == userId);
  216. return ret;
  217. });
  218. if (!showIt)
  219. return HttpNotFound();
  220. }
  221. return View(new DovominViewModel(user as Dovomin));
  222. }
  223. private async Task SignInAsync(User user, bool isPersistent)
  224. {
  225. AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  226. var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
  227. AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  228. }
  229. private ActionResult RedirectToLocal(string returnUrl)
  230. {
  231. if (Url.IsLocalUrl(returnUrl))
  232. {
  233. return Redirect(returnUrl);
  234. }
  235. else
  236. {
  237. return RedirectToAction("Index", "Home");
  238. }
  239. }
  240. private void AddErrors(IdentityResult result)
  241. {
  242. foreach (var error in result.Errors)
  243. {
  244. ModelState.AddModelError("", error);
  245. }
  246. }
  247. }
  248. }