示例#1
0
        public async Task <ActionResult> Index()
        {
            ActiveDirectoryClient activeDirectoryClient = GraphHelper.ActiveDirectoryClient();
            var users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(GraphHelper.UserObjectId)).ExecuteAsync();

            IUser user = users.CurrentPage.ToList().First();

            return(View(user));
        }
        public bool AuthorizeRequest(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            string userObjectId = GraphHelper.UserObjectId;

            if (AuthorizedUsersCache.Instance.Contains(userObjectId))
            {
                return(true);
            }
            else
            {
                try
                {
                    ActiveDirectoryClient activeDirectoryClient = GraphHelper.ActiveDirectoryClient();
                    List <string>         userRoles             = new List <string>();

                    // earnit-admin security group
                    bool?isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Admin], GraphHelper.UserObjectId)).Result;
                    if (isUserInRole.GetValueOrDefault(false))
                    {
                        userRoles.Add(Config.Roles.Admin);
                    }

                    // earnit security group
                    isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.User], GraphHelper.UserObjectId)).Result;
                    if (isUserInRole.GetValueOrDefault(false))
                    {
                        userRoles.Add(Config.Roles.User);
                    }

                    // earnit-support security group
                    isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Support], GraphHelper.UserObjectId)).Result;
                    if (isUserInRole.GetValueOrDefault(false))
                    {
                        userRoles.Add(Config.Roles.Support);
                    }

                    if (userRoles.Any())
                    {
                        AuthorizedUsersCache.Instance.AddToCache(GraphHelper.UserObjectId, userRoles);
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    if (Config.IsProduction)
                    {
                        Log.Critical(ex, "ActiveDirectoryClient failed in AuthorizeSGAttribute");
                        TelemetryClient telemetry = new TelemetryClient();
                        telemetry.TrackException(ex);
                        return(false);
                    }
                    else
                    {
                        AuthorizedUsersCache.Instance.AddToCache(userObjectId, new List <string> {
                            Config.Roles.Admin
                        });
                        return(true);
                    }
                }
            }

            return(false);
        }
示例#3
0
        public async Task <ActionResult> AddUser()
        {
            ActiveDirectoryClient activeDirectoryClient      = GraphHelper.ActiveDirectoryClient();
            Dictionary <string, IEnumerable <string> > model = new Dictionary <string, IEnumerable <string> >();
            List <string> users  = null;
            var           groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.User])).ExecuteAsync();

            IGroupFetcher retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group;

            if (retrievedGroupFetcher != null)
            {
                users = new List <string>();
                IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync();

                do
                {
                    List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                    foreach (IDirectoryObject member in directoryObjects)
                    {
                        if (member is User)
                        {
                            User user = member as User;
                            users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName));
                        }
                        else if (member is Group)
                        {
                            Group group = member as Group;
                            users.Add(string.Format("{0}, (Group)", group.DisplayName));
                        }
                        else if (member is Contact)
                        {
                            Contact contact = member as Contact;
                            users.Add(string.Format("{0}, (Contact)", contact.DisplayName));
                        }
                    }
                    members = members.GetNextPageAsync().Result;
                } while (members != null);
            }

            model.Add(Config.Roles.User, users);
            users  = null;
            groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.Admin])).ExecuteAsync();

            retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group;
            users = new List <string>();
            if (retrievedGroupFetcher != null)
            {
                users = new List <string>();
                IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync();

                do
                {
                    List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                    foreach (IDirectoryObject member in directoryObjects)
                    {
                        if (member is User)
                        {
                            User user = member as User;
                            users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName));
                        }
                        if (member is Group)
                        {
                            Group group = member as Group;
                            users.Add(string.Format("Group - {0}", group.DisplayName));
                        }
                        if (member is Contact)
                        {
                            Contact contact = member as Contact;
                            users.Add(string.Format("Contact - {0}", contact.DisplayName));
                        }
                    }
                    members = members.GetNextPageAsync().Result;
                } while (members != null);
            }

            model.Add(Config.Roles.Admin, users);

            users  = null;
            groups = await activeDirectoryClient.Groups.Where(group => group.ObjectId.Equals(Config.SecurityGroups[Config.Roles.Support])).ExecuteAsync();

            retrievedGroupFetcher = groups.CurrentPage.FirstOrDefault() as Group;
            users = new List <string>();
            if (retrievedGroupFetcher != null)
            {
                users = new List <string>();
                IPagedCollection <IDirectoryObject> members = await retrievedGroupFetcher.Members.ExecuteAsync();

                do
                {
                    List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                    foreach (IDirectoryObject member in directoryObjects)
                    {
                        if (member is User)
                        {
                            User user = member as User;
                            users.Add(string.Format("{0}, ({1})", user.DisplayName, user.UserPrincipalName));
                        }
                        if (member is Group)
                        {
                            Group group = member as Group;
                            users.Add(string.Format("Group - {0}", group.DisplayName));
                        }
                        if (member is Contact)
                        {
                            Contact contact = member as Contact;
                            users.Add(string.Format("Contact - {0}", contact.DisplayName));
                        }
                    }
                    members = members.GetNextPageAsync().Result;
                } while (members != null);
            }

            model.Add(Config.Roles.Support, users);
            return(View(model));
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null || httpContext.Session == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if (base.AuthorizeCore(httpContext))
            {
                if (httpContext.Session[Config.IsAuthorized] == null)
                {
                    if (AuthorizedUsersCache.Instance.Contains(GraphHelper.UserObjectId))
                    {
                        httpContext.Session.Add(Config.IsAuthorized, true);
                        httpContext.Session.Add(Config.Role, AuthorizedUsersCache.Instance[GraphHelper.UserObjectId]);
                        return(true);
                    }
                    else
                    {
                        try
                        {
                            ActiveDirectoryClient activeDirectoryClient = GraphHelper.ActiveDirectoryClient();
                            // user thumbnail photo
                            var   users = Task.Run(async() => await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(GraphHelper.UserObjectId)).ExecuteAsync()).Result;
                            IUser user  = users.CurrentPage.ToList().First();
                            if (user.ThumbnailPhoto.ContentType != null)
                            {
                                DataServiceStreamResponse response = Task.Run(async() => await user.ThumbnailPhoto.DownloadAsync()).Result;
                                using (var ms = new MemoryStream())
                                {
                                    response.Stream.CopyTo(ms);
                                    string imageBase64 = Convert.ToBase64String(ms.ToArray());
                                    string image       = string.Format("data:image/gif;base64,{0}", imageBase64);
                                    httpContext.Session.Add(Config.ThumbnailPhoto, image);
                                    httpContext.Response.Cookies.Add(new HttpCookie(Config.ThumbnailPhotoCookie)
                                    {
                                        Secure = true, Value = HttpUtility.UrlEncode(image)
                                    });
                                }
                            }

                            List <string> userRoles = new List <string>();
                            // earnit-admin security group
                            bool?isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Admin], GraphHelper.UserObjectId)).Result;
                            if (isUserInRole.GetValueOrDefault(false))
                            {
                                userRoles.Add(Config.Roles.Admin);
                            }

                            // earnit security group
                            isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.User], GraphHelper.UserObjectId)).Result;
                            if (isUserInRole.GetValueOrDefault(false))
                            {
                                userRoles.Add(Config.Roles.User);
                            }

                            // earnit-support security group
                            isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Support], GraphHelper.UserObjectId)).Result;
                            if (isUserInRole.GetValueOrDefault(false))
                            {
                                userRoles.Add(Config.Roles.Support);
                            }

                            if (userRoles.Any())
                            {
                                httpContext.Session.Add(Config.IsAuthorized, true);
                                httpContext.Session.Add(Config.Role, userRoles);
                                AuthorizedUsersCache.Instance.AddToCache(GraphHelper.UserObjectId, userRoles);
                                return(true);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (Config.IsProduction)
                            {
                                Log.Critical(ex, "ActiveDirectoryClient failed in AuthorizeSGAttribute");
                                TelemetryClient telemetry = new TelemetryClient();
                                telemetry.TrackException(ex);
                            }
                            else
                            {
                                List <string> admin = new List <string> {
                                    Config.Roles.Admin
                                };
                                httpContext.Session.Add(Config.IsAuthorized, true);
                                httpContext.Session.Add(Config.Role, admin);
                                AuthorizedUsersCache.Instance.AddToCache(GraphHelper.UserObjectId, admin);
                                return(true);
                            }
                        }

                        httpContext.Session.Add(Config.IsAuthorized, false);
                        httpContext.Session.Add(Config.Role, new List <string> {
                            Config.Roles.Visitor
                        });
                        AuthorizedUsersCache.Instance.Remove(GraphHelper.UserObjectId);
                    }
                }

                return((bool)httpContext.Session[Config.IsAuthorized]);
            }

            if (!string.IsNullOrWhiteSpace(this.Roles))
            {
                string[]      authorizedRoles = this.Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                List <string> userRoles       = (List <string>)httpContext.Session[Config.Role];

                return(authorizedRoles.Intersect(userRoles).Any());
            }

            return(false);
        }