Exemplo n.º 1
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            try
            {
                ViewData["ReturnUrl"] = returnUrl;
                if (ModelState.IsValid)
                {
                    if (model.UserName.Contains("@"))
                    {
                        bool authentic          = false;
                        List <DomainUser> users = _findAllADUsers.FindAll(model.DomainId, model.UserName);

                        ApplicationUser        applicationUser  = new ApplicationUser();
                        List <ApplicationUser> applicationUsers = new List <ApplicationUser>();

                        foreach (var user in users)
                        {
                            applicationUser.UserName             = user.DisplayName;
                            applicationUser.FirstName            = user.FirstName;
                            applicationUser.LastName             = user.LastName;
                            applicationUser.Email                = user.Email;
                            applicationUser.EmailConfirmed       = true;
                            applicationUser.PhoneNumberConfirmed = true;
                            applicationUser.PhoneNumber          = "-";
                            applicationUser.Mobile               = "-";
                            applicationUser.AddedDate            = DateTime.Now;
                            applicationUsers.Add(applicationUser);
                        }
                        IQueryable <DomainSetting> domainSetting = _context.DomainSetting.Where(w => w.Id == model.DomainId);
                        string cipherText = "";
                        var    domain     = domainSetting.Select(w => new DomainSetting
                        {
                            UserName = w.UserName,
                            Server   = w.Server,
                            Title    = w.Title,
                            Password = w.Password
                        }).FirstOrDefault();
                        cipherText = _encriptdescriptStringRepository.DecryptString(domain.Password);
                        string   dcString = "";
                        string   rootNode = "";
                        string[] arrString;
                        arrString = domain.Title.Split('.');
                        if (arrString.Length == 1)
                        {
                            dcString = "dc=" + domain.Title + "";
                            rootNode = arrString[0];
                        }
                        else
                        {
                            for (int i = 0; i != arrString.Length; i++)
                            {
                                dcString += "dc=" + arrString[i].ToString() + ",";
                            }
                            if (arrString.Length == 3)
                            {
                                rootNode = arrString[1].ToString();
                            }
                            else if (arrString.Length == 2)
                            {
                                rootNode = arrString[0].ToString();
                            }
                            dcString = dcString.Substring(0, dcString.Length - 1);
                        }
                        string         DomainPath = "LDAP://" + domain.Server + "/" + dcString;
                        DirectoryEntry entry      = new DirectoryEntry("LDAP://" + domain.Server + "/" + dcString, model.UserName.Split("@")[0], model.Password);
                        try
                        {
                            object nativeObject = entry.NativeObject;

                            authentic = true;
                            byte[] salt = new byte[128 / 8];
                            model.Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                                        password: "******",
                                                                        salt: salt,
                                                                        prf: KeyDerivationPrf.HMACSHA1,
                                                                        iterationCount: 10000,
                                                                        numBytesRequested: 256 / 8));
                            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, true, false);

                            if (result.Succeeded)
                            {
                                return(RedirectToLocal(returnUrl));
                            }
                        }
                        catch (Exception e)
                        {
                            ModelState.AddModelError(string.Empty, Resources.Messages.InvalidLoginAttempt);
                            return(View(model));
                        }
                    }
                    else
                    {
                        IQueryable <DomainSetting> domainSetting = _context.DomainSetting.Where(w => w.Id == model.DomainId);

                        var domain = domainSetting.Select(w => new DomainSetting
                        {
                            Id    = w.Id,
                            Title = w.Title,
                        }).FirstOrDefault();

                        if (domain.Title == "کاربران سیستمی")
                        {
                            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, true, false);

                            if (result.Succeeded)
                            {
                                return(RedirectToLocal(returnUrl));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, Resources.Messages.InvaliDomainAttempt);
                            return(View(model));
                        }
                    }


                    ModelState.AddModelError(string.Empty, Resources.Messages.InvalidLoginAttempt);
                    return(View(model));
                }

                // If we got this far, something failed, redisplay form
                return(View(model));
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
                    RequestId = e.Message
                }));
            }
        }
        //[Authorize(Roles = "Admin")]
        // [ValidateAntiForgeryToken]
        public async Task <IActionResult> Create(DomainUserViewModel model)
        {
            try
            {
                model.message   = "";
                model.IsSuccess = false;
                bool ping = _pingLdap.Ping(model.DomainId, model.UserName);
                if (ping)
                {
                    List <DomainUser>      users            = _findAllADUsers.FindAll(model.DomainId, model.UserName);
                    ApplicationUser        applicationUser  = new ApplicationUser();
                    List <ApplicationUser> applicationUsers = new List <ApplicationUser>();
                    IdentityResult         result           = new IdentityResult();

                    if (users.Count > 0)
                    {
                        foreach (var user in users)
                        {
                            applicationUser.UserName             = user.UserName + "@" + user.dcString.Split("dc=")[1].Replace(",", ".") + user.dcString.Split(",dc=")[1];
                            applicationUser.FirstName            = user.FirstName;
                            applicationUser.LastName             = user.LastName;
                            applicationUser.Email                = user.Email;
                            applicationUser.EmailConfirmed       = true;
                            applicationUser.PhoneNumberConfirmed = true;
                            applicationUser.PhoneNumber          = "-";
                            applicationUser.Mobile               = "-";
                            applicationUser.AddedDate            = DateTime.Now;
                            applicationUsers.Add(applicationUser);
                        }

                        if (ModelState.IsValid)
                        {
                            byte[] salt = new byte[128 / 8];
                            model.PasswordHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                                            password: "******",
                                                                            salt: salt,
                                                                            prf: KeyDerivationPrf.HMACSHA1,
                                                                            iterationCount: 10000,
                                                                            numBytesRequested: 256 / 8));

                            foreach (var applicationUser1 in applicationUsers)
                            {
                                try
                                {
                                    result = await _userManager.CreateAsync(applicationUser1, model.PasswordHash);

                                    if (result.Succeeded)
                                    {
                                        //if (await _roleManager.FindByNameAsync(model.RoleType.ToString()) == null)
                                        //{

                                        //    await _roleManager.CreateAsync(new ApplicationRole
                                        //    {
                                        //        Name = model.RoleType.ToString(),
                                        //        NormalizedName = model.RoleType.ToString().ToUpper()
                                        //    });
                                        //}

                                        //await _userManager.AddToRoleAsync(applicationUser, model.RoleType.ToString());


                                        var systemRoles = _roleManager.Roles.ToList().Where(x => x.Id == model.RoleId);

                                        var roles = systemRoles.Select(x => x.Name).FirstOrDefault();
                                        if (roles != null)
                                        {
                                            await _userManager.AddToRoleAsync(applicationUser1, roles.ToString());
                                        }

                                        if (Request.Form.Keys.Contains("SaveAndReturn"))
                                        {
                                            model.IsSuccess = true;
                                            model.message   = "Sucsses";
                                            return(View(model));
                                        }
                                    }

                                    else
                                    {
                                        var errors = result.Errors.ToList();
                                        if (errors.Count > 0)
                                        {
                                            foreach (var error in errors)
                                            {
                                                AddErrors(result);
                                            }
                                        }

                                        else
                                        {
                                            model.IsSuccess = false;
                                            model.message   = "Error";
                                            return(View(model));
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    var a = e.Message;
                                }
                            }
                        }
                    }

                    else
                    {
                        var errors = result.Errors.ToList();
                        if (errors.Count > 0)
                        {
                            foreach (var error in errors)
                            {
                                AddErrors(result);
                            }
                        }

                        else
                        {
                            model.IsSuccess = false;
                            model.message   = "Error";
                            return(View(model));
                        }
                    }
                }

                else
                {
                    ModelState.AddModelError("", "دامین غیر فعال است.!");
                }


                return(View(model));
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
                return(View("~/Views/Shared/Error.cshtml", new ErrorViewModel {
                    RequestId = e.Message
                }));
            }
        }