Exemplo n.º 1
0
        public string ChangePassword(ApplicationUser user, string currentPassword, string newPassword)
        {
            string s = "";

            if (string.IsNullOrEmpty(user.Id))
            {
                s = "錯誤!無此帳號!";
                return(s);
            }
            int id = Convert.ToInt32(user.Id);
            var ur = _context.AppUsers.Find(id);

            if (ur != null)
            {
                // user's password encrypt by DES.
                string DESKey  = "84203025";
                var    checkPW = CryptoExtensions.DESEncrypt(currentPassword, DESKey);
                if (ur.Password == checkPW)
                {
                    var encryptPW = CryptoExtensions.DESEncrypt(newPassword, DESKey);   // Encrypt and check password.
                    ur.Password = encryptPW;
                    _context.Entry(ur).State = EntityState.Modified;
                    _context.SaveChanges();
                    s = "成功";
                    return(s);
                }
            }
            s = "錯誤!原密碼輸入不正確!";
            return(s);
        }
Exemplo n.º 2
0
        public ActionResult Create(AppUserModel appUser)
        {
            if (ModelState.IsValid)
            {
                AppUserModel user = _context.AppUsers.Where(u => u.UserName == appUser.UserName).FirstOrDefault();
                if (user != null)
                {
                    ModelState.AddModelError("", "使用者名稱重複");
                    return(View(appUser));
                }
                // user's password encrypt by DES.
                string DESKey    = "84203025";
                var    encryptPW = CryptoExtensions.DESEncrypt(appUser.Password, DESKey); // Encrypt and check password.
                appUser.Password         = encryptPW;
                appUser.DateCreated      = DateTime.Now;
                appUser.LastActivityDate = DateTime.Now;
                _context.AppUsers.Add(appUser);
                _context.SaveChanges();
                //
                //// Save log.
                //SystemLog log = new SystemLog();
                //log.LogClass = "系統管理者紀錄";
                //log.LogTime = DateTime.UtcNow.AddHours(8);
                //log.UserId = WebSecurity.CurrentUserId;
                //log.Action = "使用者維護 > 新增使用者 > " + newUser.FullName + "(" + newUser.UserName + ")";
                //db.SystemLogs.Add(log);
                //db.SaveChanges();
                //
                List <UserInRolesViewModel> uv = appUser.InRoles.Where(v => v.IsSelected == true).ToList();
                foreach (UserInRolesViewModel u in uv)
                {
                    roleManager.AddUserToRole(appUser.UserName, u.RoleName);
                }
                return(RedirectToAction("Index"));
            }

            appUser.InRoles = roleManager.GetRoles();
            return(View(appUser));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            /* Login from mail. */
            ViewData["MailDocId"] = HttpContext.Request.Form["MailDocId"];
            ViewData["MailType"]  = HttpContext.Request.Form["MailType"];
            string MailDocId = HttpContext.Request.Form["MailDocId"];
            string MailType  = HttpContext.Request.Form["MailType"].ToString();

            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (model.LoginType == "2") //系統帳密
                {
                    // Get the login user's details.
                    var loginUser = _context.AppUsers.Where(a => a.UserName == model.UserName).FirstOrDefault();
                    if (loginUser != null)
                    {
                        if (string.IsNullOrEmpty(loginUser.Password))
                        {
                            // vendor's password will default to unitoNo, if not changed.
                            var vendor = _context.BMEDVendors.Where(v => v.VendorId == loginUser.VendorId).FirstOrDefault();
                            if (vendor != null)
                            {
                                string defaultPW = vendor.UniteNo;
                                if (model.Password != defaultPW)
                                {
                                    ModelState.AddModelError(string.Empty, "密碼錯誤.");
                                    return(View(model));
                                }
                            }
                            else
                            {
                                ModelState.AddModelError(string.Empty, "查無廠商.");
                                return(View(model));
                            }
                        }
                        else
                        {
                            // user's password encrypt by DES.
                            string DESKey    = "84203025";
                            var    encryptPW = CryptoExtensions.DESEncrypt(model.Password, DESKey); // Encrypt and check password.
                            if (encryptPW != loginUser.Password)
                            {
                                ModelState.AddModelError(string.Empty, "密碼錯誤.");
                                return(View(model));
                            }
                        }
                        var user = new ApplicationUser {
                            Id = loginUser.Id.ToString(), UserName = model.UserName
                        };

                        await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = true });

                        _logger.LogInformation("使用者已經登入.");
                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return(RedirectToLocal(returnUrl));
                        }

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "帳號或密碼錯誤.");
                        return(View(model));
                    }
                }
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                //
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://dms.cch.org.tw:8080/");
                string url = "WebApi/Accounts/CheckPasswdForCch?id=" + model.UserName;
                url += "&pwd=" + HttpUtility.UrlEncode(model.Password, Encoding.GetEncoding("UTF-8"));
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(url);

                string rstr = "";
                if (response.IsSuccessStatusCode)
                {
                    rstr = await response.Content.ReadAsStringAsync();
                }
                client.Dispose();
                //
                //var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
                //if (result.Succeeded)
                if (rstr.Contains("成功")) //彰基2000帳號WebApi登入
                {
                    var findUser = _context.AppUsers.Where(a => a.UserName == model.UserName).FirstOrDefault();
                    if (findUser != null)    //AppUsers內搜尋該user detail
                    {
                        var signInId = _context.AppUsers.Where(a => a.UserName == model.UserName).First().Id.ToString();
                        var user     = new ApplicationUser {
                            Id = signInId, UserName = model.UserName
                        };

                        await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = true });

                        /* If login from mail. */
                        if (MailDocId != "")
                        {
                            if (MailType == "Edit")
                            {
                                var editDoc = _context.BMEDRepairFlows.Where(r => r.DocId == MailDocId).OrderByDescending(r => r.StepId)
                                              .FirstOrDefault();
                                int userId = _context.AppUsers.Where(a => a.UserName == model.UserName).First().Id;
                                /* 編輯流程在登入者身上,進入Edit,否則導回首頁 */
                                if (editDoc.Status == "?" && editDoc.UserId == userId)
                                {
                                    return(RedirectToAction(MailType, "Repair", new { Area = "", id = MailDocId }));
                                }
                                else
                                {
                                    return(RedirectToAction("Index", "Home"));
                                }
                            }
                            return(RedirectToAction(MailType, "Repair", new { Area = "", id = MailDocId }));
                        }

                        _logger.LogInformation("使用者已經登入.");
                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return(RedirectToLocal(returnUrl));
                        }

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "無此帳號.");
                        return(View(model));
                    }
                }
                //else  //外包帳號 or 值班帳號
                //{
                //    /* Check and get external user. */
                //    var ExternalUser = _context.ExternalUsers.Where(ex => ex.UserName == model.UserName).FirstOrDefault();
                //    if( ExternalUser != null && ExternalUser.Password == model.Password )
                //    {
                //        var signInId = ExternalUser.Id.ToString();
                //        var user = new ApplicationUser { Id = signInId, UserName = model.UserName };

                //        await _signInManager.SignInAsync(user, new AuthenticationProperties { IsPersistent = model.RememberMe });

                //        /* If login from mail. */
                //        if (MailDocId != "")
                //        {
                //            if (MailType == "Edit")
                //            {
                //                var editDoc = _context.RepairFlows.Where(r => r.DocId == MailDocId).OrderByDescending(r => r.StepId)
                //                                                  .FirstOrDefault();
                //                int userId = _context.AppUsers.Where(a => a.UserName == model.UserName).First().Id;
                //                /* 編輯流程在登入者身上,進入Edit,否則導回首頁 */
                //                if (editDoc.Status == "?" && editDoc.UserId == userId)
                //                {
                //                    return RedirectToAction(MailType, "Repair", new { Area = "", id = MailDocId });
                //                }
                //                else
                //                {
                //                    return RedirectToAction("Index", "Home");
                //                }
                //            }
                //            return RedirectToAction(MailType, "Repair", new { Area = "", id = MailDocId });
                //        }

                //        _logger.LogInformation("使用者已經登入.");
                //        if (!string.IsNullOrEmpty(returnUrl))
                //            return RedirectToLocal(returnUrl);

                //        return RedirectToAction("Index", "Home");
                //    }
                //    else
                //    {
                //        ModelState.AddModelError(string.Empty, "帳號或密碼錯誤.");
                //        return View(model);
                //    }
                //}
                //if (result.RequiresTwoFactor)
                //{
                //    return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
                //}
                //if (result.IsLockedOut)
                //{
                //    _logger.LogWarning("您的帳號被封鎖.");
                //    return RedirectToAction(nameof(Lockout));
                //}
                //else
                //{
                //    ModelState.AddModelError(string.Empty, "帳號或密碼錯誤.");
                //    return View(model);
                //}
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }