// Load user's profile.
        public async Task <IActionResult> Index(string email)
        {
            if (User.Identity.IsAuthenticated)
            {
                // Get users's email.
                email             = email ?? User.FindFirst("preferred_username")?.Value;
                ViewData["Email"] = email;

                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);

                ViewData["Drives"] = await GraphService.GetDrives(graphClient, email, HttpContext);

                ViewData["Picture"] = await GraphService.GetPictureBase64(graphClient, email, HttpContext);

                ViewData["User"] = await GraphService.GetUser(graphClient, email, HttpContext);
            }

            return(View());
        }
Пример #2
0
        public async Task <ActionResult> CreateSubscription()
        {
            if (User.Identity.IsAuthenticated)
            {
                string       identifier          = User.FindFirst(Startup.ObjectIdentifierType)?.Value;
                var          graphClient         = _graphSdkHelper.GetAuthenticatedClient(identifier);
                Subscription createdSubscription = null;

                /// <exercise_hint>
                /// Some hints that can help you.
                /// Creating subscription https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/subscription_post_subscriptions
                /// </exercise_hint>

                /// ADD CODE HERE

                SubscriptionViewModel viewModel = new SubscriptionViewModel
                {
                    Subscription = JsonConvert.DeserializeObject <Models.Subscription>(JsonConvert.SerializeObject(createdSubscription))
                };

                SubscriptionStore.SaveSubscriptionInfo(viewModel.Subscription.Id,
                                                       viewModel.Subscription.ClientState,
                                                       User.FindFirst(Startup.ObjectIdentifierType)?.Value,
                                                       User.FindFirst(Startup.TenantIdType)?.Value);
                subscriptionId = viewModel.Subscription.Id;

                return(View("Subscription", createdSubscription));
            }

            return(View("Subscription", null));
        }
Пример #3
0
        public async Task <IActionResult> Index(string email)
        {
            if (User.Identity.IsAuthenticated)
            {
                // Get users's email.
                email             = email ?? User.FindFirst("preferred_username")?.Value;
                ViewData["Email"] = email;

                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);

                ViewData["Picture"] = await GraphService.GetPictureBase64(graphClient, email, HttpContext);

                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/beta/me/notifications/");

                    // Authenticate (add access token) our HttpRequestMessage
                    await graphClient.AuthenticationProvider.AuthenticateRequestAsync(request);

                    ViewData["Bearer"] = request.Headers.Authorization.ToString();
                }
                catch { }
            }

            return(View());
        }
        public async Task <IActionResult> AzureAdLateralMovement()
        {
            var tenantId = ((ClaimsIdentity)User.Identity)
                           .FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            await CosmosDbHelper.InitializeCosmosDb(tenantId);

            var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

            var azureActiveDirectoryHelper = new AzureActiveDirectoryHelper(graphClient, HttpContext);

            List <string> lateralMovementDataList = null;

            try
            {
                lateralMovementDataList = await azureActiveDirectoryHelper.RunAzureActiveDirectoryApplication();
            }
            catch (ServiceException e)
            {
                if (e.Error.Code == "TokenNotFound")
                {
                    foreach (var cookie in Request.Cookies.Keys)
                    {
                        Response.Cookies.Delete(cookie);
                    }
                    return(RedirectToAction(nameof(Index), "Home"));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction(nameof(Index), "Home"));
            }

            return(View(lateralMovementDataList));
        }
Пример #5
0
        // Send an email message from the current user.
        public async Task <IActionResult> SendEmail(string recipients)
        {
            if (string.IsNullOrEmpty(recipients))
            {
                TempData["Message"] = "Please add a valid email address to the recipients list!";
                return(RedirectToAction("Index"));
            }

            try
            {
                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                // Send the email.
                await GraphService.SendEmail(graphClient, _env, recipients, HttpContext);

                // Reset the current user's email address and the status to display when the page reloads.
                TempData["Message"] = "Success! Your mail was sent.";
                return(RedirectToAction("Index"));
            }
            catch (ServiceException se)
            {
                if (se.Error.Code == "Caller needs to authenticate.")
                {
                    return(new EmptyResult());
                }
                return(RedirectToAction("Error", "Home", new { message = "Error: " + se.Error.Message }));
            }
        }
        //[AllowAnonymous]
        // Load user's profile.
        public async Task <IActionResult> Index(string email)
        {
            if (User.Identity.IsAuthenticated)
            {
                // Get users's email.
                email             = email ?? User.FindFirst("preferred_username")?.Value;
                ViewData["Email"] = email;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

                ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);

                ViewData["Picture"] = await GraphService.GetPictureBase64(graphClient, email, HttpContext);
            }

            return(View());
        }
        public async Task <ActionResult> CreateSubscription()
        {
            if (User.Identity.IsAuthenticated)
            {
                string       identifier          = User.FindFirst(Startup.ObjectIdentifierType)?.Value;
                var          graphClient         = _graphSdkHelper.GetAuthenticatedClient(identifier);
                Subscription createdSubscription = null;
                Subscription subscription        = new Subscription
                {
                    Resource           = "me/messages",
                    ChangeType         = "created,updated",
                    NotificationUrl    = GraphAuthProvider.GetNotificationUrl(),
                    ClientState        = Guid.NewGuid().ToString(),
                    ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 15, 0)
                };

                try
                {
                    createdSubscription = await graphClient.Subscriptions.Request().AddAsync(subscription);
                }
                catch (ServiceException e)
                {
                    string message = e.Message;
                    return(RedirectToAction("Index", "Error", new { message = e.Message, debug = e.Message }));
                }

                SubscriptionViewModel viewModel = new SubscriptionViewModel
                {
                    Subscription = JsonConvert.DeserializeObject <Models.Subscription>(JsonConvert.SerializeObject(createdSubscription))
                };

                SubscriptionStore.SaveSubscriptionInfo(viewModel.Subscription.Id,
                                                       viewModel.Subscription.ClientState,
                                                       User.FindFirst(Startup.ObjectIdentifierType)?.Value,
                                                       User.FindFirst(Startup.TenantIdType)?.Value);
                subscriptionId = viewModel.Subscription.Id;

                return(View("Subscription", createdSubscription));
            }

            return(View("Subscription", null));
        }
        public async Task <ActionResult> Photo(string id, string userId)
        {
            // Initialize the GraphServiceClient.
            var graphClient = _graphSdkHelper.GetAuthenticatedClient(userId);

            string pic = default(string);

            try
            {
                pic = await GraphService.GetGroupPictureBase64(graphClient, id);
            }
            catch (ServiceException e)
            {
                return(Json(new { Message = "An unknown error has occurred." }));
            }

            System.Diagnostics.Debug.WriteLine(_msalLog.GetLog());

            return(Json(new { id = id, photoUrl = pic }));
        }
        public async Task <IActionResult> Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                string email       = "" ?? User.FindFirst("preferred_username")?.Value;
                var    graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);
                await GraphService.GetUserJson(graphClient, email, HttpContext);
            }

            return(View());
        }
        public bool RedirectToSignIn(out ActionResult result)
        {
            if (!User.Identity.IsAuthenticated)
            {
                result = RedirectToAction(actionName: nameof(AccountController.SignIn), controllerName: "Account");
                return(true);
            }

            try
            {
                _graphSdkHelper.GetAuthenticatedClient(User);
            }
            catch
            {
                result = RedirectToAction(actionName: nameof(AccountController.SignOut), controllerName: "Account");
                return(true);
            }

            result = null;
            return(false);
        }
 private async Task <DeltaFiles> GetRootFilesAsync(IGraphSdkHelper helper, string deltaToken)
 {
     try
     {
         var client = helper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);
         return(await client.GetRootFilesAsync(deltaToken));
     }
     catch (ServiceException se) when(se.Error.Code == "TokenNotFound")
     {
         // May be token cache has been lost
         return(null);
     }
 }
Пример #12
0
        public async Task <IActionResult> Index(string email)
        {
            UserModel userModel = null;

            if (User.Identity.IsAuthenticated)
            {
                // Get user's id for token cache.
                var identifier = User.FindFirst(GraphAuthProvider.ObjectIdentifierType)?.Value;

                userModel = base.GetUserModelFromCache(identifier);

                if (userModel == null)
                {
                    // Get users's email.
                    email = email ?? User.Identity.Name ?? User.FindFirst("preferred_username").Value;

                    // Initialize the GraphServiceClient.
                    var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                    var userData = await GraphService.GetUserJson(graphClient, email, HttpContext);

                    var userObject = JsonConvert.DeserializeObject <User>(userData);

                    userModel = new UserModel
                    {
                        Id    = identifier,
                        Name  = userObject.DisplayName,
                        Email = userObject.Mail
                    };

                    var pic = await GraphService.GetPictureBase64(graphClient, email, HttpContext);

                    userModel.PictureBase64 = pic;

                    // dont store an empty model
                    if (!string.IsNullOrEmpty(userModel.Name))
                    {
                        base.SaveUserModelInCache(userModel);
                    }
                }

                base.CopyUserModelToViewData(identifier);

                System.Diagnostics.Debug.WriteLine(_msalLog.GetLog());
            }

            return(View());
        }
        // GET: Group
        public async Task <ActionResult> Index()
        {
            List <GroupListItemViewModel> data = new List <GroupListItemViewModel>();

            // Get user's id for token cache.
            var identifier = User.FindFirst(GraphAuthProvider.ObjectIdentifierType)?.Value;

            base.CopyUserModelToViewData(identifier);

            // Initialize the GraphServiceClient.
            var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

            try
            {
                var groupsData = await GraphService.GetGroups(graphClient, HttpContext);

                foreach (var group in groupsData)
                {
                    data.Add(new GroupListItemViewModel
                    {
                        Key          = group.Id,
                        Description  = group.Description,
                        GroupType    = String.Join(" ", group.GroupTypes),
                        Name         = group.DisplayName,
                        MailNickname = group.MailNickname,
                        Thumbnail    = "",
                        Visibility   = group.Visibility
                    });
                }
            }
            catch (ServiceException e)
            {
                switch (e.Error.Code)
                {
                case "Authorization_RequestDenied":
                    return(new RedirectResult("/Account/PermissionsRequired"));

                default:
                    //return JsonConvert.SerializeObject(new { Message = "An unknown error has occurred." }, Formatting.Indented);
                    var x = e.ToString();
                    break;
                }
            }

            System.Diagnostics.Debug.WriteLine(_msalLog.GetLog());

            return(View(data));
        }
Пример #14
0
        private async Task <HttpResponseMessage> ProcessRequestAsync(string method, string all, object content)
        {
            var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

            var qs  = HttpContext.Request.QueryString;
            var url = $"{GetBaseUrlWithoutVersion(graphClient)}/{all}{qs.ToUriComponent()}";

            var request = new BaseRequest(url, graphClient, null)
            {
                Method      = method,
                ContentType = HttpContext.Request.ContentType,
            };

            var neededHeaders = Request.Headers.Where(h => h.Key.ToLower() == "if-match").ToList();

            if (neededHeaders.Count() > 0)
            {
                foreach (var header in neededHeaders)
                {
                    request.Headers.Add(new HeaderOption(header.Key, string.Join(",", header.Value)));
                }
            }

            var contentType = "application/json";

            try
            {
                using (var response = await request.SendRequestAsync(content?.ToString(), CancellationToken.None, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false))
                {
                    response.Content.Headers.TryGetValues("content-type", out var contentTypes);

                    contentType = contentTypes?.FirstOrDefault() ?? contentType;

                    var byteArrayContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                    return(ReturnHttpResponseMessage(HttpStatusCode.OK, contentType, new ByteArrayContent(byteArrayContent)));
                }
            }
            catch (ServiceException ex)
            {
                return(ReturnHttpResponseMessage(ex.StatusCode, contentType, new StringContent(ex.Error.ToString())));
            }
        }
Пример #15
0
        public async Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var email = string.Empty;

            try
            {
                var config = _httpContextAccessor.HttpContext.RequestServices.GetRequiredService <IConfiguration>();
                var ret    = new Dictionary <string, string>();
                config.GetSection("UserPermissions").GetChildren().ToList().ForEach(x => ret.Add(x.Key, x.Value));
                var claims = ret.Select(x => new Claim("UserPremission", x.Key)).ToList();

                var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)principal.Identity);
                email = principal.GetEmailAddress();

                var groups    = await graphClient.Users[email].MemberOf.Request().GetAsync();
                var groupList = new List <string>();
                foreach (var g in groups.CurrentPage)
                {
                    if (g.GetType() == typeof(Group))
                    {
                        var role = g as Group;
                        groupList.Add(role.DisplayName);
                    }
                    else if (g.GetType() == typeof(DirectoryRole))
                    {
                        var role = g as DirectoryRole;
                        groupList.Add(role.DisplayName);
                    }
                }

                if (groupList.Any(x => x == "TMSMaster" || x == "TMSAdmin"))
                {
                    _logger.LogInformation($"Adding claims to user: {string.Join("; ", claims.Select(x => x.Value).ToArray())}");
                    ((ClaimsIdentity)principal.Identity).AddClaims(claims);
                }
            }
            catch (ServiceException e)
            {
                switch (e.Error.Code)
                {
                case "Request_ResourceNotFound":
                case "ResourceNotFound":
                case "ErrorItemNotFound":
                case "itemNotFound":
                    _logger.LogError($"Error: {e.Error.Code}, {JsonConvert.SerializeObject(new { Message = $"User '{email}' was not found." }, Formatting.Indented)}");
                    break;

                case "ErrorInvalidUser":
                    _logger.LogError($"Error: {e.Error.Code}, {JsonConvert.SerializeObject(new { Message = $"The requested user '{email}' is invalid." }, Formatting.Indented)}");
                    break;

                case "AuthenticationFailure":
                    _logger.LogError($"Error: {e.Error.Code}, {JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)}");
                    break;

                case "TokenNotFound":
                    await _httpContextAccessor.HttpContext.ChallengeAsync();

                    _logger.LogError($"Error: {e.Error.Code}, {JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented)}");;
                    break;

                default:
                    _logger.LogError($"Error: {e.Error.Code}, {JsonConvert.SerializeObject(new { Message = "An unknown error has occurred." }, Formatting.Indented)}");
                    break;
                }
            }
            return(principal);
        }
 public BaseGraphService(IGraphSdkHelper graphSdkHelper)
 {
     _graphSdkHelper = graphSdkHelper;
     GraphClient     = _graphSdkHelper.GetAuthenticatedClient();
 }
        public async Task <IActionResult> Index(string email)
        {
            UserModel userModel = null;

            if (User.Identity.IsAuthenticated)
            {
                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                userModel = base.GetUserModelFromCache(identifier);

                if (userModel == null)
                {
                    // Get users's email.
                    email = email ?? User.FindFirst("preferred_username").Value;

                    // Initialize the GraphServiceClient.
                    var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);

                    try
                    {
                        var userData = await GraphService.GetUserJson(graphClient, email, HttpContext);

                        var userObject = JsonConvert.DeserializeObject <User>(userData);

                        userModel = new UserModel
                        {
                            Id    = identifier,
                            Name  = userObject.DisplayName,
                            Email = userObject.Mail
                        };

                        var pic = await GraphService.GetPictureBase64(graphClient, email, HttpContext);

                        userModel.PictureBase64 = pic;

                        // dont store an empty model
                        if (!string.IsNullOrEmpty(userModel.Name))
                        {
                            base.SaveUserModelInCache(userModel);
                        }
                    }
                    catch (ServiceException e)
                    {
                        switch (e.Error.Code)
                        {
                        case "Authorization_RequestDenied":
                            return(new RedirectResult("/Account/PermissionsRequired"));

                        default:
                            return(new RedirectResult($"/Home/Error?msg={e.Error.Message}"));
                        }
                    }
                }

                base.CopyUserModelToViewData(identifier);

                System.Diagnostics.Debug.WriteLine(_msalLog.GetLog());
            }

            return(View());
        }
Пример #18
0
        // Load user's profile.
        public async Task <IActionResult> Index(int page = 1, int row = 10)
        {
            if (User.Identity.IsAuthenticated)
            {
                // Initialize the GraphServiceClient.
                graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);



                var events = await graphClient.Me.Events
                             .Request().Top(100)
                             .Header("Prefer", "outlook.timezone=\"W. Europe Standard Time\"")
                             .Select(e => new
                {
                    e.Subject,
                    e.Body,
                    e.BodyPreview,
                    e.Organizer,
                    e.Attendees,
                    e.Start,
                    e.End,
                    e.Location,
                    e.Id
                })
                             .GetAsync();


                string Datenow = System.DateTime.Now.Date.ToShortDateString();

                var _events = events.Where(e => e.Location.DisplayName != "" && e.Start.DateTime.Split('T')[0].ToString() == Datenow

                                           ).Select(e => new Events {
                    Attendees = e.Attendees, Start = e.Start, End = e.End, IsFull = false, Id = e.Id
                }).ToList();

                var li = _events.Where(e => e.Start.DateTime.Split('T')[0].ToString() == Datenow && (Convert.ToDateTime(e.Start.DateTime.Split('T')[1].ToString()).TimeOfDay >= DateTime.Now.TimeOfDay

                                                                                                     || Convert.ToDateTime(e.End.DateTime.Split('T')[1].ToString()).TimeOfDay >= DateTime.Now.TimeOfDay)).ToList();
                var model = PagingList.Create(li, row, page);

                var m = li.Min(P => P.Start.DateTime);

                Events test = li.Select(a => new Events {
                    Start = a.Start, End = a.End
                })

                              .Where(c => c.Start.DateTime == m).FirstOrDefault();

                if (test != null && Convert.ToDateTime(test.Start.DateTime.Split('T')[1].ToString()).TimeOfDay <= DateTime.Now.TimeOfDay &&
                    Convert.ToDateTime(test.End.DateTime.Split('T')[1].ToString()).TimeOfDay >= DateTime.Now.TimeOfDay)
                {
                    test.IsFull    = true;
                    ViewBag.IsFull = 1;
                }
                else
                {
                    ViewBag.IsFull = 0;
                }

                var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
                if (isAjax)
                {
                    return(PartialView("_Meeting", model));
                }
                else
                {
                    return(View("Index", model));
                }
            }

            return(View());
        }