private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AllGroups          = ADService.GetAllGroups();
            cmbOUs.ItemsSource = ADService.GetAllOUs();

            for (int r = 0; r < cmbOUs.Items.Count; r++)
            {
                if (((OU)cmbOUs.Items[r]).Path == ActiveOU.Path)
                {
                    cmbOUs.SelectedIndex = r;
                    break;
                }
            }
            //cmbOUs.SelectedItem = ActiveOU;
            PopulateMemberShipGroups();
            PopulateAvailableGroups();
            DisplayMemberShipGroups();
            DisplayAvailableGroups();
            if (isNew)
            {
                ClearControls();
            }
            else
            {
                FillControls();
            }
        }
Beispiel #2
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            allADGroups = ADService.GetAllGroups();
            allADUsers  = ADService.GetAllUsers();
            if (isNew)
            {
                activeGroup       = new Group();
                txtGroupName.Text = "";
            }
            else
            {
                txtGroupName.Text   = activeGroup.SamAccountName;
                usersInActiveGroup  = GroupService.GetUsersInGroup(activeGroup.GroupPrincipal).OrderBy(g => g.SamAccountName).ToList();
                groupsInActiveGroup = GroupService.GetGroupsInGroup(activeGroup.GroupPrincipal).OrderBy(g => g.SamAccountName).ToList();
            }
            cmbOUs.ItemsSource = ADService.GetAllOUs();
            for (int r = 0; r < cmbOUs.Items.Count; r++)
            {
                if (((OU)cmbOUs.Items[r]).Path == activeOU.Path)
                {
                    cmbOUs.SelectedIndex = r;
                    break;
                }
            }

            PopulateUsersNotInGroups();
            PopulateGroupsNotInGroups();
            DisplayPopulations();
        }
Beispiel #3
0
        /// <summary>
        /// 驗證使用者是否登入成功(By AD)
        /// </summary>
        /// <param name="strUsername">登入帳號</param>
        /// <param name="strPassword">登入密碼</param>
        /// <returns>return boolean</returns>
        private bool ValidateLogin(string strUsername, string strPassword)
        {
            var result = false;

            var dc = WebConfigurationManager.AppSettings["DCName"];

            this.user = new UserViewModel
            {
                Roles = new[] { "user" },
                Name  = strUsername
            };
            var util = new Landpy.ActiveDirectory.Password.PasswordUnity();

            result = util.IsPasswordValid($"{dc}\\{strUsername}", strPassword);
            if (result)
            {
                using (var service = new ADService(WebUtils.GetAdOperator()))
                {
                    var userObject = service.Get(strUsername);
                    if (userObject.IsAccountOperator || userObject.IsDomainAdmin)
                    {
                        this.user.Roles = new[] { "user", "admin" };
                    }
                }
            }

            return(result);
        }
        public async Task <IActionResult> getCurrentEmployee(bool getAD = false)
        {
            // if(this.HostingEnvironment.EnvironmentName== Environments.Development)
            if (CurrentUser == "ENERGY\\d.khudairi.c" || CurrentUser == "ENERGY\\r.draiwaish.c")
            {
                getAD = true;
            }
            Employee employeedata = new Employee();

            try
            {
                employeedata = await EmployeeService.FindEmployeeWithEmailAsync(CurrentUserEmail);
            }
            catch {
                Logger.LogDebug($"can not get data for this email : {CurrentUserEmail}");
            }
            if (getAD)
            {
                var ademployee = await ADService.GetDataFromAD(CurrentUserEmail);

                var employee = Mapper.Map <Employee>(ademployee);
                Mapper.Map <ADService.ADReturned, Employee>(ademployee, employeedata);
                employeedata.Email = CurrentUserEmail;
            }
            return(Ok(employeedata));
        }
        /// <inheritdoc />
        public async Task <IToken> IsValidAsync(ICredentials creds)
        {
            var domain = ConfigurationManager.AppSettings.Get <string>("Domain", null);

            if (string.IsNullOrWhiteSpace(domain))
            {
                throw new Exception("The 'Domain' appsetting value in the web.config must be populated.");
            }

            var group = ConfigurationManager.AppSettings.Get <string>("DomainGroup", null);

            if (string.IsNullOrWhiteSpace(group))
            {
                throw new Exception("The 'DomainGroup' appsetting value in the web.config must be populated.");
            }

            var userDomain = GetDomain(creds.User) ?? domain;
            var netCreds   = new NetworkCredential(GetUserName(creds.User), creds.Password, userDomain);

            if (ADService.ValidateCredentialsAgainstDomain(netCreds) && ADService.IsUserInGroup(netCreds, domain, group))
            {
                var userClient = ClientsCache.Generic.GetValueOrNew <EntityClientAdminAsync <User, long>, bool>(typeof(User).Name, true);
                var odataUser  = await userClient.GetAsync(creds.User);

                IUser user = odataUser?.Object;
                if (user == null)
                {
                    user = await StoreUser(creds);
                }
                return(await BuildAsync(creds, user, odataUser?.RelatedEntityCollection));
            }
            return(null);
        }
Beispiel #6
0
        public ADServiceFixture()
        {
            Configuration = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json", optional: false)
                            .Build();

            LoggerFactory = new LoggerFactory();

            ADService = new ADService(Configuration, LoggerFactory.CreateLogger <ADService>());
        }
Beispiel #7
0
        public override bool IsValid(object value)
        {
            var matricula = value as string;

            if (string.IsNullOrEmpty(matricula))
            {
                return(true);
            }

            var ADService = new ADService();

            return(ADService.ValidaMatricula(matricula));
        }
Beispiel #8
0
        private void BuildTreeView()
        {
            List <OU> oUs = ADService.GetBaseOUs();

            TVOU.Items.Clear();
            foreach (OU ou in oUs)
            {
                TreeViewItem treeViewItem = new TreeViewItem();
                treeViewItem.Tag    = ou;
                treeViewItem.Header = ou.DirectoryEntry.Name;
                BuildTreeViewRecursive(treeViewItem, ou);
                TVOU.Items.Add(treeViewItem);
            }
        }
Beispiel #9
0
        public static string GetSlideAd(int positionId)
        {
            string slideAdHTML = String.Empty;

            List <ADModuleForSite> ads = ADService.GetSlideAdByPosition(positionId);

            if (ads != null)
            {
                StringBuilder strb = new StringBuilder("<div id='adShow'>");

                string adHTMLTemplate = @"<a href='{0}'>
                    <img alt='{1}' src='{2}' width='780' height='277'></a>";

                for (int j = 0; j < ads.Count; j++)
                {
                    string image = YoeJoyConfig.ImgVirtualPathBase + ads[j].ADImg;
                    if (j == 0)
                    {
                        strb.Append(String.Format(@"<a class='show' href='{0}'><img alt='{1}' src='{2}' width='780' height='277'></a>", ads[j].ADLink, ads[j].ADName, image));
                    }
                    else
                    {
                        strb.Append(String.Format(adHTMLTemplate, ads[j].ADLink, ads[j].ADName, image));
                    }
                }

                strb.Append("<div class='btItem'>");

                if (ads.Count > 0)
                {
                    for (int i = 1; i <= ads.Count; i++)
                    {
                        if (i == 1)
                        {
                            strb.Append(String.Format("<a class='selected' href='javascript:'>{0}</a>", i));
                        }
                        else
                        {
                            strb.Append(String.Format("<a href='javascript:'>{0}</a>", i));
                        }
                    }
                }

                strb.Append("</div>");
                strb.Append("</div>");
                slideAdHTML = strb.ToString();
            }
            return(slideAdHTML);
        }
Beispiel #10
0
        public async Task <Employee> GetCreationEmployeeData(string email)
        {
            var employeedata = await employeeService.FindEmployeeWithEmailAsync(email);

            Employee employee = null;

            if (employeedata == null)
            {
                var adData = await ADService.GetDataFromAD(email);

                employee = Mapper.Map <Employee>(adData);
            }
            else
            {
                employee = Mapper.Map <Employee>(employeedata);
            }
            return(employee);
        }
Beispiel #11
0
        public virtual async Task <ActionResult> SyncUsers()
        {
            string token = await ADService.GetTokenForApplication();

            if (token == null)
            {
                return(RedirectToAction("SignIn", MVC.Account.Name));
            }

            var result = await ADService.GetUsers();

            IEnumerable <IUser> users = result.CurrentPage.ToList();

            var myId             = CurrentUserId;
            var defaultRole      = RoleRepository.Single(x => x.Name == "User");
            var currentEmployees = EmployeeRepository.Select(x => x.Id);

            var appUsers = users.Where(x => x.GivenName != null).Select(x => new Employee()
            {
                Id                      = x.ObjectId,
                Email                   = x.Mail,
                Role                    = defaultRole,
                Name                    = x.DisplayName,
                PhoneNumber             = x.Mobile,
                IsInitialized           = false,
                VacationMessages        = false,
                RequestMessages         = false,
                MonthlyBirthdayMessages = false,
                DailyBirthdayMessages   = false,
                VacationDays            = 28
            });

            var newUsers = appUsers.Where(x => !currentEmployees.Contains(x.Id));

            EmployeeRepository.AddRange(newUsers);

            EmployeeRepository.Commit();

            return(View(MVC.Admin.Views.EditEmployees, new WorkersViewModel()
            {
                Employees = EmployeeRepository.AsDto()
            }));
        }
Beispiel #12
0
        public static string GetSiteStaticAd(int positionId, string cssClass, string width, string height)
        {
            string          siteAdHTML      = String.Empty;
            string          imageVitualPath = ConfigurationManager.AppSettings["ImageVitrualPath"].ToString();
            ADModuleForSite ad = ADService.GetHomeAdByPosition(positionId);

            if (ad != null)
            {
                string adImg = String.Concat(imageVitualPath, ad.ADImg);
                if (String.IsNullOrEmpty(width) || String.IsNullOrEmpty(height))
                {
                    siteAdHTML = String.Format("<a class='{0}' href='{1}' target='_blank' ><img src='{2}' alt='{3}' /></a>", cssClass, ad.ADLink, adImg, ad.ADName);
                }
                else
                {
                    siteAdHTML = String.Format("<a class='{0}' href='{1}' target='_blank' ><img width='{2}' height='{3}' src='{4}' alt='{5}' /></a>", cssClass, ad.ADLink, width, height, adImg, ad.ADName);
                }
            }
            return(siteAdHTML);
        }
        public async Task <Employee> GetResignedEmployeeData(string email)
        {
            var employeedata = await employeeService.GetEmployeeFromREST(email);

            Employee employee = null;

            if (employeedata == null)
            {
                var adData = await ADService.GetDataFromAD(email);

                employee = Mapper.Map <Employee>(adData);
            }
            else
            {
                employee = Mapper.Map <Department, Employee>(employeedata.Department);
                Mapper.Map <EmployeeRest, Employee>(employeedata, employee);
                return(employee);
            }
            return(employee);
        }
        public ActionResult Signin(LoginModel model, string returnUrl)
        {
            try
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    if (!ADService.IsAuthGroup(model.UserName))
                    {
                        this.ModelState.AddModelError(string.Empty, "이용 가능한 사용자 그룹에 속해 있지 않습니다.");
                        return(this.View(model));
                    }
                    if (!IsRoledUser(model.UserName))
                    {
                        this.ModelState.AddModelError(string.Empty, "등록 되지 않은 사용자 입니다.");
                        return(this.View(model));
                    }

                    initFirstLogin(model.UserName);
                    // View
                    FormsAuthentication.SetAuthCookie(model.UserName, true);
                    if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(this.Redirect(returnUrl));
                    }

                    return(this.RedirectToAction("Dashboard", "Dashboard"));
                }
            }
            catch (Exception e) {
                log.Error(e);
                Console.WriteLine(e);
                this.ModelState.AddModelError(string.Empty, e.Message);
                return(this.View(model));
            }

            this.ModelState.AddModelError(string.Empty, "사용자 계정 정보가 정확하지 않습니다.");

            return(this.View(model));
        }
Beispiel #15
0
        public void InsertValue(ADUserViewModel value)
        {
            try
            {
                if (this.ModelState.IsValid)
                {
                    var adOperator = WebUtils.GetAdOperator();

                    using (var service = new ADService(adOperator))
                    {
                        value.ADType = ADType.Vpn;
                        service.CreateUser(value);
                        WebUtils.ShowAjaxMessage(this.Page, "作業完成");
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
                this.ModelState.AddModelError("VPN", e.Message);
            }
        }
Beispiel #16
0
    /// <summary>
    /// AD驗證
    /// </summary>
    /// <param name="UserID">帳號</param>
    /// <param name="UserPwd">密碼</param>
    /// <returns></returns>
    private bool Check_AD(string UserID, string UserPwd, out string ErrMsg)
    {
        try
        {
            //呼叫ADService
            ADService ADSrv = new ADService();
            //輸入帳號
            ADSrv.AD_UserName = UserID;
            //輸入密碼
            ADSrv.AD_UserPwd = UserPwd;
            //取得回傳字串集
            StringCollection collectAttr = ADSrv.getADAttributes(out ErrMsg);
            if (collectAttr != null)
            {
                //先清除Cookie
                HttpCookie myCookie = new HttpCookie("PKSign_MemberInfo");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);

                #region -- Cookie處理 --

                //產生Cookie
                HttpCookie cMemberInfo = new HttpCookie("PKSign_MemberInfo");

                //設定多值
                cMemberInfo.Values.Add("MemberID", collectAttr[3]);                     //AD Guid
                //cMemberInfo.Values.Add("MemberAcct", collectAttr[2]);   //登入工號
                cMemberInfo.Values.Add("MemberName", Server.UrlEncode(collectAttr[1])); //名稱


                //判斷是否要記住帳號
                if (this.cb_Remember.Checked)
                {
                    cMemberInfo.Values.Add("RememberMe", "Y");  //記住我
                    //設定到期日(12個月)
                    cMemberInfo.Expires = DateTime.Now.AddMonths(12);
                }
                else
                {
                    cMemberInfo.Values.Add("RememberMe", "N");  //記住我(N)
                    //不設定到期日, 基本上瀏覽器關閉就會消失
                }

                //寫到用戶端
                Response.Cookies.Add(cMemberInfo);

                #endregion

                return(true);
            }
            else
            {
                //AD驗證不通過
                return(false);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
Beispiel #17
0
        /// <summary>
        /// AD列表
        /// </summary>
        /// <param name="title"></param>
        /// <param name="dateTime"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult Index(int pageIndex = 1)
        {
            int pageSize = int.Parse(AppSettingManager.AppSettings["ComonListPageNum"].ToString());

            ViewBag.CurPage  = pageIndex;
            ViewBag.PageSize = pageSize;
            string        title            = Request["title"];
            string        showStatus       = Request["ShowStatus"];
            string        dateBegin        = Request["DateBegin"];
            string        dateEnd          = Request["DateEnd"];
            string        positionId       = Request["PositionId"];
            string        positionParentId = Request["PositionParentId"];
            string        menPositionIds   = "2,20001,20002,20003,20004,20005,20006,20007,20008";
            string        womenPositionIds = "1,10001,10002,10003,10004,10005,10006,10007,10008";
            List <string> positionIds      = new List <string>()
            {
            };

            if (positionId == "1" && positionParentId == "0")
            {
                positionIds = womenPositionIds.Split(',').ToList();
            }
            else if (positionId == "2" && positionParentId == "0")
            {
                positionIds = menPositionIds.Split(',').ToList();
            }
            else if (!string.IsNullOrEmpty(positionId))
            {
                positionIds.Add(positionId);
            }
            Dictionary <string, object> dicParam = new Dictionary <string, object>();

            if (string.IsNullOrEmpty(title))
            {
                dicParam.Add("Title", "");
            }
            else
            {
                dicParam.Add("Title", title.Trim());
            }
            if (string.IsNullOrEmpty(showStatus) || showStatus == "0")
            {
                dicParam.Add("ShowStatus", "");
            }
            else
            {
                dicParam.Add("ShowStatus", int.Parse(Request["ShowStatus"]));
            }
            if (string.IsNullOrEmpty(dateBegin))
            {
                dicParam.Add("DateBegin", "");
            }
            else
            {
                dicParam.Add("DateBegin", Convert.ToDateTime(Request["DateBegin"]));
            }
            if (string.IsNullOrEmpty(dateEnd))
            {
                dicParam.Add("DateEnd", "");
            }
            else
            {
                dicParam.Add("DateEnd", Convert.ToDateTime(Request["DateEnd"]));
            }

            if (positionIds.Count > 0)
            {
                dicParam.Add("PositionId", positionIds);
            }
            else
            {
                dicParam.Add("PositionId", "");
            }
            if (string.IsNullOrEmpty(positionParentId) || positionParentId == "0")
            {
                dicParam.Add("PositionParentId", "");
            }
            else
            {
                dicParam.Add("PositionParentId", int.Parse(Request["PositionParentId"]));
            }
            dicParam.Add("SiteNo", "1");
            IList <WfsCmsContent> list = new ADService().GetADList(dicParam, positionIds);

            ViewBag.Count            = list.Count();
            list                     = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();//默认每页显示20条数据
            ViewBag.List             = list;
            ViewBag.Titles           = title ?? "";
            ViewBag.DateBegin        = dateBegin ?? "";
            ViewBag.DateEnd          = dateEnd ?? "";
            ViewBag.ShowStatus       = showStatus;
            ViewBag.PositionId       = positionId;
            ViewBag.PositionParentId = positionParentId;

            return(View());
        }
        public JsonResult GetFullName(string userid)
        {
            ADService aDService = new ADService();

            return(Json(aDService.getFullName(userid)));
        }
 public AuthService()
 {
     _Ad = new ADService();
 }
Beispiel #20
0
        public virtual async Task <ActionResult> InitializeAccount(ChangeAccountSettingsViewModel model)
        {
            if (EmployeeRepository.SingleOrDefault(x => x.Id == CurrentUserId) != null)
            {
                var employee = EmployeeRepository.First(x => x.Id == CurrentUser.Id);
                employee.PhoneNumber             = model.Phone;
                employee.MonthlyBirthdayMessages = model.MonthlyBirthdayMessages;
                employee.DailyBirthdayMessages   = model.DailyBirthdayMessages;
                employee.RequestMessages         = model.RequestMessages;
                employee.VacationMessages        = model.VacationMessages;
                employee.Skype            = model.Skype;
                employee.SocialSecurityID = model.SocialSecurityID;
                employee.IsInitialized    = true;

                if (model.BirthDay != null)
                {
                    employee.Birthdate = model.BirthDay;
                }

                EmployeeRepository.SaveOrUpdate(employee);
                EmployeeRepository.Commit();
            }
            else
            {
                IPagedCollection <IUser> result = await ADService.GetUsers();

                IUser user        = result.CurrentPage.Single(x => x.ObjectId == CurrentUserId);
                var   defaultRole = RoleRepository.Single(x => x.Name == "User");

                var employee = new Employee()
                {
                    Id                      = user.ObjectId,
                    Name                    = user.DisplayName,
                    Email                   = user.Mail,
                    Role                    = defaultRole,
                    PhoneNumber             = model.Phone,
                    IsInitialized           = true,
                    VacationDays            = 28,
                    VacationMessages        = model.VacationMessages,
                    RequestMessages         = model.RequestMessages,
                    MonthlyBirthdayMessages = model.MonthlyBirthdayMessages,
                    DailyBirthdayMessages   = model.DailyBirthdayMessages,
                    Birthdate               = model.BirthDay,
                    Skype                   = model.Skype,
                    SocialSecurityID        = model.SocialSecurityID
                };

                EmployeeRepository.Add(employee);
                EmployeeRepository.Commit();
            }

            var employees = EmployeeRepository
                            .Where(x => x.Birthdate.HasValue)
                            .Where(x => x.Birthdate.Value.Month == DateTime.Now.Month && x.Birthdate.Value.Day == DateTime.Now.Day)
                            .AsDto();

            var vacations = VacationRepository
                            .Where(x => x.StartDate.Month == DateTime.Now.Month || x.EndDate.Month == DateTime.Now.Month)
                            .Where(x => x.Status == VacationStatus.Approved)
                            .OrderBy(x => x.StartDate)
                            .Select(x => new EmployeeVacationModel()
            {
                EmployeeName = x.Employee.Name,
                StartDate    = x.StartDate,
                EndDate      = x.EndDate
            })
                            .ToList();

            return(View(MVC.Home.Views.Index, new IndexViewModel()
            {
                Employees = employees, Vacations = vacations
            }));
        }
Beispiel #21
0
 public AuthController(ADService authService)
 {
     this._authService = authService;
 }
Beispiel #22
0
 public AutenticacaoController(Contexto db, ADService aD, Autenticador tiaIdentity)
 {
     this.db          = db;
     this.AD          = aD;
     this.tiaIdentity = tiaIdentity;
 }